How to write the first program in JAVA

java

In java every program begins with the class ans that class name must match the filename.

Let’s create our first java program, named First.java, which can be write in any text editor such as notepad, notepad++, etc.

You can also use the IDE (Integrated Development Environment) to write your code.

class First
{
	public static void main(String args[])
	{
		System.out.println("Hello World");
	}
}

Save above code in notepad as “First.java”.

Open command prompt and navigate to directory where you saved your java program and type following.

C:\Users\Your Name>javac First.java

Above statement will compile your java code.

If your program is having error then the error will display on command prompt and if there is no error then command prompt will take to new line, Type below code to run program.

C:\Users\Your Name>java First

The output should as follow:

Hello World

Explanation of above program

Each and every line of code that we want to execute must be inside the class. In our example, we have created a class named First. The class name should always start with the first letter in uppercase.

The name of the java file must be the same as the class name while saving the file save it using the class name and append “.java” to the end of the filename.

public static void main(String[] args)

In the above line of code “public” is an access specifier that defines whether that code is accessible outside of class or not. We’ll learn access specifiers in detail in another tutorial.

“static” is a keyword that is used in the above example so that JVM (Java Virtual Machine) can call the main() without creating any reference variable.

System.out.println("Hello World");

In the above line of code “System” is a final class defined in java.lang.package.

“out” is the instance of PrintStream type which is public and static member of “System” class.

“println()” is the method present in PrintStream class, which is used to print any argument passed to it. After printing the argument it adds a new line to the output.

Leave a Comment

Your email address will not be published. Required fields are marked *