Creating your first Java application

Now we are going to create, compile and run your first Java application. This example requires only text editor, but for next lessons I recommend you to install an IDE, because it makes writing code simpler and faster.

Writing a code

Create a file named Hello.java. If you have troubles with adding right file extension just enable it in file properties (for Windows).

Open the created file in text-editor of your choice and add the following lines:

public class Hello {

    public static void main(String... args) {
        System.out.println("Hello world");
    }
}

This is the short and simple example of java application which only purpose is to print “Hello world” into console. Here we have a class Hello (we’ll talk about classes later) which contains the only method (or function) named main. main method is an entry point of any java application. So every java application should have at least one main method. Curly brackets identify blocks that belong to classes and methods, so you can see that method main belongs to class Hello and line System.out.println<em>(</em>"Hello world"<em>)</em>; belongs to method main.

In other sources you may also see main method version with String[] args instead of String... args, in this context both work same.

Compilation

Save your Hello.java. Open command line tool. Then enter:

javac {path_to_your_java_file}/Hello.java

Instead of {path_to_your_java_file} insert absolute path to Hello.java. For example, in my case it would be:

javac C:/Projects/Juravine/code/Hello.java

It will instruct java to compile your Hello.java file. Look, now you have a file Hello.class in same directory where Hello.java is. This file contains generated java bytecode and is not very readable (but you can try 🙂 ).

If you have troubles with calling javac command, please check that you have configured system environment variables correctly.

Running your application

Now lets run our application. In command line tool enter:

java -cp {path_to_your_class_file} Hello

This will run your java application and you’ll see its output “Hello world” in the console.

You can find source code here.

Scroll to Top