You are on page 1of 17

HCI CHAPTER 1 -PONSURESH Page 1

CHAPTER 1

INTRODUCTION
Java is a programming language created by James Gosling from Sun Microsystems (Sun)
in 1991. The first publicly available version of Java (Java 1.0) was released in 1995.
Sun Microsystems was acquired by the Oracle Corporation in 2010. Oracle has now the
steermanship for Java.
Over time new enhanced versions of Java have been released. The current version of Java
is Java 1.7 which is also known as Java 7.
From the Java programming language the Java platform evolved. The Java platform
allows software developers to write program code in other languages than the Java programming
language and still runs on the Java virtual machine. The Java platform is usually associated with
the Java virtual machine and the Java core libraries.
Java Virtual machine
The Java virtual machine (JVM) is a software implementation of a computer that
executes programs like a real machine.
The Java virtual machine is written specifically for a specific operating system, e.g. for
Linux a special implementation is required as well as for Windows.

Java programs are compiled by the Java compiler into bytecode. The Java virtual machine
interprets this bytecode and executes the Java program.
HCI CHAPTER 1 -PONSURESH Page 2

Java Runtime Environment vs. Java Development Kit
A Java distribution comes typically in two flavors, the Java Runtime Environment (JRE)
and the Java Development Kit (JDK).
The Java runtime environment (JRE) consists of the JVM and the Java class libraries and
contains the necessary functionality to start Java programs.
The JDK contains in addition the development tools necessary to create Java programs.
The JDK consists therefore of a Java compiler, the Java virtual machine, and the Java class
libraries.
Characteristics of Java
The target of Java is to write a program once and then run this program on multiple operating
systems.
Java has the following properties:
Platform independent: Java programs use the Java virtual machine as abstraction and do
not access the operating system directly. This makes Java programs highly portable. A
Java program (which is standard complaint and follows certain rules) can run unmodified
on all supported platforms, e.g. Windows or Linux.
Object-orientated programming language: Except the primitive data types, all elements in
Java are objects.
Strongly-typed programming language: Java is strongly-typed, e.g. the types of the used
variables must be pre-defined and conversion to other objects is relatively strict, e.g. must
be done in most cases by the programmer.
Interpreted and compiled language: Java source code is transferred into the bytecode
format which does not depend on the target platform. These bytecode instructions will be
interpreted by the Java Virtual machine (JVM). The JVM contains a so called Hotspot-
Compiler which translates performance critical bytecode instructions into native code
instructions.
Automatic memory management: Java manages the memory allocation and de-allocation
for creating new objects. The program does not have direct access to the memory. The
so-called garbage collector deletes automatically objects to which no active pointer
exists.
HCI CHAPTER 1 -PONSURESH Page 3

The Java syntax is similar to C++. Java is case sensitive, e.g. variables called myValue and
myvalue are treated as different variables.
Sample Java Program
1 // Welcome1.java
2 // Text-printing program.
3
4 public class Welcome1
5 {
6 // main method begins execution of Java application
7 public static void main( String[ ] args )
8 {
9 System.out.println( "Welcome to Java Programming!" );
10 } // end method main
11 } // end class Welcome1

Output : Welcome to Java Programming!
Commenting Your Programs
We insert comments to document programs and improve their readability. The Java
compiler ignores comments, so they do not cause the computer to perform any action when the
program is run. By convention, we begin every program with a comment indicating the figure
number and file name. The comment in line 1
// Fig. 2.1: Welcome1.java
begins with //, indicating that it is an end-of-line commentit terminates at the end of the line
on which the // appears. An end-of-line comment need not begin a line; it also can begin in the
middle of a line and continue until the end. Java also has traditional comments, which can be
spread over several lines as in
/* This is a traditional comment. It
can be split over multiple lines */
These begin and end with delimiters, /* and */.


HCI CHAPTER 1 -PONSURESH Page 4

Using Blank Lines
Line 3 is a blank line. Blank lines, space characters and tabs make programs easier to
read. Together, theyre known as white space (or whitespace). The compiler ignores white
space.
Declaring a Class
Line 4
public class Welcome1
begins a class declaration for class Welcome1. Every Java program consists of at least one class
that you (the programmer) define. The class keyword introduces a class declaration and is
immediately followed by the class name (Welcome1).
Class Names and I dentifiers
By convention, class names begin with a capital letter and capitalize the first letter of
each word they include (e.g., SampleClassName). A class name is an identifiera series of
characters consisting of letters, digits, underscores (_) and dollar signs ($) that does not begin
with a digit and does not contain spaces. Normally, an identifier that does not begin with a
capital letter is not a class name.
Declaring a Method
Line 6
// main method begins execution of Java application
is an end-of-line comment indicating the purpose of lines 710 of the program. Line 7
public static void main( String[] args )
is the starting point of every Java application. The parentheses after the identifier main
indicate that its a program building block called a method. Java class declarations normally
contain one or more methods. For a Java application, one of the methods must be called main
and must be defined as shown in line 7; otherwise, the Java Virtual Machine (JVM) will not
execute the application. Methods perform tasks and can return information when they complete
their tasks.
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.)
HCI CHAPTER 1 -PONSURESH Page 5

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 Virtual Machine before any objects are made. The keyword void simply tells the
compiler that main( ) does not return a value. As you will see, methods may also return values.
Performing Output with System.out.println
Line 9
System.out.println( "Welcome to Java Programming!" );
instructs the computer to perform an actionnamely, to print the string of characters
contained between the double quotation marks (but not the quotation marks themselves). A string
is sometimes called a character string or a string literal. White-space characters in strings are
not ignored by the compiler.
The System.out object is known as the standard output object. It allows a Java
applications to display information in the command window from which it executes. Method
System.out.println displays (or prints) a line of text in the command window. The string in the
parentheses in line 9 is the argument to the method.
Classes and Methods
When you define a class, you are specifying the data that it contains and the code that
operates on that data. A class is declared by use of the class keyword. A simplified general form
of a class definition is shown here:
class classname {
type instance-variable1;
type instance-variable2;
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
HCI CHAPTER 1 -PONSURESH Page 6

}
type methodnameN(parameter-list)
{
// body of method
}
}

The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class are
called members of the class.
/* A program that uses the Box class.
Call this file BoxDemo.java
*/
class Box
{
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo
{
public static void main(String args[])
{
HCI CHAPTER 1 -PONSURESH Page 7

Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
As stated earlier, each object has its own copies of the instance variables. This means that
if you have two Box objects, each has its own copy of depth, width, and height. It is important to
understand that changes to the instance variables of one object have no effect on the instance
variables of another. For example, the following program declares two Box objects:
// This program declares two Box objects.
class Box
{
double width;
double height;
double depth;
}
class BoxDemo2
HCI CHAPTER 1 -PONSURESH Page 8

{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
The output produced by this program is shown here:
Volume is 3000.0
HCI CHAPTER 1 -PONSURESH Page 9

Volume is 162.0
As you can see, mybox1s data is completely separate from the data contained in
mybox2.
Introducing Methods
As mentioned earlier, classes usually consist of two things: instance variables and
methods. The topic of methods is a large one because Java gives them so much power and
flexibility. In fact, much of the next chapter is devoted to methods. However, there are some
fundamentals that you need to learn now so that you can begin to add methods to your classes.
This is the general form of a method:
type name(parameter-list)
{
// body of method
}
Here, type specifies the type of data returned by the method. This can be any valid type,
including class types that you create. If the method does not return a value, its return type must
be void. The name of the method is specified by name. This can be any legal identifier other than
those already used by other items within the current scope. The parameter-list is a sequence of
type and identifier pairs separated by commas. Parameters are essentially variables that receive
the value of the arguments passed to the method when it is called. If the method has no
parameters, then the parameter list will be empty.
// This program includes a method inside the box class.
class Box
{
double width;
double height;
double depth;
HCI CHAPTER 1 -PONSURESH Page 10

// display volume of a box
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume();
// display volume of second box
HCI CHAPTER 1 -PONSURESH Page 11

mybox2.volume();
}
}
This program generates the following output, which is the same as the previous version.
Volume is 3000.0
Volume is 162.0
You can use a parameterized method to improve the Box class. In the preceding examples,
the dimensions of each box had to be set separately by use of a sequence of statements, such as:
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
While this code works, it is troubling for two reasons. First, it is clumsy and error prone. For
example, it would be easy to forget to set a dimension. Second, in well-designed Java programs,
instance variables should be accessed only through methods defined by their class. In the future,
you can change the behavior of a method, but you cant change the behavior of an exposed
instance variable.
Thus, a better approach to setting the dimensions of a box is to create a method that takes
the dimensions of a box in its parameters and sets each instance variable appropriately. This
concept is implemented by the following program:
// This program uses a parameterized method.
class Box
{
double width;
HCI CHAPTER 1 -PONSURESH Page 12

double height;
double depth;
// compute and return volume
double volume()
{
return width * height * depth;
}
// sets dimensions of box
void setDim(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
}
class BoxDemo5
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// initialize each box
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
HCI CHAPTER 1 -PONSURESH Page 13

// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
As you can see, the setDim( ) method is used to set the dimensions of each box. For example,
when
mybox1.setDim(10, 20, 15);
is executed, 10 is copied into parameter w, 20 is copied into h, and 15 is copied into d. Inside
setDim( ) the values of w, h, and d are then assigned to width, height, and depth, respectively.
Access Specifiers
Access public protected private
Same class yes yes yes
Derived classes yes yes no
Outside classes yes no no

Static Members
When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object. You can declare both methods and variables to be
HCI CHAPTER 1 -PONSURESH Page 14

static. The most common example of a static member is main( ). main( ) is declared as static
because it must be called before any objects exist.
Instance variables declared as static are, essentially, global variables. When objects of its
class are declared, no copy of a static variable is made. Instead, all instances of the class share
the same static variable.
Methods declared as static have several restrictions:
They can only call other static methods.
They must only access static data.
They cannot refer to this or super in any way. (The keyword super relates to inheritance
and is described in the next chapter.)
If you need to do computation in order to initialize your static variables, you can declare a
static block that gets executed exactly once, when the class is first loaded. The following
example shows a class that has a static method, some static variables, and a static initialization
block:
// Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[])
{
HCI CHAPTER 1 -PONSURESH Page 15

meth(42);
}
}
Here is the output of the program:
Static block initialized.
x = 42
a = 3
b = 12
Outside of the class in which they are defined, static methods and variables can be used
independently of any object. To do so, you need only specify the name of their class followed by
the dot operator. For example, if you wish to call a static method from outside its class, you can
do so using the following general form:
classname.method( )
Here, classname is the name of the class in which the static method is declared.
Constructors
A constructor initializes an object immediately upon creation. It has the same name as
the class in which it resides and is syntactically similar to a method. Once defined, the
constructor is automatically called immediately after the object is created, before the new
operator completes. Constructors look a little strange because they have no return type, not even
void.
You can rework the Box example so that the dimensions of a box are automatically
initialized when an object is constructed. To do so, replace setDim( ) with a constructor. Lets
begin by defining a simple constructor that simply sets the dimensions of each box to the same
values. This version is shown here:
/* Here, Box uses a constructor to initialize the
dimensions of a box.
*/
class Box {
double width;
double height;
double depth;
HCI CHAPTER 1 -PONSURESH Page 16

// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

When this program is run, it generates the following results:
Constructing Box
Constructing Box
Volume is 1000.0
HCI CHAPTER 1 -PONSURESH Page 17

Volume is 1000.0
Finalize Method
Sometimes an object will need to perform some action when it is destroyed. For example,
if an object is holding some non-Java resource such as a file handle or character font, then you
might want to make sure these resources are freed before an object is destroyed. To handle such
situations, Java provides a mechanism called finalization. By using finalization, you can define
specific actions that will occur when an object is just about to be reclaimed by the garbage
collector.
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code
defined outside its class. It is important to understand that finalize( ) is only called just prior to
garbage collection.

You might also like