Home > Articles > Programming > Java

This chapter is from the book

A Closer Look at HelloWorld

Now that you've compiled and run your first program, you may be wondering how it works and how similar it is to other applications or applets. This section will first take a closer look at the HelloWorldApp application and then the HelloWorld applet. Be aware that the following chapters, Object-Oriented Programming Concepts (page 45) and Language Basics (page 65), will go into much more detail than is presented in this section.

Explanation of an Application

Let's dissect the HelloWorldApp application. First, we will look at the comments in the code before we touch on programming concepts, such as classes and methods.

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

Comments

The Java programming language supports three kinds of comments:

/* text */

The compiler ignores everything from the opening /* to the closing */.

/** documentation */

This style indicates a documentation comment (doc comment, for short). As with the first kind of comment, the compiler ignores all the text within the comment. The SDK javadoc tool uses doc comments to automatically generate documentation. For more information on javadoc, see the tool documentation.13

// text

The compiler ignores everything from the // to the end of the line.

The boldface parts in the following code are comments:

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

Defining a Class

The first boldface line in this listing begins a class definition block:

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

A class is the basic building block of an object-oriented language, such as the Java programming language. A class is a blueprint that describes the state and the behavior associated with instances of that class. When you instantiate a class, you create an object that has the same states and behaviors as other instances of the same class. The state associated with a class or an object is stored in member variables. The behavior associated with a class or an object is implemented with methods, which are similar to the functions or procedures in procedural languages, such as C.

A recipe—say, Julia Child's recipe for ratatouille—is like a class. It's a blueprint for making a specific instance of the recipe. Her rendition of ratatouille is one instance of the recipe, and Mary Campione's is (quite) another.

A more traditional example from the world of programming is a class that represents a rectangle. The class defines variables for the origin, width, and height of the rectangle. The class might also define a method that calculates the area of the rectangle. An instance of the rectangle class, a rectangle object, contains the information for a specific rectangle, such as the dimensions of the floor of your office or the dimensions of this page.

This is simplest form of a class definition:

class Ratatouille {
  . . .         //class definition block
}

The keyword class begins the class definition for a class named Ratatouille. The variables and the methods of the class are enclosed by the braces that begin and end the class definition block. The HelloWorldApp class has no variables and has a single method, named main.

The main Method

The entry point of every Java application is its main method. When you run an application with the Java interpreter, you specify the name of the class that you want to run. The interpreter invokes the main method defined in that class. The main method controls the flow of the program, allocates whatever resources are needed, and runs any other methods that provide the functionality for the application.

The boldface lines in the following listing begin and end the definition of the main method.

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

Every application must contain a main method declared like this:

public static void main(String[] args)

The main method declaration starts with three modifiers:

  • public: Allows any class to call the main method

  • static: Means that the main method is associated with the HelloWorldApp class as a whole instead of operating on an instance of the class

  • void: Indicates that the main method does not return a value

When you invoke the interpreter, you give it the name of the class that you want to run. This class is the application's controlling class and must contain a main method. When invoked, the interpreter starts by calling the class's main method, which then calls all the other methods required to run the application. If you try to invoke the interpreter on a class that does not have a main method, the interpreter can't run your program. Instead, the interpreter displays an error message similar to this:

In class NoMain: void main(String argv[]) is not defined

As you can see from the declaration of the main method, it accepts a single argument: an array of elements of type String, like this:

public static void main(String[] args)

This array is the mechanism through which the Java Virtual Machine passes information to your application. Each String in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. The HelloWorldApp application ignores its command-line arguments, so there isn't much more to discuss here.

Using Classes and Objects

The HelloWorldApp application is about the simplest program you can write that actually does something. Because it is such a simple program, it doesn't need to define any classes except HelloWorldApp.

However, the application does use another class, System, that is part of the Java API. The System class provides system-independent access to system-dependent functionality. One feature provided by the System class is the standard output stream—a place to send text that usually refers to the terminal window in which you invoked the Java interpreter.

Impurity Alert!

Using the standard output stream isn't recommended in 100% Pure Java programs. However, it's fine to use during the development cycle. We use it in many of our example programs because otherwise, our code would be longer and more difficult to read.

The following boldface line shows HelloWorldApp's use of the standard output stream to display the string Hello World:

/**
 * The HelloWorldApp class implements an application that
 * simply displays "Hello World!" to the standard output.
 */




class HelloWorldApp {
  public static void main(String[] args) {
    System.out.println("Hello World!"); //Display the string.
  }
}

This one line of code uses both a class variable and an instance method.

Let's take a look at the first segment of the statement:

System.out.println("Hello World!");

The construct System.out is the full name of the out variable in the System class. The application never instantiates the System class but instead refers to out directly through the class. The reason is that out is a class variable—a variable associated with a class rather than with an object. The Java Virtual Machine allocates a class variable once per class, no matter how many instances of that class exist. The Java programming language also has the notion of class methods used to implement class-specific behaviors.

Although System's out variable is a class variable, it refers to an instance of the PrintStream class (another Java API-provided class that implements an easy-to-use output stream). When it is loaded into the application, the System class instantiates PrintStream and assigns the new PrintStream object to the out class variable. Now that you have an instance of a class, you can call one of its instance methods:

System.out.println("Hello World!");

An instance method implements behavior specific to a particular object—an instance of a class.

The Java programming language also has instance variables. An instance variable is a member variable associated with an object rather than with a class. Each time you instantiate a class, the new object gets its own copy of all the instance variables defined in its class.

If this discussion of member variables, methods, instances, and classes has left you with nothing but questions, the chapters Object-Oriented Programming Concepts (page 45) and Language Basics (page 65) can help.

The Anatomy of an Applet

By following the steps outlined in Creating Your First Applet (page 13 for Win32 and page 20 for UNIX/Linux), you created an applet—a program to be included in HTML pages and executed in Java-enabled browsers. Remember that an applet is a program that adheres to some conventions that allow it to run within a Java-enabled browser.

Here again is the code for the HelloWorld applet:

import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorld extends Applet {
  public void paint(Graphics g) {
    g.drawString("Hello world!", 50, 25);
  }
}

Importing Classes and Packages

HelloWorld.java begins with two import statements that import the Applet and Graphics classes:

import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorld extends Applet {
  public void paint(Graphics g) {
    g.drawString("Hello world!", 50, 25);
  }
}

By importing classes or packages, a class can easily refer to classes in other packages. In the Java programming language, packages are used to group classes, similar to the way libraries group C functions. If you removed the first two lines, you could still compile and run the program, but you could do so only if you changed the rest of the code like this (as shown in boldface):

public class HelloWorld extends java.applet.Applet {
  public void paint(java.awt.Graphics g) {
    g.drawString("Hello world!", 50, 25);
  }\
}

As you can see, importing the Applet and Graphics classes lets the program refer to them later without any prefixes. The java.applet. and java.awt. prefixes tell the compiler which packages it should search for the Applet and Graphics classes. The java.applet package contains classes that are essential to applets. The java.awt package contains classes used by all programs with a GUI.

You might have noticed that the HelloWorldApp application uses the System class without any prefix, yet it does not import the System class. The reason is that the System class is part of the java.lang package, and everything in the java.lang package is automatically imported into every program written in the Java programming language.

You can import not only individual classes but also entire packages. Here's an example:

import java.applet.*;
import java.awt.*;

public class HelloWorld extends Applet {
  public void paint(Graphics g) {
    g.drawString("Hello world!", 50, 25);
  }
}

Every class is in a package. If the source code for a class doesn't have a package statement at the top declaring in which package the class is, the class is in the default package. Almost all the example classes in this tutorial are in the default package.

Within a package, all classes can refer to one another without prefixes. For example, the java.awt package's Component class refers to the same package's Graphics class without any prefixes and without importing the Graphics class.

Defining an Applet Subclass

The first boldface line of the following listing begins a block that defines the HelloWorld class:

import java.applet.Applet;\
import java.awt.Graphics;

public class HelloWorld extends Applet {
  public void paint(Graphics g) {\
    g.drawString("Hello world!", 50, 25);
  }
}

The extends keyword indicates that HelloWorld is a subclass of the Applet class. In fact, every applet must define a subclass of the Applet class. Applets inherit a great deal of functionality from the Applet class, ranging from the ability to communicate with the browser to the ability to present a graphical user interface (GUI). You will learn more about subclasses in the chapter Object-Oriented Programming Concepts (page 45).

Implementing Applet Methods

The boldface lines of the following listing implement the paint method:

import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorld extends Applet {
  public void paint(Graphics g) {
    g.drawString("Hello world!", 50, 25);
  }
}

The HelloWorld applet implements just one method: paint. Every applet should implement at least one of the following methods: init, start, or paint. Unlike Java applications, applets do not need to implement a main method.

Applets are designed to be included in HTML pages. Using the <APPLET> HTML tag, you specify (at a minimum) the location of the Applet subclass and the dimensions of the applet's on-screen display area. The applet's coordinate system starts at (0,0), which is at the upper-left corner of the applet's display area. In the previous code snippet, the string Hello world! is drawn starting at location (50,25), which is at the bottom of the applet's display area.

Running an Applet

When it encounters an <APPLET> tag, a Java-enabled browser reserves on-screen space for the applet, loads the Applet subclass onto the computer on which it is executing, and creates an instance of the Applet subclass.14

The boldface lines of the following listing comprise the <APPLET> tag that includes the Hello-World applet in an HTML page:

<HTML>
  <HEAD>
    <TITLE> A Simple Program </TITLE>
  </HEAD>
  <BODY>
    Here is the output of my program: 
    <APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25> 
    </APPLET>
  </BODY>
</HTML>

The <APPLET> tag specifies that the browser should load the class whose compiled code (bytecodes) is in the file named HelloWorld.class. The browser looks for this file in the same directory as the HTML document that contains the tag.

When it finds the class file, the browser loads it over the network, if necessary, onto the computer on which the browser is running. The browser then creates an instance of the class. If you include an applet twice in one HTML page, the browser loads the class file once and creates two instances of the class.

The WIDTH and HEIGHT attributes are like the attributes of the same name in an <IMG> tag: They specify the size in pixels of the applet's display area. Most browsers do not let the applet resize itself to be larger or smaller than this display area. For example, all the drawing that the HelloWorld applet does in its paint method occurs within the 150 x 25 pixel display area reserved by the <APPLET> tag.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020