Example 1: Write a Java first program to display a message "Hello World".
class First
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Hello World
Save the program with the name "First.java", Open 'Command Prompt', open directory in which you saved the program, and type the following commands:
- javac First.java - to compile the program.
- java First - to execute the program.
Code Explanation:
- class: class is a keyword used to declare a class. As stated earlier, Java is a pure object-oriented programming language therefore, everything must be placed inside a class. A class definition in C++ ends with a semicolon but not in Java.
- void main: This is similar to the main() function in C/C++. Every Java application program must include the main() method. This is the starting point to begin the execution of the program. A Java application can have any number of classes but only one main method.
- { }: Braces or curly brackets define the scope of the program.
- public: The keyword public is an access specifier that declares the main method accessible to all other classes.
- static: static is a keyword, it declare the main method as static means there is no need to create an object to invoke static method. The main must always be declared as static since the interpreter uses this method before any objects are created.
- String args[]: It declares a parameter named args, which contains an array of type String. String[] args is used for command line argument.
- System.out.println(): It is use to print statement.
Valid Java main method signature
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
public static void main(String... args)
static public void main(String args[])
public static final void main(String[] args)
final public static void main(String[] args)
Invalid java main method signature
public void main(String[] args)
static void main(String[] args)
public void static main(String[] args)
abstract public static void main(String[] args)
Example 2: Find Sum of 2 numbers.
class Sum
{
public static void main( String args[] )
{
int a=10, b=20, c;
c = a + b;
System.out.println("Sum = " + c);
}
}
Sum = 30
Having semicolon at the end of class in java is optional.