Java - Getting Started - Hello World

> Procedural Languages > Java

1 - About

A little article on the basics of Java.

Advertising

3 - Steps

3.1 - Is Java Installed

java -version
java version "1.6.0_24"
Java(TM) SE Runtime Environment (build 1.6.0_24-b07)
Java HotSpot(TM) 64-Bit Server VM (build 19.1-b02, mixed mode)

On Windows, the Java Control Panel:

3.2 - The source of the HelloWorld.java file

Creation of the HelloWorld.java file as text file.

package myWorld;
 
/**
 * The HelloWorld class implements an application that
 * simply prints "Hello World!" to standard output.
 */
class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
    }
}

This simple code is composed of:

  • a class HelloWorld
  • a main method who uses the System class (System.out.println) from the core library to print the “Hello World!” message to standard output. Portions of this library is also known as the “Application Programming Interface”, or “API”).
  • and a package

3.3 - Compilation to get the binary HelloWorld.class file

When you compile a program written in the Java programming language, the compiler converts the human-readable source file into platform-independent code that a Java Virtual Machine can understand. This platform-independent code is called Bytecode.

Java programs are compiled and executed using the JavaSoft’s JDK in a client environment.

When Java source programs are compiled, each public class is stored in a separate .class file in the operating system environment.

  • compiling the .java file from the command line
javac HelloWorld.java

You will get a .class file and then you can run your program.

When Java searches different classes needed to be executed,different file system directories specified in the CLASSPATH environment variable to resolve references to the classes needed for execution.

Advertising

3.4 - Run the progam

  • Move you class file in a directory called myWorld. A package is in java physically a directory.
  • Run the class
java myWorld/HelloWorld
Hello World!

Don't add the class extension otherwise you get a java.lang.NoClassDefFoundError

java myWorld/HelloWorld.class
Exception in thread "main" java.lang.NoClassDefFoundError: myWorld/HelloWorld/cla
Caused by: java.lang.ClassNotFoundException: HelloWorld.class
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: myWorld/HelloWorld.class.  Program will exit.

4 - How to

4.1 - Pass an Argument

In the main method, you can pass arguments. Example:

package myWorld;
/**
 * This HelloWorld class implements an application that
 * prints "Hello World!" of "Hello Args" to standard output 
 * if an argument is given
 */
class HelloWorld {
    public static void main(String[] args) {
    	if (args.length==0) 
    	{
    		System.out.println("Hello World!"); 
    	} else {
    		System.out.println("Hello " + args[0].toString());
    	}
    }
}

After compilation:

c:\MyJava>java myWorld/HelloWorld
Hello World!

c:\MyJava>java myWorld/HelloWorld Nico
Hello Nico

4.2 - Create a Jar File

To create a .jar file from the class

jar cf HelloWorld.jar HelloWorld.class
Advertising

5 - Type of Errors

5.1 - Syntax

If you mistype part of a program, the compiler may issue a syntax error. The message usually displays the type of the error, the line number where the error was detected, the code on that line, and the position of the error within the code. Here's an error caused by omitting a semicolon (;) at the end of a statement:

testing.java:14: `;' expected. System.out.println("Input has " + count + " chars.") ^ 1 error

Sometimes the compiler can't guess your intent and prints a confusing error message or multiple error messages if the error cascades over several lines. For example, the following code snippet omits a semicolon (;) after the count++ instruction:

while (System.in.read() != -1) count++ System.out.println("Input has " + count + " chars.");

When processing this code, the compiler issues two error messages:

testing.java:13: Invalid type expression. count++ ^ 
testing.java:14: Invalid declaration. System.out.println("Input has " + count + " chars."); ^ 
2 errors 

The compiler issues two error messages because after it processes count++, the compiler's state indicates that it's in the middle of an expression. Without the semicolon, the compiler has no way of knowing that the statement is complete.

If you see any compiler errors, then your program did not successfully compile, and the compiler did not create a .class file. Carefully verify the program, fix any errors that you detect, and try again.

5.2 - Semantic

In addition to verifying that your program is syntactically correct, the compiler checks for other basic correctness. For example, the compiler warns you each time you use a variable that has not been initialized:

testing.java:13: Variable count may not have been initialized. count++ ^ 
testing.java:14: Variable count may not have been initialized. System.out.println("Input has " + count + " chars."); ^
2 errors 

Again, your program did not successfully compile, and the compiler did not create a .class file. Fix the error and try again.

6 - Support

6.1 - java.lang.NoClassDefFoundError HelloWorld.java

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld.java.

If you receive this error, java cannot find your bytecode file, HelloWorld.class.

  • Check or change your classpath environment variable
  • or Change your current directory to the bytecode file directory

6.2 - java.lang.NoClassDefFoundError: HelloWorld/class

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld/class

The argument is the name of the class that you want to use, not the filename.

A common mistake made by beginner programmers is to try and run the java launcher on the .class file that was created by the compiler.

For example, you'll get this error if you try to run your program with

java HelloWorldApp.class

instead of

java HelloWorldApp

6.3 - 'javac' is not recognized as an internal or external command

'javac' is not recognized as an internal or external command, operable program or batch file

If you receive this error, Windows or Linux cannot find the compiler (javac).

Here's one way to tell Windows where to find javac. Suppose you installed the JDK in C:\jdk6. At the prompt you would type the following command and press Enter: C:\jdk6\bin\javac HelloWorldApp.java If you choose this option, you'll have to precede your javac and java commands with C:\jdk6\bin\ each time you compile or run a program. To avoid this extra typing, you could add this information to your PATH variable. Consult the section in the JDK 6 installation instructions.

6.4 - Class names, 'HelloWorld', are only accepted if ...

Class names, 'HelloWorld', are only accepted if annotation processing is explicitly requested

If you receive this error, you forgot to include the .java suffix when compiling the program. Remember, the command is javac HelloWorldApp.java not javac HelloWorldApp.

lang/java/getting_started.txt · Last modified: 2017/02/16 10:02 by gerardnico