Master java skills

First Java Program

It’s time for us to create our first java program and run it. But before that there are certain requirements that we need to meet in order to run our first java program.

Requirements:

  1. You need to have JDK installed on our machine. If you don’t have, then download from below link. https://www.oracle.com/java/technologies/javase-downloads.html
  2. Set environment variable named ‘path’ and mention the path of jdk bin directory. Click here to set the ‘path’ environment variable. If path is already set for java, skip this step.

First Java Program:

  1. Open a text editor of your choice and write the following program.
public class MyFirstJavaProgram {

	public static void main (String [] args){
		System.out.println("Welcome to Java programming language");
	}
}

2. Save the file with the same name as class name i.e. MyFirstJavaProgram.java

3. Open command prompt and go to the directory (using cd command) where you have saved your java file. In the below example, the file is saved on desktop therefore we have changed the directory to Desktop .

4. Run the below command

javac MyFirstJavaProgram.java

5. Run the below command

java MyFirstJavaProgram

As we can see in the above diagram, the message that we had written in our java program “Welcome to Java programming language” has been printed on the command prompt.

Running the java program from a different directory

If you want to run the same java program, you have to set the classpath.

Classpath tells JVM about the path that needs to be searched for complied java files (.class).

For compilation, run the below command by passing the full path of the java file

To run the program, run the below command. Here cp option represents the classpath (where to look for compiled java files)

Congratultions! You have successfully written and run your first java program. It’s coffee time now. You deserve your cup of coffee. Enjoy!