Java Language


Improvements requested by Braiam, 3751_Creator:

  • Other: - We got to decide on ONE type of formatting (eg output of an example, decide on ONE site to use for code simulation) - Clean up duplicates (eg command line args (end of "Creating a new Java program" and page "Command line args)) - Aug 1 at 16:09
  • This topic duplicates material from other topics, is deprecated, is obsolete, or is otherwise superfluous. - Aug 31 at 17:34

This draft deletes the entire topic.

inline side-by-side expand all collapse all

Examples

  • 169

    Create a new text file named HelloWorld.java and paste this code in it:

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

    Run live on Ideone

    Note: In order for Java to recognise this as a class (and not throw a compiler error), the filename must comprise the name of the class with a .java extension. Convention states that Java classes should begin with an uppercase character.

    To compile your code, open the directory where HelloWorld.java is located in a terminal window:
    cd /path/to/containing/folder/ and enter javac followed by the file name and extension as follows:

    $ javac HelloWorld.java
    

    Note: The javac command is the Java compiler.

    The compiler will then generate a bytecode file called HelloWorld.class which can be executed in the Java Virtual Machine (JVM).

    Next enter java, followed by the name of the class with the main method (HelloWorld in our example).:

    $ java HelloWorld
    

    Note: The java command runs a Java application.

    This will output:

    Hello, World!

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

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

    • A JDK is installed (e.g. Oracle, OpenJDK and other sources)
    • Your environment variables are properly set up

    You will need to use a compiler (javac) and an executor (java) provided by your JVM. java -version and javac -version on the command line, will report which versions (e.g. 1.8.0_73) of these are installed.


    A closer look at the Hello World application

    The Hello World application consists of a HelloWorld class definition and a main method.

    The HelloWorld class definition:

    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).

    The main method:

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

    This is an entry point method (defined by its name main) from which the JVM can run your program. Every Java program should have one. It is:

    • public: meaning where the method can be called from isn't limited to inside your program.
    • static: meaning it exists and can be run by itself (at the class level without creating an object).
    • void: meaning it returns no value. Note: This is unlike C where a return code such as int is expected (Java's way is System.exit()).

    It accepts :

    • An array (called args) of Strings used to pass arguments into your program (e.g. from command line arguments).

    Almost all of this is required for a Java entry point method. The exceptions being:

    • The name args is a variable name, so can be called anything.
    • Whether its type is an array or Varargs (String... args).

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

  • 9

    In Java you can pass command line arguments to the application by appending them after the main class separated by spaces, in the general form:

    java ClassName [arg0] [arg1] [arg2] [arg3] ...
    

    where ClassName is the name of the class, [arg0] is the first command line argument which will be inputted as args[0], [arg1] is the second command line input which will be inputted as args[1], and so on.

    Note that command line arguments are all optional: there need not be any arguments, nor is there a limit to command line arguments, although there are some limitations to the maximum size of command line arguments in Windows, Linux or other UNIX based operating systems.

    In the Java program, these can be accessed from the args parameter, which is of type String[] (a String array), that is passed to the main() method, the entry point of the Java program.


    Full Example

    public class SayHello {
    
        public static void main(String[] args) { // args is a set of command line arguments
    
            // First part of a statement:
            String message = "Hello ";
          
            // append all arguments to the message
            for(int i = 0; i < args.length; i++) {
              message = message + args[i] + ' ';
            }
    
            // Finally, display the message:
            System.out.println(message);
        }
    }
    

    In the example above you can run the Java application with two parameters. In the example below, Mr. is the first parameter, and Smith is the second.

    java SayHello Mr. Smith
    

    The output will be

    Hello Mr. Smith
    

    This because the program takes the first and second arguments, supplied from the command and prints them out.

    A breakdown of the command:

    SayHello: The program we are running

    "Mr.": The string put into the array args[0] from the main method

    "Smith": The string put into args[1]


    Conversion to Other Types

    Because the args parameter is of type String[] (a String array), all of the arguments will be entered as strings. Types will have to be converted, with their classes' respective methods. For example, to run the following command and have the input parameters converted into their respective types:

    java TypeConverter string 1 3.4 true
    

    (where string should be converted to a String, 1 to an Integer, 3.4 to a Double, and true to a Boolean) you can use their respective constructors (provided that a constructor with a String parameter is provided):

    // args = { "string", "1", "3.4", "true" };
    String s = args[0]; // already a string
    int i = new Integer(args[1]);
    double d = new Double(args[2]);
    bool b = new Boolean(args[3]);
    

    (Note that Integer, Double, and Boolean all have constructors with String representation as parameter.)


    Escaping Spaces

    To "escape" spaces in a parameter, simply encapsulate the parameter in quotation marks.

    For example, to pass the string "Hello, World!" as a parameter, simply pass it with quotation marks. The quotation marks will not be counted as part of the argument. For example, when executing the command:

    java TestSpaces "Hello, World!"
    

    then args[0] will be set to the entire string Hello, World!.

I am downvoting this example because it is...

Remarks

The Java programming language is...

  • General-purpose, which means it is designed to be used for writing software in a wide variety of application domains, and lacks specialized features for any specific domain.

  • Class-based, which means its object structure is defined in classes. Class instances always have those fields and methods specified in their class definitions (see Classes and Objects). This is in contrast to non-class-based languages such as JavaScript.

  • Statically-typed, which means the compiler checks at compile time that variable types are respected. For example, if a method expects an argument of type String, that argument must in fact be a string when the method is called.

  • Object-oriented, which means most things in a Java program are class instances, i.e. bundles of state (fields) and behavior (methods which operate on data and form the object's interface to the outside world).

  • Portable, compile it on one platform and the resultant class files can run on any platform that has a JVM.

Java code is compiled to bytecode (the .class files) which in turn get interpreted by the Java Virtual Machine (JVM). In theory, bytecode created by one Java compiler should run the same way on any JVM, even on a different kind of computer. The JVM might (and in real-world programs will) choose to compile into native machine commands the parts of the bytecode that are executed often. This is called "JIT compilation".

Installing

There is a separate topic on Installing Java (Standard Edition).

Testing

Unlike newer languages (e.g. Go, Rust, Ruby), Java does not have any support for testing in the standard library. If you want to test your code, you will need to use an external testing library. Of those, the two most popular are:

Versions

VersionCode NameRelease Date
Java SE 9 (Early Access)None2017-03-23
Java SE 8None2014-03-18
Java SE 7Dolphin2011-07-28
Java SE 6Mustang2006-12-23
Java SE 5Tiger2004-10-04
Java SE 1.4Merlin2002-02-06
Java SE 1.3Kestrel2000-05-08
Java SE 1.2Playground1998-12-08
Java SE 1.1None1997-02-19
Java SE 1.0Oak1996-01-21
Still have a question about Compile and run your first Java program? Ask Question

Creating a new Java program

169

Create a new text file named HelloWorld.java and paste this code in it:

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

Run live on Ideone

Note: In order for Java to recognise this as a class (and not throw a compiler error), the filename must comprise the name of the class with a .java extension. Convention states that Java classes should begin with an uppercase character.

To compile your code, open the directory where HelloWorld.java is located in a terminal window:
cd /path/to/containing/folder/ and enter javac followed by the file name and extension as follows:

$ javac HelloWorld.java

Note: The javac command is the Java compiler.

The compiler will then generate a bytecode file called HelloWorld.class which can be executed in the Java Virtual Machine (JVM).

Next enter java, followed by the name of the class with the main method (HelloWorld in our example).:

$ java HelloWorld

Note: The java command runs a Java application.

This will output:

Hello, World!

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

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

  • A JDK is installed (e.g. Oracle, OpenJDK and other sources)
  • Your environment variables are properly set up

You will need to use a compiler (javac) and an executor (java) provided by your JVM. java -version and javac -version on the command line, will report which versions (e.g. 1.8.0_73) of these are installed.


A closer look at the Hello World application

The Hello World application consists of a HelloWorld class definition and a main method.

The HelloWorld class definition:

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).

The main method:

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

This is an entry point method (defined by its name main) from which the JVM can run your program. Every Java program should have one. It is:

  • public: meaning where the method can be called from isn't limited to inside your program.
  • static: meaning it exists and can be run by itself (at the class level without creating an object).
  • void: meaning it returns no value. Note: This is unlike C where a return code such as int is expected (Java's way is System.exit()).

It accepts :

  • An array (called args) of Strings used to pass arguments into your program (e.g. from command line arguments).

Almost all of this is required for a Java entry point method. The exceptions being:

  • The name args is a variable name, so can be called anything.
  • Whether its type is an array or Varargs (String... args).

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

Command line arguments

9

In Java you can pass command line arguments to the application by appending them after the main class separated by spaces, in the general form:

java ClassName [arg0] [arg1] [arg2] [arg3] ...

where ClassName is the name of the class, [arg0] is the first command line argument which will be inputted as args[0], [arg1] is the second command line input which will be inputted as args[1], and so on.

Note that command line arguments are all optional: there need not be any arguments, nor is there a limit to command line arguments, although there are some limitations to the maximum size of command line arguments in Windows, Linux or other UNIX based operating systems.

In the Java program, these can be accessed from the args parameter, which is of type String[] (a String array), that is passed to the main() method, the entry point of the Java program.


Full Example

public class SayHello {

    public static void main(String[] args) { // args is a set of command line arguments

        // First part of a statement:
        String message = "Hello ";
      
        // append all arguments to the message
        for(int i = 0; i < args.length; i++) {
          message = message + args[i] + ' ';
        }

        // Finally, display the message:
        System.out.println(message);
    }
}

In the example above you can run the Java application with two parameters. In the example below, Mr. is the first parameter, and Smith is the second.

java SayHello Mr. Smith

The output will be

Hello Mr. Smith

This because the program takes the first and second arguments, supplied from the command and prints them out.

A breakdown of the command:

SayHello: The program we are running

"Mr.": The string put into the array args[0] from the main method

"Smith": The string put into args[1]


Conversion to Other Types

Because the args parameter is of type String[] (a String array), all of the arguments will be entered as strings. Types will have to be converted, with their classes' respective methods. For example, to run the following command and have the input parameters converted into their respective types:

java TypeConverter string 1 3.4 true

(where string should be converted to a String, 1 to an Integer, 3.4 to a Double, and true to a Boolean) you can use their respective constructors (provided that a constructor with a String parameter is provided):

// args = { "string", "1", "3.4", "true" };
String s = args[0]; // already a string
int i = new Integer(args[1]);
double d = new Double(args[2]);
bool b = new Boolean(args[3]);

(Note that Integer, Double, and Boolean all have constructors with String representation as parameter.)


Escaping Spaces

To "escape" spaces in a parameter, simply encapsulate the parameter in quotation marks.

For example, to pass the string "Hello, World!" as a parameter, simply pass it with quotation marks. The quotation marks will not be counted as part of the argument. For example, when executing the command:

java TestSpaces "Hello, World!"

then args[0] will be set to the entire string Hello, World!.

Topic Outline