Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Java lecture 2: A quick intro to Java programming. Teach/learn online

JavaFAQ Home » Java Lectures by Anatoliy Malyarenko Go to all tips in Java Lectures by Anatoliy Malyarenko


Bookmark and Share
All Java Lectures contents page | Java lecture 1: Your first cup of Java | Java lecture 2: A quick introduction to Java programming | Java Lecture 3: Object-oriented programming concepts: theory. | Java Lecture 4: Object-oriented programming concepts: example. | Java Lecture 5: Variables | Java Lecture 6: Operators | Java Lecture 7: Expressions, statements, and blocks | Java Lecture 8: Control flow statements | Java Lecture 9: The life cycle of an object | Java Lecture 10: Characters and strings | Java Lecture 11: Numbers and arrays | Java Lecture 12: Classes | Java Lecture 12a: Introduction to Painting Concepts | Java Lecture 13: Inheritance in Java. Part I | Java Lecture 13: Inheritance in Java. Part II | Java Lecture 14: Interfaces and packages. Part I. | Java Lecture 14: Interfaces and packages. Part II. | Java Lecture 15: Swing I. Part I |

A quick introduction to Java programming

by Anatoliy Malyarenko

Abstract

  • Contents of the lecture.
  • Comments in Java code.
  • Defining a class.
  • The main method.
  • Using classes and objects.
  • Importing classes and packages.
  • Defining an applet subclass.
  • Implementing applet methods.
  • Running an applet.

A closer look at HelloWorld

Now that you've seen a Java application (and perhaps even compiled and run it), you might be wondering how it works and how similar it is to other Java applications. Remember that a Java application is a stand-alone Java program -- a program written in the Java language that runs independently of any browser.

We dissect the "Hello World" application you've already seen. Here, again, is its code:

Code:

/**
* File: HelloWorld.java
* Description: First application
* Author: your name
* Mail: your e-mail address
*/
public class HelloWorldApp {
   public static void main(String[] args) {
      // Display "Hello World!"
      System.out.println("Hello World!");
   }
}

Comments in Java code
The bold characters in the following listing are comments.

Code:

/**
* File: HelloWorld.java
* Description: First application
* Author: your name
* Mail: your e-mail address
*/
public class HelloWorldApp {
   public static void main(String[] args) { // Display "Hello World!"
      System.out.println("Hello World!");
   }
}

The Java language supports three kinds of comments:

/* text */
The compiler ignores everything from /* to */.

/** documentation */
This indicates a documentation comment (doc comment, for short).
The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The JDK
javadoc tool uses doc comments when preparing automatically generated documentation.

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

Defining a class

The first line in the following listing begins a class definition block.

Code:

/**
* File: HelloWorld.java
* Description: First application
* Author: your name
* Mail: your e-mail address
*/
class HelloWorldApp {
   public static void main(String[] args) {
      // Display "Hello World!"
      System.out.println("Hello World!");
   }
}
A class -- the basic building block of an object-oriented language such as Java -- is a template that describes the data and behaviour associated with instances of that class. When you instantiate a class you create an object that looks and feels like other instances of the same class. The data associated with a class or object is stored in variables; the behaviour associated with a class or object is implemented with methods. Methods are similar to the functions or procedures in procedural languages such as C.

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

In the Java language, the simplest form of a class definition is:

Code:


class name {
   . . .
}

The keyword class begins the class definition for a class named name. The curly brackets begin and end the class definition block. The "Hello World" application has no variables and has a single method named main.

The main method

The first line in the following listing begins the definition of a main method.

Code:

/**
* File: HelloWorld.java
* Description: First application
* Author: your name
* Mail: your e-mail address
*/
class HelloWorldApp {
   public static void main(String[] args) {
      // Display "Hello World!"
      System.out.println("Hello World!");
   }
}

Every Java application must contain a main method whose signature looks like this:

    public static void main(String[] args)

The method signature for the main method contains three modifiers:

  • public indicates that the main method can be called by any object.
  • static indicates that the main method is a class method.
  • void indicates that the main method doesn't return any value.

How the main method gets called?

The main method in the Java language is similar to the main function in C and C++. When the Java interpreter executes an application (by being invoked upon the application's controlling class), it starts by calling the class's main method. The main method then calls all the other methods required to run your application.

If you try to invoke the Java interpreter on a class that does not have a main method, the interpreter refuses to run your program and displays an error message similar to this:

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

Arguments to the main method

As you can see from the following code snippet, the main method accepts a single argument: an array of elements of type String.

    public static void main(String[] args)

This array is the mechanism through which the runtime system 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. For example, a sorting program might allow the user to specify that the data be sorted in descending order with this command-line argument:

-descending

The "Hello World" application ignores its command-line arguments, so there isn't much more to discuss here.

Using classes and objects

The "Hello World" application is about the simplest Java program you can write that actually does something. Because it is such a simple program, it doesn't need to define any classes except for HelloWorldApp. However, most programs that you write will be more complex and require you to write other classes and supporting Java code.

The "Hello World" application does use another class -- the System class -- that is part of the API (application programming interface) provided with the Java environment. The System class provides system-independent access to system-dependent functionality.

The bold code in the following listing illustrates the use of a class variable of the System class, and of an instance method.

Code:

/**
* File: HelloWorld.java
* Description: First application
* Author: your name
* Mail: your e-mail address
*/
class HelloWorldApp {
   public static void main(String[] args) {
      // Display "Hello World!"
      System.out.println("Hello World!");
   }
}

Using a class method or variable

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

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

The construction System.out is the full name of the out variable in the System class.

Notice that the application never instantiates the System class and that out is referred to directly from the class name. This is because out is a class variable -- a variable associated with the class rather than with an instance of the class. You can also associate methods with a class -- class methods.

To refer to class variables and methods, you join the class name and the name of the class method or class variable together with a period (".").

Using an instance method or variable

Methods and variables that are not class methods or class variables are known as instance methods and instance variables. To refer to instance methods and variables, you must reference the methods and variables from an object.

While System's out variable is a class variable, it refers to an instance of the PrintStream class (a class provided with the Java development environment) that implements the standard output stream.

When the System class is loaded into the application, it 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!");

As you can see, you refer to instance methods and variables similarly to the way you refer to class methods and variables. You join an object reference (out) and the name of the instance method or variable (println) together with a period (".").

The Java compiler allows you to cascade references to class and instance methods and variables together, resulting in constructs like the one that appears in the sample program:

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

This line of code displays "Hello World!" to the application's standard output stream.

Summary

A class method or class variable is associated with a particular class. The runtime system allocates a class variable once per class, no matter how many instances exist of that class. You access class variables and methods through the class.

An instance method or instance variable is associated with a particular object (an instance of a class). Every time you create an object, the new object gets a copy of every instance variable defined in its class. You access instance variables and methods through objects.

The anatomy of an applet

Now that you've seen a Java applet, you're probably wondering how it works. Remember that a Java applet is a program that adheres to a set of conventions that allows it to run within a Java-compatible browser.

Here again is the code for the "Hello World" applet.

Code:

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

The first two lines of the following listing import two classes used in the applet: Applet and Graphics.

Code:

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

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

If you removed the first two lines, the applet could still compile and run, but only if you changed the rest of the code like this:

Code:

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. Both the java.applet and java.awt packages are part of the core Java API -- API that every Java program can count on being in the Java environment. The java.applet package contains classes that are essential to Java applets. The java.awt package contains the most frequently used classes in the Abstract Window Toolkit (AWT), which provides the Java graphical user interface (GUI).

You might have noticed that the example at p. 0 uses the System class without any prefix, and yet 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 Java program.

Besides importing individual classes, you can also import entire packages. Here's an example:

Code:

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

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

In the Java language, every class is in a package. If the source code for a class doesn't have a package statement at the top, declaring the package the class is in, then the class is in the default package. Almost all of the example classes in these lectures are in the default package.

Within a package, all classes can refer to each other without prefixes. For example, the java.awt Component class refers to the java.awt Graphics class without any prefixes, without importing the Graphics class.

Defining an applet subclass

The first bold line of the following listing begins a block that defines the HelloWorld class.

Code:

import java.applet.*;
import java.awt.*;
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 class whose name follows: Applet.

From the Applet class, applets inherit a great deal of functionality. Perhaps most important is the ability to respond to browser requests. For example, when a Java-capable browser loads a page containing an applet, the browser sends a request to the applet, telling the applet to initialize itself and start executing.

An applet isn't restricted to defining just one class. Besides the necessary Applet subclass, an applet can define additional custom classes. When the applet attempts to use a class, the application that's executing the applet first looks on the local host for the class. If the class isn't available locally, it's loaded from the location that the Applet subclass originated from.

Implementing applet methods

The lines of the following listing implement the paint method.

Code:

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

Every applet must implement one or more of the init, start, and paint methods.
Besides the init, start, and paint methods, applets can implement two more methods that the browser calls when a major event occurs (such as leaving the applet's page):

stop and destroy. Applets can implement any number of other methods, as well.

Returning to the above code snippet, the Graphics object passed into the paint method represents the applet's on-screen drawing context. The first argument to the Graphics drawString method is the string to draw on-screen. The second and third arguments are the (x, y) position of the lower left corner of the text on-screen. This applet draws the string "Hello world!" starting at location (50, 25). The applet's coordinate system starts at (0, 0), which is at the upper left corner of the applet's display area.

Running an applet

The bold lines of the following listing comprise the <APPLET> tag that includes the "Hello World" applet in an HTML page.

Code:

<HTML>
   <HEAD>
      <TITLE>MyApplet Example1</TITLE>
   </HEAD>
   <BODY>
      <H1>MyApplet</H1>
      <HR>
      <P>
         <APPLET CODE="HelloWorld.class"
            WIDTH="300" HEIGHT="300">
         </APPLET>
      </P>
      <HR>
   </BODY>
</HTML>

The above <APPLET> tag specifies that the browser should load the class whose compiled code 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 the browser finds the class file, it loads it over the network, if necessary, onto the computer the browser is running on. The browser then creates an instance of the class. If you include an applet twice in one page, the browser loads the class file once and creates two instances of the class.

The WIDTH and HEIGHT attributes are like the same attributes 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, every bit of drawing that the "Hello World" applet does in its paint method occurs within the 150 ? 25-pixel display area that the above <APPLET> tag reserves for it.
 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy