Java Introduction

An Overview of Java

 

Object-Oriented Programming

 

Object-oriented programming is at the core of Java. In fact, all Java programs are object oriented. OOP is so important to Java that you must understand its basic principles. All computer programs consist of two elements: code and data.  These are the two ways how a program is constructed. The first way is called the process-oriented model. This approach distinguishes a program as a series of steps. The process-oriented model can be thought of as code acting on data. Procedural languages such as C employ this model. Problems with this approach appear as programs grow larger and more complex. To manage increasing complexity, the second approach, called object-oriented programming, was considered. Object-oriented programming organizes a program around its data that is, objects and a set of well-defined methods to that data.

 

Abstraction

An essential element of object-oriented programming is abstraction. Complexity is managed through abstraction. For example, people do not think of a car as thousands of individual parts. They think of it as a well-defined object with its own behavior. This abstraction allows people to use a car to drive to the stores without knowing the complexity of the parts that form the car. They can ignore the details of how the engine, transmission, and braking systems work. Instead they are free to utilize the object as a whole. A powerful way to manage abstraction is through the use of hierarchical classifications. This allows you to layer the complex systems, breaking them into more manageable pieces. From the outside, the car is a single object. Once inside, you see that the car consists of several systems: steering, breaks, sound system, seat belts, and so on. In turn, each of these systems is made up of more specialized units. For instance, the sound system consists of a radio, a CD player. The point is that you manage the complexity of the car through the use of hierarchical abstractions. Hierarchical abstractions of complex systems can also be applied to computer programs. A sequence of process steps can become a collection of messages between these objects. Each of these objects describes its own unique behavior. You can treat these objects as entities that respond to messages telling them to do something. Object-oriented concepts form the heart of Java. It is important that you understand how these concepts translate into programs.

 

The Three OOP Principles

 

All object-oriented programming languages provide mechanisms that help you implement the object-oriented model. They are encapsulation, inheritance, and polymorphism.

 

Encapsulation

Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from misuse. One way to think about encapsulation is as a protective covering that prevents the code and data from being accessed by other code from outside. To relate this to the real world, consider the automatic transmission on an automobile. It encapsulates hundreds of bits of information about the engine, such as how much you are accelerating and the position of the shift lever. You, as the user, have only one method of this complex encapsulation: by moving the gear lever. You can’t affect the transmission by using the turn signal or windshield wipers. Thus, the gear-shift lever is a well-defined unique interface to the transmission. For example, shifting gears does not turn on the headlights because an automatic transmission is encapsulated. This same idea can be applied to programming. The power of encapsulated code is that everyone knows how to access it and thus can use it regardless of the implementation details. In Java the basis of encapsulation is the class. A class defines the structure/ data and behavior/code that will be shared by a set of objects. Objects are sometimes referred to as instances of a class.  When you create a class, you will specify the code and data that constitute that class. Collectively, these elements are called members of the class. The data defined by the class are referred to as member variables or instance variables. The code that operates on that data is referred to as member methods or methods. In Java programs, the methods define how the member variables can be used. Since the purpose of a class is to encapsulate complexity, there are mechanisms for hiding the complexity of the implementation inside the class. Each method or variable in a class may be private or public. The public interface of a class represents everything that external users of the class need to know. The private methods and data can only be accessed by code that is a member of the class. Therefore, any other code that is not a member of the class cannot access a private method or variable.

 

Inheritance

Inheritance is the process by which one object acquires the properties of another object. This is important because it supports the concept of hierarchical classification. Without the use of hierarchies, each object would need to define all of its characteristics explicitly. However, by use of inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. Most people naturally view the world as made up of objects that are related to each other in a hierarchical way, such as animals, mammals, and cats. If you wanted to describe animals in an abstract way, you would say they have some attributes, such as size, intelligence, and type of skeletal system. Animals also have certain behavioral aspects; they eat, breathe, and sleep. This description of attributes and behavior is the class definition for animals. If you wanted to describe a more specific class of animals, such as mammals, they would have more specific attributes, such as type of teeth. This is known as a subclass of animals, where animals are referred to as mammals’ superclass. Since mammals are simply more precisely specified animals, they inherit all of the attributes from animals. A deeply inherited subclass inherits all of the attributes from each of its ancestors in the class hierarchy.

 

Polymorphism

Polymorphism from the Greek, meaning “many forms” is a feature that allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation. Consider a stack which is a last-in, first-out list. You might have a program that requires three types of stacks. One stack is used for integer values, one for floating-point values, and one for characters. The algorithm that implements each stack is the same, even though the data being stored differs. In a non object-oriented language, you have to create three different sets of stack methods, with each set using different names. However, because of polymorphism, in Java you can specify a general set of stack methods that all share the same names. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler’s job to select the specific action that is, method as it applies to each situation.

 

Polymorphism, Encapsulation, and Inheritance Work Together

When properly applied, polymorphism, encapsulation, and inheritance combine to produce a programming environment that supports the development of far more robust and scaleable programs than does the process oriented model. Encapsulation allows you to migrate your implementations over time without breaking the code that depends on the public interface of your classes. Polymorphism allows you to create clean, sensible, readable, and resilient code. For examples, the automobile more completely illustrates the power of object-oriented design. Cars are more like programs. All drivers rely on inheritance to drive different types of vehicles. Whether the vehicle is a school bus, a minivan, and drivers can all more or less find and operate the steering wheel, the brakes, and the accelerator. The brake and gas pedals hide an unbelievable array of complexity with an interface so simple you can operate them with your feet. The implementation of the engine, the style of brakes, and the size of the tires have no effect on how you interface with the class definition of the pedals. Finally, polymorphism is clearly reflected in the ability of car manufacturers to offer a wide array of options on basically the same vehicle. For example, you can get an antilock braking system or traditional brakes, power steering, different engines. Either way, you will still press the break pedal to stop, turn the steering wheel to change direction, and press the accelerator when you want to move. As you can see, it is through the application of encapsulation, inheritance, and polymorphism that the individual parts are transformed into the object known as a car. The same is also true of computer programs. By the application of object-oriented principles, the various parts of a complex program can be brought together to form a robust application. Every Java program involves encapsulation, inheritance, and polymorphism. As you will see, many of the features supplied by Java are part of its built-in class libraries.

 

A First Simple Program

 

Let’s look at some actual Java programs. Let’s start by compiling and running the short sample program shown here.

 

/*

This is a simple Java program.

Call this file “Example.java”.

*/

class Example {

// Your program begins with a call to main().

public static void main(String args[]) {

System.out.println(“This is a simple Java program.”);

}

}

 

Entering the Program

The first thing that you must learn about Java is that the name you give to a source file is very important. For this example, the name of the source file should be Example.java. In Java, a source file is officially called a compilation unit. It is a text file that contains one or more class definitions. The Java compiler requires that a source file use the .java filename extension. As you can see by looking at the program, the name of the class defined by the program is also Example. In Java, all code must reside inside a class. By convention, the name of that class should match the name of the file. The reason for this is that Java is case-sensitive.

 

Compiling the Program

To compile the Example program, execute the compiler, javac, specifying the name of the source file on the command line, as shown here:

 

C:\>javac Example.java

 

The javac compiler creates a file called Example.class that contains the bytecode of the program. The Java bytecode is the intermediate representation of your program that contains instructions the Java interpreter will execute. Thus, the output of javac is not code that can be directly executed. To actually run the program, you must use the Java interpreter, called java. To do so, pass the class name Example as a command-line argument, as shown here:

 

C:\>java Example

 

When the program is run, the following output is displayed:

 

This is a simple Java program.

 

When Java source code is compiled, each individual class is put into its own output file named after the class and using the .class extension. When you execute the Java interpreter as just shown, you are actually specifying the name of the class that you want the interpreter to execute. It will automatically search for a file by that name that has the .class extension. If it finds the file, it will execute the code contained in the specified class. The program begins with the following lines:

 

/*

This is a simple Java program.

Call this file “Example.java”.

*/

 

This is a comment. The contents of a comment are ignored by the compiler. Instead, a comment explains the operation of the program to anyone who is reading its source code. In this case, the comment describes the program. in real applications, comments generally explain how some part of the program works. Java supports three styles of comments. The one shown at the top of the program is called a multiline comment. This type of comment must begin with /* and end with */. Anything between these two comment symbols is ignored by the compiler. As the name suggests, a multiline comment may be several lines long. The next line of code in the program is shown here:

 

class Example {

 

This line uses the keyword class to declare that a new class is being defined. Example is an identifier that is the name of the class. The entire class definition, including all of its members, will be between the opening curly brace {and the closing curly brace}. The next line in the program is the single-line comment, shown here:

 

// Your program begins with a call to main().

 

This is the second type of comment supported by Java. A single-line comment begins with a // and ends at the end of the line. The next line of code is shown here:

 

public static void main(String args[]) {

 

This line begins the main( ) method. this is the line at which the program will begin executing. All Java applications begin execution by calling main( ). The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. The opposite of public is private, which prevents a member from being used by code defined outside of its class. In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program is started. The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java interpreter before any objects are made. The keyword void simply tells the compiler that main( ) does not return a value. Keep in mind that Java is case-sensitive. Thus, Main is different from main. It is important to understand that the Java compiler will compile classes that do not contain a main( ) method. But the Java interpreter has no way to run these classes. So, if you had typed Main instead of main, the compiler would still compile your program. However, the Java interpreter would report an error because it would be unable to find the main( ) method. Any information that you need to pass to a method is received by variables specified within the set of parentheses that follow the name of the method. These variables are called parameters. In main( ), there is only one parameter. String args[ ] declares a parameter named args, which is an array of the class String. Objects of type String store character strings. In this case, args receives any command-line arguments present when the program is executed. The last character on the line is the {. This signals the start of main( )’s body. All of the code that comprises a method will occur between the method’s opening curly brace and its closing curly brace. One other point: main( ) is simply a starting place for your program. A complex program will have many classes. The next line of code is shown here. Notice that it occurs inside main( ).

 

System.out.println(“This is a simple Java program.”);

 

This line outputs the string “This is a simple Java program.” followed by a new line on the screen. Output is actually accomplished by the built-in println( ) method. In this case, println( ) displays the string which is passed to it. The line begins with System.out. System is a predefined class that provides access to the system, and out is the output stream that is connected to the console. Notice that the println( ) statement ends with a semicolon. All statements in Java end with a semicolon. The first} in the program ends main( ), and the last } ends the Example class definition.

 


A Second Short Program

A variable is a named memory location that may be assigned a value by your program. The value of a variable may be changed during the execution of the program. The next program shows how a variable is declared and how it is assigned a value. In addition, the program also illustrates some new aspects of console output. As the comments at the top of the program state, you should call this file Example2.java.

 

/*

Here is another short example.

Call this file “Example2.java”.

*/

class Example2 {

public static void main(String args[]) {

int num; // this declares a variable called num

num = 100; // this assigns num the value 100

System.out.println(“This is num: ” + num);

num = num * 2;

System.out.print(“The value of num * 2 is “);

System.out.println(num);

}

}

 

When you run this program, you will see the following output:

 

This is num: 100

The value of num * 2 is 200

 

The first new line in the program is shown here:

 

int num; // this declares a variable called num

 

This line declares an integer variable called num. Java requires that variables be declared before they are used. Following is the general form of a variable declaration:

 

type var-name;

 

Here, type specifies the type of variable being declared, and var-name is the name of the variable. If you want to declare more than one variable of the specified type, you may use a comma-separated list of variable names. Java defines several data types, including integer, character, and floating-point. The keyword int specifies an integer type. In the program, the line: num = 100; // this assigns num the value 100. In Java, the assignment operator is a single equal sign.

 

The next line of code outputs the value of num preceded by the string “This is num:”.

 

System.out.println(“This is num: ” + num);

 

In this statement, the plus sign causes the value of num to be appended to the string that precedes it, and then the resulting string is output. Using the + operator, you can string together as many items as you want within a single println( ) statement. The next line of code assigns num the value of num times 2. Java uses the * operator to indicate multiplication. After this line executes, num will contain the value 200. Here are the next two lines in the program:

 

System.out.print(“The value of num * 2 is “);

System.out.println(num);

 

Several new things are occurring here. First, the built-in method print( ) is used to display the string “The value of num * 2 is ”. This string is not followed by a newline. This means that when the next output is generated, it will start on the same line. The print( ) method is just like println( ), except that it does not output a newline character after each call. println( ) can be used to output values of any of Java’s built-in types.

 

Using Blocks of Code

Java allows two or more statements to be grouped into blocks of code, also called code blocks. This is done by enclosing the statements between opening and closing curly braces. Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can. For example, a block can be a target for Java’s if and for statements. Consider this if statement:

 

if(x < y) { // begin a block

x = y;

y = 0;

} // end of block

 

Here, if x is less than y, then both statements inside the block will be executed. Thus, the two statements inside the block form a logical unit, and one statement cannot execute without the other also executing. The key point here is that whenever you need to logically link two or more statements, you do so by creating a block. Let’s look at another example. The following program uses a block of code as the target of a for loop.

 

/*

Demonstrate a block of code.

Call this file “BlockTest.java”

*/

class BlockTest {

public static void main(String args[]) {

int x, y;

y = 10;

// the target of this loop is a block

for(x = 0; x<510; x++) {

System.out.println(“This is x: ” + x);

System.out.println(“This is y: ” + y);

y = y – 2;

}

}

}

 

The output generated by this program is shown here:

This is x: 0

This is y: 10

This is x: 1

This is y: 8

This is x: 2

This is y: 6

This is x: 3

This is y: 4

This is x: 4

This is y: 2

This is x: 5

This is y: 0

 

In this case, the target of the for loop is a block of code and not just a single statement. Thus, each time the loop iterates, the three statements inside the block will be executed. This fact is, of course, evidenced by the output generated by the program.

 

Lexical Issues

 

Java programs are a collection of whitespace, identifiers, comments, literals, operators, separators, and keywords.

 

Whitespace

Java is a free-form language. This means that you do not need to follow any special indentation rules. For example, the Example program could have been written all on one line or in any other strange way you felt like typing it, as long as there was at least one whitespace character between each token that was not already delineated by an operator or separator. In Java, whitespace is a space, tab, or newline.

 

Identifiers

Identifiers are used for class names, method names, and variable names. An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign characters. They must not begin with a number, lest they be confused with a numeric literal. Again, Java is case-sensitive, so VALUE is a different identifier than Value.

 

Literals

A constant value in Java is created by using a literal representation of it. For example, here are some literals: 100 98.6 ‘X’ “This is a test” Left to right, the first literal specifies an integer, the next is a floating-point value, the third is a character constant, and the last is a string. A literal can be used anywhere a value of its type is allowed.

 

Comments

There are three types of comments defined by Java. You have already seen two: single-line and multiline. The third type is called a documentation comment. This type of comment is used to produce an HTML file that documents your program. The documentation comment begins with a /** and ends with a */.

 

Separators

In Java, there are a few characters that are used as separators. The most commonly used separator in Java is the semicolon. As you have seen, it is used to terminate statements. The separators are shown in the following table:

 

Symbol Name Purpose
( )

 

Parentheses Used to contain lists of parameters in method definition and invocation. Also used for defining precedence in expressions, containing expressions in control statements, and surrounding cast types.
{ }

 

Braces Used to contain the values of automatically initialized arrays. Also used to define a block of code, for classes, methods, and local scopes.
[ ] Brackets Used to declare array types. Also used when dereferencing array values.
; Semicolon Terminates statements.
, Comma Separates consecutive identifiers in a variable declaration. Also used to chain statements together inside a for statement.
.

 

Period Used to separate package names from sub packages and classes. Also used to separate a variable or method from a reference variable.

 

The Java Keywords

There are 49 reserved keywords currently defined in the Java language. These keywords, combined with the syntax of the operators and separators, form the definition of the Java language. These keywords cannot be used as names for a variable, class, or method. In addition to the keywords, Java reserves the following: true, false, and null. These are values defined by Java. You may not use these words for the names of variables, classes, and so on.