Creating a new Java program
Note:
In order for Java commands (java
, javac
, etc) to be recognised, you will need to make sure:-
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!");
}
}
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, returnsvoid
meaning it gives no data back to the caller after execution. It acceptsString[]
an (integer indexed) array ofString
s calledargs
.
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 frommain()
.Note: This is unlike C where a return code such as
int
is expected (Java's way isSystem.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]
.
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
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
-
Open Windows Explorer.
-
In the navigation pane on the left right click on "This PC" (or "Computer" for older Windows versions).
-
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.
Alternatively, type
SystemPropertiesAdvanced
(case insensitive) in the Run (Win+R), and hit Enter. -
In the "Advanced" tab of the "System Properties" window select the Environment Variables... button in the lower right corner of the window.
-
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. -
Scroll down the list of "System Variables" and select the
Path
variable. -
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 thePath
variable selected. Add;%JAVA_HOME%\bin
to the end of thePath
variable. -
Keep clicking "OK" and "Apply" until all the windows that you opened are closed.
Check your work
- Open the command prompt by clicking Start then typing
cmd
and pressingEnter
. - 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
-
Retrieve archive(tar.gz/zip) file of desired JDK flavour using wget or manually transfer to required location in Linux machine/vm.
-
Decompress the archive file. e.g.
tar xzvf jdk-7u67-linux-x64.gz
-
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
-
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.
Command line arguments
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.
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 organization
- 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
- On-the-spot error reporting and logging
- Auto-completion when editing code
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 Name | Platforms | Open-Source? | Written in/Created with Java? | Has everything listed above? | Some Additional Features |
---|---|---|---|---|---|
Eclipse | Windows, Mac, Linux (x64/x86) | Yes | Yes | Yes | Comprehensive Plugin System, GUI Builder, Highly Customisable |
NetBeans | Windows, Linux, Mac | Yes | Yes | Yes | Applications based around Modules, Community Based Plugin System, GUI Builder, Customisable, Supports Independent Developers |
IntelliJ IDEA | Windows, Linux, Mac | Yes (Community Edition) | Yes | Yes | Integrated with Git, Comprehensive Version Control, GUI Builder |
jGRASP | Windows, Linux, Mac | Yes | Yes | Yes | Designed to make Source Code more readable (Diagarams Interactions, Workbenches, Viewers), Lightweight |
Geany | Windows, Mac | Yes | No (C) | Yes | Extremely Lightweight, Tag Auto-closing, Plugin Interface |
jDeveloper | Windows, Linux | Yes | Yes | Yes | Provides Oracle Fusion, Contains a full development lifecycle to Simplify Development, Provides a visual and declerative approach to development, GUI Builder |
JCreator | Windows | No | No (C++) | Yes | Quick formatting, Mass Editing, Advanced Edit Commands, Code Templates |
BlueJ | Windows, Ubuntu, Mac, Raspberry Pi | Yes | Yes | Yes | Extension 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.