Java Language


Improvements requested by 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 draft deletes the entire topic.

inline side-by-side expand all collapse all

Examples

  • 159

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

    • JDK is installed (e.g. Oracle)
    • Your environmental variables are properly set up

    java -version and javac -version will report the version (e.g. 1.8.0_73) you have installed if these conditions are satisfied.


    Create a new 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 and class name must be exactly the same. Java classes normally begin with an uppercase character.

    To compile your code, navigate to 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!


    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:

    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 it's name main) from which the JVM can run your program. A Java program needn't have one but the execution can only be started from there.
    This special method is:

    • public meaning that it can be called from elsewhere,
    • static meaning it is not bound to a specific object and can be run by itself, returns
    • void meaning it gives no data back to the caller after execution. It accepts
    • String[] an (integer indexed) array of Strings called args.

    Almost all of this is required for a Java entry point method. The exceptions being the name args which is a variable name so can be called anything.
    (It is also possible to express the array as Varargs, which would look like String... args)

    Note that a single application may have multiple classes having a public static void main (String[] args) method. The actually used entry point of the application (i.e. the main method chosen to be the first executed method of the application) is determined by the class name passed as argument to the java command.

    main() must be declared:

    • public because it is invoked by the JVM whenever the program execution starts and the JVM does not belong to our program package. In order to access main outside the package we have to declare it as public (see also: visibility).

    • static so that JVM does not have to create an object of a class and main method can be called directly (not to use reflection).

    • void because the JVM is not expecting any value from main().

      Note: This is unlike C where a return code such as int is expected (Java's way is System.exit(). The return code is a signal that tells whether the program failed or not.)

    String[] args is for getting command-line arguments that are passed to the program when it is executed. It is not required that you build programs that rely on command line arguments, however the use of command line arguments allows the user to affect operation of the program when it is executed without recompiling it. This is equivalent to C's pair of arguments argc, and argv.

    For an example of a program that uses command line arguments, we could write the following code:

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

    Compile it and then run the HelloWorld application by entering:

    $ java HelloWorld Goodnight Moon
    

    This will output:

    Goodnight, Moon!

    In the main method, Goodnight will be assigned in args[0] and Moon in args[1].

    View Demo

    Note: The command line you have enterred can be translated as such:*

    $ java ApplicationName args[0] args[1] ... args[n]
    

    Note: args[0] will be the first argument passed to the program. If no command line arguments were supplied, args.length will equal zero.

  • Improvements requested by Stephen C:

    • Other: This content really belongs in the Topic on "Installing Java (Standard Edition)". And it should be refactored into separate "examples" for the different ways of installing. - aug 4 at 6:22
    30

    Most Operating Systems (Windows, OS X / macOS, Linux)

    You can install the latest version of the Java Development Kit (JDK) from Oracle's website, or if using Linux, you also have the option to install OpenJDK. Make sure to select a JDK rather than a Java Runtime Environment (JRE), as you won't be able to develop with a JRE.

    If successful, you will be redirected to the JDK downloads page. Read and accept the License Agreement, select your operating system, and download the executable. The installer will walk you through the setup process.

    An important note is that the JDK includes the JRE, so you don't need to download and install a public JRE. Even if you only install a JDK, this will be enough to compile and run Java programs. The JRE has the core commands necessary to run Java (e.g., the java program), and the JDK is a superset of the JRE's commands along with commands to compile Java programs (e.g., javac command). Installing both a JDK and a JRE increases the chance of issues arising from having multiple versions installed.

    More information about the differences between the public JRE and the JRE included within JDK (AKA the private JRE) can be found here.


    Setting up path variable after installing on Windows

    Assumptions:

    • The JDK is already installed.
    • The JDK was installed to the default directory.

    Setup steps

    1. Open Windows Explorer.

    2. In the navigation pane on the left right click on "This PC" (or "Computer" for older Windows versions).

    3. In the newly opened Control Panel window, left click "Advanced System Settings" which should be in the top left corner. This will open the "System Properties" window.enter image description here

      Alternatively, type SystemPropertiesAdvanced (case insensitive) in the Run (Win+R), and hit Enter.

    4. In the "Advanced" tab of the "System Properties" window select the Environment Variables... button in the lower right corner of the window.

    5. Add a New System Variable by clicking the New... button in "System Variables" with the name JAVA_HOME and whose value is the path to the directory where the JDK was installed. After entering these values, press OK.

      JAVA_HOME Environment Variable

    6. Scroll down the list of "System Variables" and select the Path variable.

    7. BE VERY CAREFUL HERE! Windows relies on Path to find important programs. If any or all if it is removed, Windows may not be able to do everything it used to do; however, it must be modified to allow Windows to run the JDK. With this in mind click the "Edit..." button with the Path variable selected. Add ;%JAVA_HOME%\bin to the end of the Path variable.

    8. Keep clicking "OK" and "Apply" until all the windows that you opened are closed.

    Check your work

    1. Open the command prompt by clicking Start then typing cmd and pressing Enter.
    2. Enter javac -version into the prompt. If it was successful, then the version of the JDK will be printed to the screen.

    Note: If you have to try again, close the prompt before checking your work. This will force windows to get the new version of Path.

    Alternately for command line fans, you can install any version of JAVA using Chocolately from within your CMD:

    • Install Chocolately
    • open a CMD instance (command+r and then type cmd)
    • In your cmd type the following command:
      C:\> choco install jdk8
    

    Linux

    The Java Development Kit (JDK) can be installed using a package manager. Open a terminal window, and run the following command to install the JDK.

    apt-get, Debian based Linux distributions (Ubuntu, etc)

    sudo add-apt-repository ppa:webupd8team/java
    sudo apt-get update
    sudo apt-get install oracle-java8-installer
    

    Note: To automatically set up the Java 8 environment variables, you can install the following package:

    sudo apt-get install oracle-java8-set-default
    

    Creating a .deb file

    If you prefer to create the .deb file yourself from the .tar.gz file downloaded from Oracle, do the following (assuming you've downloaded the .tar.gz to ./<jdk>.tar.gz):

    sudo apt-get install java-package # might not be available in default repos
    make-jpkg ./<jdk>.tar.gz # must not be run as root
    sudo dpkg -i *j2sdk*.deb
    

    Note: This requires that the filename be in a particular format (e.g. it must end with .tar.gz).

    slackpkg, Slackware based Linux distributions

    sudo slapt-get install default-jdk
    

    yum, Fedora based Linux distributions (RedHat, CentOS, etc)

    sudo yum install java-1.8.0-openjdk-devel.x86_64
    

    pacman, Arch based Linux distributions

    sudo pacman -S jdk8-openjdk
    

    Using sudo is not required if you're running as the root user.

    Gentoo Linux

    The Gentoo Java guide is maintained by the Gentoo Java team and keeps an updated wiki page including the correct portage packages and USE flags needed.

    Redhat flavours

    Installing JDK from archive file using alternatives

    1. Retrieve archive(tar.gz/zip) file of desired JDK flavour using wget or manually transfer to required location in Linux machine/vm.

    2. Decompress the archive file. e.g.tar xzvf jdk-7u67-linux-x64.gz

    3. Configure java, javac, jar etc.

      e.g.

      alternatives --install /usr/bin/java java /Data/jdk1.7.0_67/bin/java 2

      alternatives --install /usr/bin/javac javac /Data/jdk1.7.0_67/bin/javac 2

    4. Verify if /usr/bin/ is configured under PATH in /etc/profile. If not append to existing PATH variable or create a new profile in /etc/profile.d/( or append to existing application profile). e.g. /etc/profile.d/tomcatprofile.

      Append /usr/bin to PATH variable

      PATH=$PATH:/usr/bin

      export PATH

    To switch between versions use alternatives--config

    e.g. alternatives --config java alternatives --config javac


    Afterwards

    Once you think you have Java installed, you should confirm that your system has JRE by typing in the terminal:

    java -version
    

    To confirm JDK presence instead run the following command:

    javac -version
    

    If the proper version number is returned without errors, your computer has been correctly configured for Java! If you get an error similar to "Command not recognized", you will need to put your Java bin file path into the Path environmental variable. For example, in Unix like systems, add these lines to your ~/.bash_profile or ~/.bashrc, if you're using bash:

    JAVA_HOME=$HOME/bin/jdk/current
    PATH=$JAVA_HOME/bin:$PATH
    
    export JAVA_HOME
    export PATH
    

    Source the file, e.g. [usr@sys ~]$ source .bash_profile. Note well, the changes will only be available to this particular shell. Reboot or re-login to apply the changes completely.

    What is the difference between JDK and JRE?

  • 6

    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 ";
          
            // Check if there is an argument in the first "slot" (0)
            // of the args array:
            if (args.length > 0) {
                // If existing, add it to the message:
                message = message + args[0];
            }
          
            // Check if there is an argument in the second "slot" (1) 
            // of the args array:
            if (args.length > 1) {
                // If existing, add it to the message:
                message = message + args[1];
            }
    
            // 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 question about Compile and run your first Java program? Ask Question

Creating a new Java program

159

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

  • JDK is installed (e.g. Oracle)
  • Your environmental variables are properly set up

java -version and javac -version will report the version (e.g. 1.8.0_73) you have installed if these conditions are satisfied.


Create a new 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 and class name must be exactly the same. Java classes normally begin with an uppercase character.

To compile your code, navigate to 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!


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:

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 it's name main) from which the JVM can run your program. A Java program needn't have one but the execution can only be started from there.
This special method is:

  • public meaning that it can be called from elsewhere,
  • static meaning it is not bound to a specific object and can be run by itself, returns
  • void meaning it gives no data back to the caller after execution. It accepts
  • String[] an (integer indexed) array of Strings called args.

Almost all of this is required for a Java entry point method. The exceptions being the name args which is a variable name so can be called anything.
(It is also possible to express the array as Varargs, which would look like String... args)

Note that a single application may have multiple classes having a public static void main (String[] args) method. The actually used entry point of the application (i.e. the main method chosen to be the first executed method of the application) is determined by the class name passed as argument to the java command.

main() must be declared:

  • public because it is invoked by the JVM whenever the program execution starts and the JVM does not belong to our program package. In order to access main outside the package we have to declare it as public (see also: visibility).

  • static so that JVM does not have to create an object of a class and main method can be called directly (not to use reflection).

  • void because the JVM is not expecting any value from main().

    Note: This is unlike C where a return code such as int is expected (Java's way is System.exit(). The return code is a signal that tells whether the program failed or not.)

String[] args is for getting command-line arguments that are passed to the program when it is executed. It is not required that you build programs that rely on command line arguments, however the use of command line arguments allows the user to affect operation of the program when it is executed without recompiling it. This is equivalent to C's pair of arguments argc, and argv.

For an example of a program that uses command line arguments, we could write the following code:

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

Compile it and then run the HelloWorld application by entering:

$ java HelloWorld Goodnight Moon

This will output:

Goodnight, Moon!

In the main method, Goodnight will be assigned in args[0] and Moon in args[1].

View Demo

Note: The command line you have enterred can be translated as such:*

$ java ApplicationName args[0] args[1] ... args[n]

Note: args[0] will be the first argument passed to the program. If no command line arguments were supplied, args.length will equal zero.

Installing Java Development Kit

30

Most Operating Systems (Windows, OS X / macOS, Linux)

You can install the latest version of the Java Development Kit (JDK) from Oracle's website, or if using Linux, you also have the option to install OpenJDK. Make sure to select a JDK rather than a Java Runtime Environment (JRE), as you won't be able to develop with a JRE.

If successful, you will be redirected to the JDK downloads page. Read and accept the License Agreement, select your operating system, and download the executable. The installer will walk you through the setup process.

An important note is that the JDK includes the JRE, so you don't need to download and install a public JRE. Even if you only install a JDK, this will be enough to compile and run Java programs. The JRE has the core commands necessary to run Java (e.g., the java program), and the JDK is a superset of the JRE's commands along with commands to compile Java programs (e.g., javac command). Installing both a JDK and a JRE increases the chance of issues arising from having multiple versions installed.

More information about the differences between the public JRE and the JRE included within JDK (AKA the private JRE) can be found here.


Setting up path variable after installing on Windows

Assumptions:

  • The JDK is already installed.
  • The JDK was installed to the default directory.

Setup steps

  1. Open Windows Explorer.

  2. In the navigation pane on the left right click on "This PC" (or "Computer" for older Windows versions).

  3. In the newly opened Control Panel window, left click "Advanced System Settings" which should be in the top left corner. This will open the "System Properties" window.enter image description here

    Alternatively, type SystemPropertiesAdvanced (case insensitive) in the Run (Win+R), and hit Enter.

  4. In the "Advanced" tab of the "System Properties" window select the Environment Variables... button in the lower right corner of the window.

  5. Add a New System Variable by clicking the New... button in "System Variables" with the name JAVA_HOME and whose value is the path to the directory where the JDK was installed. After entering these values, press OK.

    JAVA_HOME Environment Variable

  6. Scroll down the list of "System Variables" and select the Path variable.

  7. BE VERY CAREFUL HERE! Windows relies on Path to find important programs. If any or all if it is removed, Windows may not be able to do everything it used to do; however, it must be modified to allow Windows to run the JDK. With this in mind click the "Edit..." button with the Path variable selected. Add ;%JAVA_HOME%\bin to the end of the Path variable.

  8. Keep clicking "OK" and "Apply" until all the windows that you opened are closed.

Check your work

  1. Open the command prompt by clicking Start then typing cmd and pressing Enter.
  2. Enter javac -version into the prompt. If it was successful, then the version of the JDK will be printed to the screen.

Note: If you have to try again, close the prompt before checking your work. This will force windows to get the new version of Path.

Alternately for command line fans, you can install any version of JAVA using Chocolately from within your CMD:

  • Install Chocolately
  • open a CMD instance (command+r and then type cmd)
  • In your cmd type the following command:
  C:\> choco install jdk8

Linux

The Java Development Kit (JDK) can be installed using a package manager. Open a terminal window, and run the following command to install the JDK.

apt-get, Debian based Linux distributions (Ubuntu, etc)

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

Note: To automatically set up the Java 8 environment variables, you can install the following package:

sudo apt-get install oracle-java8-set-default

Creating a .deb file

If you prefer to create the .deb file yourself from the .tar.gz file downloaded from Oracle, do the following (assuming you've downloaded the .tar.gz to ./<jdk>.tar.gz):

sudo apt-get install java-package # might not be available in default repos
make-jpkg ./<jdk>.tar.gz # must not be run as root
sudo dpkg -i *j2sdk*.deb

Note: This requires that the filename be in a particular format (e.g. it must end with .tar.gz).

slackpkg, Slackware based Linux distributions

sudo slapt-get install default-jdk

yum, Fedora based Linux distributions (RedHat, CentOS, etc)

sudo yum install java-1.8.0-openjdk-devel.x86_64

pacman, Arch based Linux distributions

sudo pacman -S jdk8-openjdk

Using sudo is not required if you're running as the root user.

Gentoo Linux

The Gentoo Java guide is maintained by the Gentoo Java team and keeps an updated wiki page including the correct portage packages and USE flags needed.

Redhat flavours

Installing JDK from archive file using alternatives

  1. Retrieve archive(tar.gz/zip) file of desired JDK flavour using wget or manually transfer to required location in Linux machine/vm.

  2. Decompress the archive file. e.g.tar xzvf jdk-7u67-linux-x64.gz

  3. Configure java, javac, jar etc.

    e.g.

    alternatives --install /usr/bin/java java /Data/jdk1.7.0_67/bin/java 2

    alternatives --install /usr/bin/javac javac /Data/jdk1.7.0_67/bin/javac 2

  4. Verify if /usr/bin/ is configured under PATH in /etc/profile. If not append to existing PATH variable or create a new profile in /etc/profile.d/( or append to existing application profile). e.g. /etc/profile.d/tomcatprofile.

    Append /usr/bin to PATH variable

    PATH=$PATH:/usr/bin

    export PATH

To switch between versions use alternatives--config

e.g. alternatives --config java alternatives --config javac


Afterwards

Once you think you have Java installed, you should confirm that your system has JRE by typing in the terminal:

java -version

To confirm JDK presence instead run the following command:

javac -version

If the proper version number is returned without errors, your computer has been correctly configured for Java! If you get an error similar to "Command not recognized", you will need to put your Java bin file path into the Path environmental variable. For example, in Unix like systems, add these lines to your ~/.bash_profile or ~/.bashrc, if you're using bash:

JAVA_HOME=$HOME/bin/jdk/current
PATH=$JAVA_HOME/bin:$PATH

export JAVA_HOME
export PATH

Source the file, e.g. [usr@sys ~]$ source .bash_profile. Note well, the changes will only be available to this particular shell. Reboot or re-login to apply the changes completely.

What is the difference between JDK and JRE?

Command line arguments

6

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 ";
      
        // Check if there is an argument in the first "slot" (0)
        // of the args array:
        if (args.length > 0) {
            // If existing, add it to the message:
            message = message + args[0];
        }
      
        // Check if there is an argument in the second "slot" (1) 
        // of the args array:
        if (args.length > 1) {
            // If existing, add it to the message:
            message = message + args[1];
        }

        // 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!.

Choosing a Java I.D.E.

2

So, you want to start creating more programs in Java? Want your life to be a bit easier? Then try using an Integrated Development Environment - an editor specifically designed for programming (in this case, Java).

They surpass a default text editor in many ways. Here are some of those ways that most, if not all, IDEs provide:

  • Syntax Highlighting and Formatting for organizationExample of Syntax Highlighting
  • Compiling with the click of a run button (no need to go into command-line and use javac)
  • Hierarchy and organization for Files, Classes, and Packages Eclipse package explorer
  • On-the-spot error reporting and logging Eclipse Error Log
  • Auto-completion when editing code

Simple Auto-completion

Here's a comparison of the most common Java I.D.E.s. They all have similar features, such as the ones listed above, but are slightly different.

IDE NamePlatformsOpen-Source?Written in/Created with Java?Has everything listed above?Some Additional Features
EclipseWindows, Mac, Linux (x64/x86)YesYesYesComprehensive Plugin System, GUI Builder, Highly Customisable
NetBeansWindows, Linux, MacYesYesYesApplications based around Modules, Community Based Plugin System, GUI Builder, Customisable, Supports Independent Developers
IntelliJ IDEAWindows, Linux, MacYes (Community Edition)YesYesIntegrated with Git, Comprehensive Version Control, GUI Builder
jGRASPWindows, Linux, MacYesYesYesDesigned to make Source Code more readable (Diagarams Interactions, Workbenches, Viewers), Lightweight
GeanyWindows, MacYesNo (C)YesExtremely Lightweight, Tag Auto-closing, Plugin Interface
jDeveloperWindows, LinuxYesYesYesProvides Oracle Fusion, Contains a full development lifecycle to Simplify Development, Provides a visual and declerative approach to development, GUI Builder
JCreatorWindowsNoNo (C++)YesQuick formatting, Mass Editing, Advanced Edit Commands, Code Templates
BlueJWindows, Ubuntu, Mac, Raspberry PiYesYesYesExtension System, Designed for Teaching, Portable, Custom Method Editor

Take a look at the table above and choose which one would best suit your needs mostly based on the additional features.

Topic Outline