In this article, we will provide the Basics of Java SE and it’s syntax. We will describe the main advantages of an object-oriented approach to system design as well as the benefits of encapsulation, inheritance, and use of interfaces on architectural characteristics. This is part of a larger series of articles to help you prepare for the java associate exam.

Learning About Java Language

Java is an innovative programming language that was inspired by the advantages and disadvantages of the most popular programming languages at that time, C++ and C. It has become one of the most popular languages of choice for programs that need to run on multiple platforms. Java enables a developer to write small programs known as applets, which you can embed in web pages to add interactivity and intelligence. This process opens up a wide range of exciting possibilities outside of passively presenting text and graphics. Now a web page can be interactive in whatever way that you desire such as including animations, games and interactive transaction processing. The possibilities are almost endless.

At the same time, embedding program code in a web page creates new security needs since when any Internet user accesses a page with embedded Java code, you need to be confident that they cannot do anything that might interfere with the underlying operation of the computer or possibly damage the data existing on the system. This implies controlling the execution of the embedded code such that it prevents accidental damage to your computer environment, as well as ensuring that any Java code that was created with malicious intent is inhibited from damaging the computing environment. Java security mechanism’s incorporates measures to minimize the possibility of security breaches taking place with a Java applet.

Java’s support for the Internet and network-based applications generally goes beyond applets, extending to JavaServer Pages (JSP), which provide a powerful means of building dynamic server applications that can dynamically create and download HTML pages to a client customized specifically for the request that is received. Also JavaServer Pages can themselves contain Java applets. You can also write large-scale application programs with Java that can run unchanged on any computer with an operating system environment supporting Java. As the majority of computer devices support Java today, the slogan of Java, "write once, run anywhere," can be easily demonstrated. A java program can be develop that runs on a PC as well as a Java-enabled cell phone.

Java has matured and evolved a great deal in recent years. The breadth of function provided by the standard core Java has grown incredibly. Java provides you with comprehensive facilities for building applications with an interactive graphical user interface (GUI), extensive image processing and graphics programming facilities, as well as support for XML, accessing relational databases and communicating with remote computers over a network. Just about any kind of application can now be programmed effectively in Java, with the implicit plus of complete portability.

Of course, Java is still developing and growing over the many years since its inception in 1997. We are now on version 7 of the Java Development Kit. It adds many new functions including new language features as well as significant additions to the supporting libraries.

 Java Language Features

The most important characteristic of Java is that it was designed from the outset to be machine independent. You can run Java programs unchanged on any machine and operating system combination that supports Java. An application written in Java only requires a single set of source code statements, regardless of the number of different computer platforms on which it is run. In any other programming language, the application frequently requires the source code to be tailored to accommodate different computer environments, particularly if an extensive graphical user interface is involved. Java offers substantial savings in time and resources in developing, supporting, and maintaining major applications on several different hardware platforms and operating systems.

Another important characteristic of Java is that it is object-oriented. As Java was inspired by C++, another object-oriented programming language, it is natural that it also adopted this feature as object-oriented programs are easier to understand and less time-consuming to maintain and extend than programs that have been written without the benefit of using objects. Java is not only object-oriented, but also manages to avoid many of the difficulties and complications inherent in some object-oriented languages, making it easy to learn and very straightforward to use. This makes the learning cycle shorter, and you need less real-world coding experience to gain competence and confidence. It also makes Java code easier to test.

Java has a built-in ability to support national character sets. You can write Java programs as easily for use in Chinese or Russian as you can for English-speaking countries, assuming you are familiar with the national languages involved, of course. You can even build programs from the outset to support several different national languages with automatic adaptation to the environment in which the code executes.

Java Program Types

As previously mentioned there are two basic kinds of programs you can write in Java:
  • Applets - programs that are to be embedded in a web page
  • Applications - normal standalone programs

Java applications can be further subdivided into console applications supporting only character output to your computer screen and windowed applications that support either single or multiple windows that leverage the typical GUI mechanisms of window-based programs such as menus, toolbars, dialogs, etc.

We will use console applications as example to understand the basics of Java language. These are applications that use simple command-line input and output. With this approach you can concentrate on understanding the specifics of the language without worrying about any of the complexity involved in creating and managing windows.

The Java Environment

You can execute Java programs on a variety of computers using a range of operating systems. It runs on a standardized environment called the Java 2 Platform that has been implemented as software in the form of the Java Runtime Environment (JRE) on a wide variety of computers and operating systems. The Java Platform consists of two elements:
  • A Java Virtual Machine - a software implementation of a hypothetical computer
  • A Java Application Programming Interface (Java API) - a set of software components that provides the facilities required to write a fully fledged interactive application in Java.

The Java compiler converts the Java source code that is written into a binary program consisting of bytecode (i.e. machine instructions for the JVM). When you execute a Java program, a program known as the Java interpreter inspects and deciphers the bytecode for it, checks it out to ensure that it has not been tampered with and is safe to execute, and then executes the actions that the bytecode specify within the JVM. Since your Java program consists of bytecode rather than native machine instructions, it is completely insulated from the particular hardware on which it is run. Any computer that has the Java environment implemented handles your program as well as any other, and because the Java interpreter sits between your program and the physical machine, it can prevent unauthorized actions in the program from being executed.

Java Program Development

You will need the Java 2 Platform, Standard Edition (J2SE) version 7 or later. The JDK is available from Java SE Downloads. You can choose from versions of the JDK for Solaris, Linux, and Microsoft Windows, and there are versions supporting either 32-bit or 64-bit operating system environments.

Using a Program Code Editor

To create the Java program source files that you use with the JDK, you need some kind of code editor. There are several excellent professional Java program development tools available that provide friendly environments for creating and editing your Java source code and compiling and debugging your programs. These are powerful tools for the experienced programmer that improve productivity and provide extensive debugging capabilities. In the articles for the Java Associate Exam, we will use Eclipse.

Installing the JDK

Detailed instructions on how to install the JDK for your particular operating system are available from the JDK download website at Java SE Downloads. In order to avoid installing the documentation for Java, you can access it from its current location for online documentation for the JDK at If you download it, the documentation download for the JDK consists of a ZIP archive containing a large number of HTML files structured in a hierarchy. Install the JDK before you unzip the documentation archive. A typical directory structure is shown below:

Tutorial:Basics of Java for the Java Certification Exam-d1-jdkdirectorystructure.jpg
Figure: Java 7 Directory Structure

Creating Your First Project

We will use Eclipse to create our first java program. When you use Eclipse, you must create a separate project for each program. In this way, Eclipse can keep the details of one program separate from another. Each project consists of the source code files you write for your program and, potentially, a number of other resources that you might attach to a program. For example, you might include images and files that contain settings to load at run time and many other possible items. After you've started Eclipse, you can make a new project as follows:

1. From the File menu, select New Java Project. The New Project window appears, as shown in the figure below:

Tutorial:Basics of Java for the Java Certification Exam-d1-jdknewprojectwindow.jpg
Figure: New Java Project Window

Type MyProgram in the Project name field.

Click OK. For our purposes, the default settings work just fine. You should now have a window that looks something like the one in below:

Tutorial:Basics of Java for the Java Certification Exam-d1-eclipseide.png
Figure: The Eclipse IDE

Compiling a Java Program

Java source code is always stored in files with the extension .java. After you have created the source code for a program and saved it in a .java file, you need to process the source using a Java compiler. Using the compiler that comes with the JDK, you make the directory that contains your Java source file the current directory, and then enter the following command:

Java Code: Executing MyProgram
Here, javac is the name of the Java compiler, and is the name of the program source file. This command assumes that the current directory contains your source file. If it doesn't, the compiler isn't able to find your source file. It also assumes that the source file corresponds to the Java language as defined in the current version of the JDK. There is a command-line option, -source, that you can use to specify the Java language version, so for JDK 7, the preceding command to execute the compiler is equivalent to the following:

Java Code: Compiling MyProgram
javac -source 1.7
MyProgram is a simple program that you use to can try out the compiler:

Java Code: Class MyPorgram
public class MyProgram { public static void main(String[] args) {
	System.out.println(“Rome wasn’t burned in a day!”);
If you need to override an existing definition of the CLASSPATH environment variable because it has been set by a Java development system you have installed, the command would be the following:

Java Code: Java Compiler Command
javac -classpath .
Assuming your program contains no errors, the compiler generates a bytecode program that is the equivalent of your source code. The compiler stores the bytecode program in a file with the same name as the source file, but with the extension .class. Java executable modules are always stored in a file with the extension .class. By default, the .class file is stored in the same directory as the source file.

Executing a Java Application

To execute the bytecode program in the .class file with the Java interpreter in the JDK, you make the directory containing the .class file current and enter the command:

Java Code: Executing Java Program
java MyProgram
Note that you use just the name MyProgram to identify the program, not the name of the file that the compiler generates, MyProgram.class. It is a common beginner’s mistake to use the latter by analogy with the compile operation. If you put a .class file extension on MyProgram, your program won’t execute, and you get an error message:

Java Code: Error Message
Exception in thread “main” java.lang.NoClassDefFoundError: MyProgram/class
Although the javac compiler expects to find the name of a file that contains your source code, the java interpreter expects the name of a class (and that class must contain a main() method, as I explain later in this chapter). The class name is MyProgram in this case. The MyProgram.class file contains the compiled MyProgram class. I explain what a class is shortly.

To execute your program, the Java interpreter analyzes and then executes the bytecode instructions. The JVM behaves identically in all computer environments that support Java, so you can be sure your program is completely portable. As I already said, your program runs just as well on a Linux Java implementation as it runs on an implementation for Microsoft Windows, Solaris, or any other operating system that supports Java.

Executing an Applet

The Java compiler in the JDK compiles both applications and applets. However, an applet is not executed in the same way as an application. You must embed an applet in a web page before it can be run. You can then execute it either within a Java-enabled web browser, or by using the appletviewer, a bare-bones browser provided as part of the JDK. It is a good idea to use the appletviewer to run applets while you are learning. This ensures that if your applet doesn’t work, it is almost certainly your code that is the problem, rather than some problem of Java integration with the browser.

If you have compiled an applet and included it in a web page stored as MyApplet.html in the current directory that contains the .class file, you can execute it by entering the following command: appletviewer MyApplet.html

Adding an Applet to an HTML Document

For many element tag pairs, you can specify an element attribute in the starting tag that defines additional or qualifying data about the element. This is how a Java applet is identified in an <applet> tag. Here is an example of how you might include a Java applet in an HTML document:

XML Code: HTML Document for Applet
      <title> A Simple Program </title> 
         <applet code = “MyFirstApplet.class” width = 350 height = 200 > 
The two bolded lines between tags for horizontal lines specify that the bytecode for the applet are contained in the file MyFirstApplet.class. The name of the file containing the bytecode for the applet is specified as the value for the code attribute in the <applet> tag. The other two attributes, width and height, define the width and height of the region on the screen that is used by the applet when it executes. These always have to be specified to run an applet. Here is the Java source code for a simple applet:

Java Code: Applet Example
   import javax.swing.JApplet; 
   import java.awt.Graphics; 
   public class MyFirstApplet extends JApplet { 
      public void paint(Graphics g) { 
      g.drawString(“To climb a ladder, start at the bottom rung.”, 20, 90); 
Note that Java is case-sensitive so you cannot enter a keyword like public with a capital as this would prevent the program from compiling. The listing below will display an applet using appletviewer from the JDK:

Java Code: Running Applet using AppletViewer
appletviewer MyFirstApplet.html
Object-Oriented Programming in Java

Java is an object-oriented language. When you use a procedural programming language, the solution must express every problem essentially in terms of the basic types of data like numbers and characters that you can manipulate in the language. In an object- oriented language like Java, you still have numbers and characters to work with but you can also define other kinds of entities that are relevant to your particular problem. The means that we resolve problems using object oriented programming in Java is in terms of the entities or objects. This not only affects how a program is structured, but also the terms in which the solution to your problem is expressed. Apart from seeming to be an inherently sensible approach to constructing programs, object-oriented programs are usually easier to understand. In Java almost everything is an object.

So What Are Objects?

Anything can be thought of as an object. Objects are all around you. You can consider Tree to be a particular class of objects: trees in general. The notion of a Tree in general is a rather abstract concept—although any tree fits the description, it is more useful to think of more specific types of tree. Hence, the Oak tree in my yard which I call myOak and the Almond tree in your yard which you call yourAlmondTree are actual instances of specific types of tree, subclasses of Tree that in this case happen to be Oak, and Almond. Note how class is a term that describes a specification for a collection of objects with common properties.The figure below shows some classes of trees and how you might relate them.

Tutorial:Basics of Java for the Java Certification Exam-d1-classesoftree.jpg
Figure: Classes of Tree

A class is a specification, or blueprint expressed in program code defining what properties and behaviors make up a particular sort of object. A subclass is a class that inherits all the properties of the parent class, but that also includes extra specialization. Particular classes of Tree, such as Oak or Almond, have all the characteristics of the most general type, Tree; otherwise, they could not be considered to be such. However, each subclass of Tree, such as Oak, has its own characteristics that differentiate Oak objects from other types of Tree. Every object that your program uses must have a corresponding class definition somewhere for objects of that type. The basic idea of a class in programming parallels that of classifying things in the real world. It is a convenient and well-defined way to group things together.

An instance of a class is a technical term for an existing object of that class. This raises the question of what differentiates an object of a given class from an object of another class, an Almond class object, say, from a Oak object. In other words, what sort of information defines a class?

What Defines a Class of Objects?

A class definition identifies all the parameters that define an object of that particular class type consistent with your application needs. Someone else might define the class differently, with a larger or smaller set of parameters to define the same sort of object—it all depends on what you want to do with the class. You decide what aspects of the objects you include to define that particular class of object, and you choose them depending on the kinds of problems that you want to address using the objects of the class.

If you were defining a class Hat, for example, you might use just two parameters in the definition. You could include the type of hat as a string of characters such as “Fedora” or “Baseball cap” and its size as a numeric value. The parameters that define an object of a class are referred to as instance variables or attributes of a class, or class fields. The instance variables can be basic types of data such as numbers, but they can also be other class objects. In Java the definition of the class Hat would look something like this:

Java Code: Class Definition
class Hat { 
   // Stuff defining the class in detail goes here. 
   // This could specify the name of the hat, the size, 
   // maybe the color, and whatever else you felt was necessary.
Each object of your class has a particular set of values defined that characterize that particular object. You could have an object of type BlackHat, which might be defined by values such as “Malloy” for the type of the hat, “Standard Black” for the color, and the size as 6. This is shown in the figure below:

Tutorial:Basics of Java for the Java Certification Exam-d1-instancesofblackhat.jpg
Figure: BlackHat Instances

The figure shows BlackHat objects defined by a set of three values that normally would not change for a given instance. You would expect the type and size attributes for a particular BlackHat object to stay fixed because hats don’t usually change their size. As well you could have other attributes.

Operating on Objects

A class object is not just a collection of various items of data but also is specified by what operations are possible on objects of the class. Clearly, for objects to be of any use in a program, you need to decide what you can do with them. The operations that you specify for objects of a given type depend on what sort of objects you are talking about, the attributes they contain, and how you intend to use them.

For the BlackHat class in the previous figure, you may want to have operations that you could refer to as putHatOn and takeHatOff, which would have meanings that are fairly obvious from their names, and do make sense for BlackHat objects. These operations on a particular BlackHat object would set the value of hatOn for the object. To determine whether your BlackHat was on or off, you would just need to look at this value. Conceivably, you might also have an operation changeOwner by which you could set the instance variable recording the current owner’s name to a new value. The figure below shows these operations applied in succession to a BlackHat object:

Tutorial:Basics of Java for the Java Certification Exam-d1-blackhatcode.jpg
Figure:Code for a BlackHat

This code would be saved in a file with the name The name of a file that contains the definition of a class is always the same as the class name, and the extension is .java to identify that the file contains Java source code. The code that defines the class appears between the braces that follow the identification for the class, as shown in the figure above. The code for each of the methods in the class also appears between braces. The class has three instance variables, owner, size, and hatOn, and this last variable is always initialized as false. Each object that is created according to this class specification has its own independent copy of each of these variables, so each object has its own unique values for the owner, the hat size, and whether the hat is on or off.

Java Program Statements

As you saw in the BlackHat class example, the code for each method in the class appears between braces, and it consists of program statements. A semicolon terminates each program statement. A statement in Java can spread over several lines if necessary because the end of each statement is determined by the semicolon, not by the end of a line. Here is a Java program statement:

Java Code: Java Statement
hatOn = false;
If you wanted to, you could also write this as

Java Code: Java Statement
hatOn = 
You can generally include spaces and tabs, and spread your statements over multiple lines to enhance readability if it is a particularly long statement, but sensible constraints apply. You can’t put a space in the middle of a name, for instance. If you write hat On, for example, the compiler reads this as two words.


At this point we can introduce another bit of jargon you can use to impress or bore your friends—encapsulation. Encapsulation refers to the hiding of items of data and methods within an object. This is achieved by specifying them as private in the definition of the class. In the BlackHat class, the instance variables owner, type, size, and hatOn were encapsulated. They were accessible only through the methods defined for the class.

By allowing only limited access to the members of a class, you have the freedom to change the internals of the class without necessitating changes to programs that use the class. As long as the external characteristics of the methods that can be called from outside the class remain unchanged, the internal code can be changed in any way that you, the programmer, want.

Classes and Data Types

Programming is concerned with specifying how data of various kinds is to be processed, massaged, manipulated, or transformed. Classes define the types of objects that a program works with so you can consider defining a class to be the same as defining a data type. Thus, Hat is a type of data, as is Tree, and any other class you care to define. Java also contains a library of standard classes that provide you with a whole range of programming tools and facilities. For the most part then, your Java program processes, manipulates, or transforms class objects.

There are some basic types of data in Java that are not classes, and these are called primitive types. They are essentially data types for numeric values such as 99 or 3.75, for single characters such as A or ?, and for logical values that can be true or false. Java also has classes mapping to each of the primitive data types. For example, there is an Integer class that defines objects that encapsulate integers.

Advantages of Using Objects

Object-oriented programs are written using objects that are specific to the problem being addressed. A retail system may well define and use objects of type Shopping Cart, Product, Service, and Discount. This has tremendous advantages, not only in terms of easing the development process and making the program code easier to understand, but also in any future expansion of such a program. Java provides a whole range of standard classes to help you in the development of your program, and you can develop your own generic classes to provide a basis for developing programs that are of particular interest to you.

Because an object includes the methods that can operate on it as well as the data that defines it, programming using objects is much less prone to error. Your object-oriented Java programs should be more robust than the equivalent in a procedural programming language. Object-oriented programs take a little longer to design than programs that do not use objects because you must take care in the design of the classes that you need, but the time required to write and test the code is sometimes substantially less than that for procedural programs. Object-oriented programs are also much easier to maintain and extend.


A Java source file may contain annotations. An annotation is not a Java language statement, but rather a special statement that changes the way program statements are treated by the compiler or the libraries. You can define your own annotations but most Java programmers never need to do so since the developers of Java have provided a large set of annotations available to meet the many needs of a developer. For example, if you compiled MyFirstApplet and got a warning message from the compiler. This warning was superfluous so it could have been suppressed by adding the following annotation immediately before the MyFirstApplet class definition:

Java Code: Annotation Suppressing Warning
This annotation informs the compiler not to issue serial warning messages, where serial is the message type. You could use this annotation to suppress any type of warning message, but obviously it is sensible to only suppress warnings that really are irrelevant in a particular context.

Java Program Structure

A Java program is structured in the following manner:
  • A Java program always consists of one or more classes.
  • You put the program code for each class in a separate file, and you must give each file the same name as that of the class that is defined within it.
  • A Java source file name must have the extension .java.

Thus a file containing the class Cargo is called, and a file containing the class ULD must have the file name
A typical program consists of several files is shown in the figure below:

Tutorial:Basics of Java for the Java Certification Exam-d1-javaprogramfiles.jpg
Figure: Entire Java Program of 5 Files

Java’s Class Library

A library in Java is a collection of classes—usually providing related facilities—that you can use in your programs. The Java class library provides you with a whole range of goodies, some of which are essential for your programs to work at all, and some of which make writing your Java programs easier. The class library is a set of classes so it is stored in sets of files where each file contains a class definition. Related classes are grouped together into a set called a package, and each package is stored in a separate directory on disk. A class in a package can access any of the other classes in the package. A class in another package may or may not be accessible. You can also create your own packages that contain classes of your own that you want to reuse in different contexts and that are related in some way. Some of the packages you run into most frequently are listed in the table below:

Tutorial:Basics of Java for the Java Certification Exam-d1-frequsedstdpackages.jpg
Table: Frequently Used Standard Packages

Java Applications

Every Java application contains a class that defines a method called main(). The name of the class that contains main() is the name that you use as the argument to the Java interpreter when you run an application. You can call the class whatever you want, but the method that is executed first in an application is always called main(). When you run your Java application, execution starts with the main() method. The main()method typically causes methods belonging to other classes to be executed, but the simplest possible Java application program consists of one class containing just the main()method. The code for MyFirstProgram is shown in the figure below:

Tutorial:Basics of Java for the Java Certification Exam-d1-myfirstprogram.jpg
Figure: MyFirstProgram Code

The program consists of a definition for a class I have called MyFirstProgram. The class definition contains only one method, the method main(). The first line of the definition for the method main() is always of the form:

Java Code: Main() Method
public static void main(String[] args)
The code for the method appears between the pair of curly braces. This version of the method has only one executable statement:

Java Code: Executing Statement
System.out.println(“Krakatoa, EAST of Java??”);
You can compile this program with the command

Java Code: Compile Command
javac –source 1.7
or with the -classpath option specified: javac –classpath .
or you can just write the following:

[CODE=JAVA;Compile Command w/o Classpath]javac[/CODE=JAVA;

Java And Unicode

Programming to support languages that use anything other than the Latin character set has been a major problem historically. There are a variety of 8-bit character sets defined for many national languages, but if you want to combine the Latin character set and Cyrillic in the same context, for example, things can get difficult. If you want to handle Japanese as well, it becomes impossible with an 8-bit character set because with 8 bits you have only 256 different codes, so there just aren’t enough character codes to go round.

Unicode is a standard character set that was developed to allow the characters necessary for almost all languages to be encoded. It uses a 16-bit code to represent a character (so each character occupies 2 bytes), and with 16 bits up to 65,535 non-zero character codes can be distinguished. Unicode supports three encoding forms that allow up to a million additional characters to be represented.


In this chapter you’ve looked at the basic characteristics of Java, and how portability between different computers is achieved. I have also introduced you to the elements of object-oriented programming. In the next article we will delve into Java Syntax.