Java Fundamentals Tutorial: Hello World

ProTech Home Java Fundamentals Tutorial: Hello World

2. A Java Hello World Program

Implementing Hello World in Java

2.1. HelloWorld.java

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
  • All code is contained within a class, in this case HelloWorld.
  • The file name must match the class name and have a .java extension, for example: HelloWorld.java
  • All executable statements are contained within a method, in this case named main().
  • Use System.out.println() to print text to the terminal.

Classes and methods (including other flow-control structures) are always defined in blocks of code enclosed by curly braces ({ }).

All other statements are terminated with a semi-colon (;).

Java language is case-sensitive! This means that HelloWorld is not the same as helloworld, nor is String the same as string.

There is an generally accepted naming convention in the Java community to capitalize the names of Java classes and use the so-called CamelCase (or CamelHump) notation, where the first letter of each word is capitalized, but the words are joined together (i.e. no dashes or underscores).

[Note]Note

Java source files can be encoded in UTF-8 to support internationalized characters (even for class, method, and variable names). In most situations however, Java sources are stored in US-ASCII character set, and internationalized strings are loaded from external resource files.

2.2. Java Keywords

Table 1. Java Keywords

abstract

assert

boolean

break

byte

case

catch

char

class

const

continue

default

do

double

else

enum

extends

final

finally

float

for

goto

if

implements

import

instanceof

int

interface

long

native

new

package

private

protected

public

return

short

static

strictfp

super

switch

synchronized

this

throw

throws

transient

try

void

volatile

while



Keywords goto and const are reserved, but never used.

Keyword strictfp was added in Java 1.2.

Keyword assert was added in Java 1.4.

Keyword enum was added in Java 1.5.

In addition to these 50 keywords, Java also defined three special literals: true, false, and null.

Keywords in our HelloWorld program are in bold:

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

2.3. Java Identifiers

  • An identifier is the name of a class, variable, field, method, or constructor.

    • Cannot be a Java keyword or a literal
    • Can contain letters, digits, underscores, and dollar signs
    • Cannot start with a digit
  • Valid identifier examples: HelloWorld, args, String, i, Car, $myVar, employeeList2
  • Invalid identifier examples: 1st, byte, my-Arg, *z
  • Java naming conventions for identifiers:

    • Use CamelCase for most identifiers (classes, interfaces, variables, and methods).
    • Use an initial capital letter for classes and interfaces, and a lower case letter for variables and methods.
    • For named constants, use all capital letters separated by underscores.
    • Avoid using $ characters in identifiers.

Identifiers in our HelloWorld program are in bold:

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

2.4. Compiling Java Programs

  • The JDK comes with a command-line compiler: javac.

    • It compiles source code into Java bytecode, which is low-level instruction set similar to binary machine code.
    • The bytecode is executed by a Java virtual machine (JVM), rather than a specific physical processor.
  • To compile our HelloWorld.java, you could go to the directory containing the source file and execute:

    javac HelloWorld.java
  • This produces the file HelloWorld.class, which contains the Java bytecode.

Use the javac -help option to get a full list of available options:

Usage: javac <options> <source files>
where possible options include:
  -g                         Generate all debugging info
  -g:none                    Generate no debugging info
  -g:{lines,vars,source}     Generate only some debugging info
  -nowarn                    Generate no warnings
  -verbose                   Output messages about what the compiler is doing
  -deprecation               Output source locations where deprecated APIs are used
  -classpath <path>          Specify where to find user class files and annotation processors
  -cp <path>                 Specify where to find user class files and annotation processors
  -sourcepath <path>         Specify where to find input source files
  -bootclasspath <path>      Override location of bootstrap class files
  -extdirs <dirs>            Override location of installed extensions
  -endorseddirs <dirs>       Override location of endorsed standards path
  -proc:{none,only}          Control whether annotation processing and/or compilation is done.
  -processor <class1>[,<class2>,<class3>...]Names of the annotation processors to run; bypasses default discovery process
  -processorpath <path>      Specify where to find annotation processors
  -d <directory>             Specify where to place generated class files
  -s <directory>             Specify where to place generated source files
  -implicit:{none,class}     Specify whether or not to generate class files for implicitly referenced files
  -encoding <encoding>       Specify character encoding used by source files
  -source <release>          Provide source compatibility with specified release
  -target <release>          Generate class files for specific VM version
  -version                   Version information
  -help                      Print a synopsis of standard options
  -Akey[=value]              Options to pass to annotation processors
  -X                         Print a synopsis of nonstandard options
  -J<flag>                   Pass <flag> directly to the runtime system

You can view the generated byte-code, using the -c option to javap, the Java class disassembler. For example:

javap -c HelloWorld

2.5. Running Java Programs

Figure 2. Compiling and running a Java program

Compiling and running a Java program


  • To run the bytecode, execute:

    java HelloWorld
  • Do not include the .class extension.
  • The java command starts the JVM and executes the class bytecode.
  • The JVM abstracts O/S and H/W from the Java application.

It is the Java virtual machine that provides the layer of insulation to Java programs so that they do not depend on the underlying operating system or hardware semantics.

This allows compiled Java applications to run on any platform that has a Java virtual machine written for it:

  • AIX
  • BSD
  • HP-UX
  • Linux
  • Mac OS X
  • Solaris
  • Windows

2.6. Comments in Java Code

  • // single-line comment

    • Comments-out everything until a line break
  • /* Multi-line comment */

    • Useful for commenting out a section of code
    • Cannot be nested within other multi-line comments
  • /** JavaDoc comments */

    • Similar to multi-line comments but used to document Java code (classes, methods, fields)
    • Extracted using javadoc command-line utility

/**
 * My first class
 * @author student
 * @version 1.0
 */
public class HelloWorld {

    /**
     * Main method that runs when the program is started.
     * @param args command-line arguments
     */
    public static void main (String[] args) {
        /*
        This is how you can print to STDOUT
         */
        System.out.println("Hello World"); // don't forget the semi-colon

        /*
        System.out.println("I was also going to say...");
        System.out.println("but I changed my mind");
        */
    }
}

2.7. The main() Method

  • A Java application is a public Java class with a main() method.

    • The main() method is the entry point into the application.
    • The signature of the method is always:

      public static void main(String[] args)
    • Command-line arguments are passed through the args parameter, which is an array of Strings

Applets and servlets do not have a main() method because they are run through template methods in the context of a framework. For example, a web container is responsible for instantiating a servlet object. It then invokes a standard set of methods defined by the Servlet class at appropriate points in the servlet lifecycle; for example, init() to initialize the servlet, doGet() to handle an HTTP GET message, destroy() when the web container is about to destroy the object, and so on. The parent class provides default implementations of these methods, but the derived servlet class can override any of the template methods to provide servlet-specific functionality.

Copyright © 2020 ProTech. All Rights Reserved.

Sign In Create Account

Navigation

Social Media