i

JAVA Complete Course

First Java Program

In this example, I will try to show two different ways of writing very first Java program. Usually, over the internet it is printing “Hello World” in console for every programming language. Let’s change this approach and print something different.

The first demonstration will be running the program within the IntelliJ Idea.

To write the Java program we need class which will have main method. We will speak about it in next chapters but to say shortly, main method is the starting point for every Java application. Without it we cannot run our java program.

Let’s create a class called MyFirstJavaProgram and main method inside it. In main method we will have only one statement System.out.println(“This is my first java program”). System is the class provided by Java library and the method println is printing passed text and moves cursor to next line.

 

 

Number 1 and Number 2 steps are used to run the program. They are interchangeable so it is up to us which one we want to use. Number 3 is the output of this program. One thing is that every Java program should be compiled and Java file will be converted to class file which will be executed. If we run our application within the Idea, it will make all the steps by itself, but if we try to run our application with command line, first we need to compile this file and then run.

Let’s see this example as well. First we need to go to directory where we have our class and compile it. To go to directory we need to use the commands based on our operational system.

After compiling our file we need to go to project root directory and instead of src folder we need to go to out/production/PROJECT NAME folder and then the same directory structure as we have in Idea. When we go there we will find the same file with .class extension, in our case MyFirstJavaProgram.class

To run this compiled file we need to use java command instead of javac

java MyFirstJavaProgram.class

Please keep in mind that we need to set also CLASSPATH properly,