Creating Your First Java Program

suggest change

Create a new file in your text editor or IDE named HelloWorld.java. Then paste this code block into the file and save:

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

Run live on Ideone

Note: For Java to recognize this as a public class (and not throw a compile time error), the filename must be the same as the class name (HelloWorld in this example) with a .java extension. There should also be a public access modifier before it.

Naming conventions recommend that Java classes begin with an uppercase character, and be in camel case format (in which the first letter of each word is capitalized). The conventions recommend against underscores (_) and dollar signs ($).

To compile, open a terminal window and navigate to the directory of HelloWorld.java:

cd /path/to/containing/folder/

Note: cd is the terminal command to change directory.

Enter javac followed by the file name and extension as follows:

$ javac HelloWorld.java

It is common to get 'javac' is not recognized as an internal or external command, operable program or batch file. even after the JDK is installed and an IDE such as Eclipse can compile. The JDK bin directory is not added to PATH by default.

On Windows, javac.exe is usually under C:\Program Files\Java\jdk(version number)\bin. Quote the path if it contains spaces:

$ "C:\Program Files\Java\jdk1.8.0_xx\bin\javac" HelloWorld.java

Calling javac with no directory is the same command once the operating system knows where javac is. Add that directory to PATH so you do not type it every time.

To edit the PATH environment variable in Windows XP/Vista/7/8/10:

You cannot undo this so be careful. First copy your existing path to notepad. Then to get the exact PATH to your javac browse manually to the folder where javac resides and click on the address bar and then copy it. It should look something like c:\Program Files\Java\jdk1.8.0_xx\bin

In “Variable value” field, paste this IN FRONT of all the existing directories, followed by a semi-colon (;). DO NOT DELETE any existing entries.

Variable name  : PATH
Variable value : c:\Program Files\Java\jdk1.8.0_xx\bin;[Existing Entries...]

Now this should resolve.

For Linux Based systems try here.

Note: The javac command invokes the Java compiler.

The compiler will then generate a bytecode file called HelloWorld.class which can be executed in the Java Virtual Machine (JVM). The Java programming language compiler, javac, reads source files written in the Java programming language and compiles them into bytecode class files. Optionally, the compiler can also process annotations found in source and class files using the Pluggable Annotation Processing API. The compiler is a command line tool but can also be invoked using the Java Compiler API.

To run your program, enter java followed by the name of the class which contains the main method (HelloWorld in our example). Note how the .class is omitted:

$ java HelloWorld

Note: The java command runs a Java application.

This will output to your console:

Hello, World!

You have successfully coded and built your very first Java program!

Note: In order for Java commands (java, javac, etc) to be recognized, you will need to make sure:

You need javac and java from a JDK. To see which versions are installed, run java -version and javac -version. Each command prints that tool's version (for example 1.8.0_73).


A closer look at the Hello World program

The “Hello World” program contains a single file, which consists of a HelloWorld class definition, a main method, and a statement inside the main method.

public class HelloWorld {

The class keyword begins the class definition for a class named HelloWorld. Every Java application contains at least one class definition (Further information about classes).

public static void main(String[] args)  {

This is an entry point (the signature public static void main(String[])) from which the JVM can run your program. An application launched with the java tool needs one. It is:

This main method accepts:

Almost all of this is required for a Java entry point method.

Non-required parts:

Note: A single application may have multiple classes containing an entry point (main) method. The entry point of the application is determined by the class name passed as an argument to the java command.

Inside the main method, we see the following statement:

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

Let’s break down this statement element-by-element:

Element Purpose
System The following expression uses the System class, from the java.lang package.
. The dot operator accesses a class's members1: its fields and methods. This one selects the out static field of System.
out The static PrintStream field of System that represents standard output.
. This dot selects the println method of out.
println A PrintStream method that prints its argument and then a newline.
( Opens the argument list of println.
"Hello, World!" The String literal passed to println. The quotation marks delimit the text.
) Closes the argument list.
; Ends the statement.

Note: Each statement in Java ends with a semicolon (;).

The method body and class body are then closed.

}  // end of main function scope
}      // end of class HelloWorld scope

Here’s another example demonstrating the OO paradigm. Let’s model a football team with one (yes, one!) member. There can be more, but we’ll discuss that when we get to arrays.

First, let’s define our Team class:

public class Team {
    Member member;
    public Team(Member member) {  // who is in this Team?
        this.member = member;  //  one 'member' is in this Team!
    }
}

Now, let’s define our Member class:

class Member {
    private String name;
    private String type;
    private int level; // note the data type here
    private int rank; // note the data type here as well

    public Member(String name, String type, int level, int rank) {
        this.name = name; 
        this.type = type;
        this.level = level;
        this.rank = rank;
    }
}

Why do we use private here? Well, if someone wanted to know your name, they should ask you directly, instead of reaching into your pocket and pulling out your Social Security card. This private does something like that: it prevents outside entities from accessing your variables. You can only return private members through getter functions (shown below).

After putting it all together, and adding the getters and main method as discussed before, we have:

public class Team {
    Member member;
    public Team(Member member) {  
        this.member = member;  
    }

    // here's our main method
    public static void main(String[] args) {
       Member myMember = new Member("Aurieel", "light", 10, 1); 
       Team myTeam = new Team(myMember); 
       System.out.println(myTeam.member.getName());
       System.out.println(myTeam.member.getType());
       System.out.println(myTeam.member.getLevel());
       System.out.println(myTeam.member.getRank());
    }
}

class Member {
    private String name;
    private String type;
    private int level;
    private int rank;

    public Member(String name, String type, int level, int rank) {
        this.name = name; 
        this.type = type;
        this.level = level;
        this.rank = rank;
    }
    
    /* let's define our getter functions here */
    public String getName() { // what is your name?
        return this.name; // my name is ...
    }
   
    public String getType() { // what is your type?
        return this.type; // my type is ...
    }
    
    public int getLevel() { // what is your level?
        return this.level; // my level is ...
    }
    
    public int getRank() { // what is your rank?
        return this.rank; // my rank is
    }
}
Aurieel
light
10
1

Run on ideone

Once again, the main method inside the Team class is the entry point. Without a main method, the JVM has no place to begin execution.


1 - Because the HelloWorld class has little relation to the System class, it can only access public data.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents