Can we run a Java program without the main method?
The mainly method is executed when we execute a class in Java. For example, if we have a Main.java file with the following code:
public class Main {
public static void main(String[] args) {
System.out.println("Inside main");
}
}
and if we run this program, it will print the string Inside head.
But if I do the mainly method,
public class Main {
public void hello() {
System.out.println("Inside main");
}
}
An exception is thrown:
Error: Main method not found in class com.company.Main, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
To run a Java program without the main() method:
We can write a Java program without the main method with a static block only up to Java 1.5. A static block is written with the static keyword. This method is executed once the class file is loaded into memory. You need to write your code in the static block:
You can have more than one static block. These blocks are executed before the mainly method. The execution order is similar to the order in which they are added to the class. If you need to perform something before the mainly method is executed, you can add the code in a static block.
So the program below will work (up to Java 1.5):
public class Main {
static {
System.out.println("Inside main");
}
}
For the later Java versions, we have no other way to run a program without the mainly method.
C# Tip: DO NOT use nameof to value constants
Programming in C# involves making numerous decisions to ensure code efficiency and maintainability. One common aspect is dealing with constants,…
Java program to calculate students grades in 2 different ways
Java program to calculate students grades: In this post we will learn different ways to calculate the figure from a student…
C# Tip: LINQ’s Enumerable.Range to generate a range of consecutive numbers
When you need to generate a series of numbers in ascending order, you can simply use a while loop with…
Java String charAt method explanation with examples
Java String charAt method: The signAt method of Java string is used to find a character at a given index. This…
3 Ways to Convert System.nanoTime to Seconds in Java
How to convert System.nanoTime to seconds in Java: In this post we will learn how to convert System.nanoTime Unpleasant seconds in…
4 different Java programs to find the HCF or GCD of two numbers
Java programs to find the HCF or GCD of two numbers: Let’s learn how to find the HCF of two numbers…