The topics for this section are the following:
Create an executable Java program with a main class
Java application programs run in a standalone environment with the support of a virtual machine (JVM), the program starts up using a single thread called the main thread, the main thread is importanmt because
You can get details of this thread (just like another thread) using the methods of the Thread class (for example Thread.currentThread())
At a minmum a Java program has to have one class which contains a main method, it is this entry that the JVM will start executing code
Example of a simple Java program | class HelloWorld { // Java's entry point public static void main(String[] args) { System.out.println("This executes"); } } |
There are a number of source file declaration rules that must be followed, some topics I will be covering later
Declaration Rules |
|
Package | package uk.co.datadisk;
package com.javaguru; // Only one package allowed, compiler error
Note: only one package declaration per source code file |
Import |
import java.util.*; // Using wildcard also known as import-on-demand
import uk.co.datadisk.fooClass; // a specific class also know as single-type-input
Note: import statements must be below package declaration and above the class declaration, you can have as many as you want. Import statements have no performance hits and they do not increase the file size. |
Public Class | public class fooClass { /* any code that you want */ } Note: you can only have one public class declaration, the order of the public class makes no difference, the filename should match the public class name. It is possible to have a file with no public classes. |
Static | public static void main(String[] args) |
Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real life entities. A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type.
In real life we have many objects (people, cars, dogs, cats, buildings, etc), Object Oriented Program (OOP) reflects real life objects, in Java programming many objects are created, an object conists of the below:
There are a number of class rules that must be followed
As I mentioned above the main method is used to start the program running, this method will create objects that is required by the program, examples of the main method signature can be seen below:
Examples of a main method | // Mostly commonly used main signature public static void main(String[] args) // Other valid main method signatures public static void main(String args[]) public static void main(String []args) public static void main(String... args) public static void main(String...args) public static void main(final String[] args) public static void main(String[] hello) public static void main(String[] vars) public static void main(String[] args) throws Exception public static void main(String[] args) throws RunTimeException public static void main(String[] args) throws Throwable public static void main(String[] args) throws Error |
In Java it is wise to add lots of comments to remind you what the program does, it helps you especially when you need to change code at a later date
Single line comment | // This is a single line comment |
Multi-line comment | /* This is a multi-line comment and will be ignored by the compiler */ |
You can pass commandline arguments to your Java program, I will shortly give you examples of this soon, but below is a program example that uses arguments passed in from the commandline
Example of a simple Java program | public class PrintArgs { public static void main(String[] args) { System.out.println("Number of args is: " + args.length); System.out.println("Printing some arguments in this code: "); // Loop through arguments passed and print them to standard output for (int i = 0; i < args.length; i++) { System.out.println("Argument " + (i + 1) + ": " + args[i]); } } } |
Compile and run a Java program from the command line
There are a common set of tools that you can use when developing in Java from running, compiling, packaging (Jar file), documentation, etc I provide a table below of the most commonly used:
Commonly used Commandline tools |
|
Running | java [--class-path, --classpath, -cp] java [-verbose:class] java [-verbose:gc] java Test # Run a java program without a package configured java Test arg1 arg2 arg3 # Run a java program without a package configured and pass 3 arguments java uk.co.datadisk.Test # Run a java program with a package of uk.co.datadisk, remember you are running from the root directory uk/co/datadisk, dont from from inside uk/co/datadisk the same directory as the class java uk.co.datadisk.Test arg1 arg2 arg3 # Run a java program with a package and pass 3 arguments |
Compiling | javac -d # set the destination output directory of the class file javac -gc # generates all debugging info javac -g:[lines, vars, source] # generates specific debugging info javac -verbose # outputs compiler info |
Packaging | jar [-c, --create] # create a JAR archive file jar -C # changes the specified directory and includes the files at the end of the commandline jar [-f, --file] # specifies the name of the JAR file jar [-m, --manifest] # includes the manifest file information |
Other useful tools | javap -c # prints disassembled code javadoc # generate API documentation in HTML format jlink # assemble and optimize a set of modules and their dependencies into a custom runtime image jmod # create JMOD files and list the content of an existing JMOD file jdeps # Java class dependency analyzer jdeprscan # static analysis tool that scans a jar file |
Packages are directory structures used to organize classes and interfaces, Packages provide a mechanism for software reuse, they also provide a convention for unique class names. When coding for a large project, sometimes classes can be called the same name, especially if third party developers are involved by using packages you can distinguish between class names. Normally you supply your domain name as a package location.
Package Example | package uk.co.datadisk; // the directory structure uk/co/datadisk will contain your classes. |
The import directive tells the compiler where to look for the class definitions when it comes upon a class that it cannot find in the default java.lang package.
Import examples | import java.util.*; // using a * is known as import-on-demand import uk.co.datadisk.buildings.* // the classes can be found in uk/co/datadisk/buildings import uk.co.datadisk.* // the classes can be found in uk/co/datadisk, be careful this wont see the builings folder classes, // only the folder level you specified, there is no drilling down the directories using a wildcard import uk.co.datadisk.StockQuote // specifying a particlar class is known as single-type-import Note: single-type-import takes precedence of the import-on-demand declaration import.java.Util.* (lower precedence) |
Static Import examples | import static java.lang.Math.PI // single-type-import import static java.lang.Math.sqrt // single-type-import import static java.lang.Math.* // import-on-demand |