Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 110

History of Java

The microprocessor revolution’s most important contribution to date is that it made possible the
development of personal computers, which now number about a billion worldwide. Personal computers
have profoundly affected people’s lives and the ways organizations conduct and manage their business.
Microprocessors are having a profound impact in intelligent consumer-electronic devices. Recognizing
this, Sun Microsystems in 1991 funded an internal corporate research project code-named Green, which
resulted in a C++-based language that its creator, James Gosling, called Oak after an oak tree outside his
window at Sun. It was laterdiscovered that there already was a computer language by that name. When a
group of Sun people visited a local coffee shop, the name Java was suggested, and it stuck.
The Green project ran into some difficulties. The marketplace for intelligent consumer-electronic devices
was not developing in the early 1990s as quickly as Sun had anticipated.The project was in danger of
being canceled. By sheer good fortune, the World Wide Web exploded in popularity in 1993, and Sun
people saw the immediate potential of using Java to add dynamic content, such as interactivity and
animations, to web pages. This breathed new life into the project. Sun formally announced Java at an
industry conference in May 1995. Java garnered the attention of the business community because of the
phenomenal interest in the WorldWide Web. Java is now used to develop large-scale enterprise
applications, to enhance thefunctionality of web servers (the computers that provide the content we see in
our webbrowsers), to provide applications for consumer devices (e.g., cell phones, pagers and personal
digital assistants) and for many other purposes.

or

Somewhat surprisingly, the original impetus for Java was not the Internet! Instead, theprimary motivation
was the need for a platform-independent (that is, architecture-neutral)language that could be used to
create software to be embedded in various consumer electronicdevices, such as microwave ovens and
remote controls. As you can probably guess, manydifferent types of CPUs are used as controllers. The
trouble with C and C++ (and most otherlanguages) is that they are designed to be compiled for a specific
target. Although it is possibleto compile a C++ program for just about any type of CPU, to do so requires
a full C++ compilertargeted for that CPU. The problem is that compilers are expensive and time-
consuming tocreate. An easier—and more cost-efficient—solution was needed. In an attempt to find such
asolution, Gosling and others began work on a portable, platform-independent language thatcould be used
to produce code that would run on a variety of CPUs under differingenvironments. This effort ultimately
led to the creation of Java.
About the time that the details of Java were being worked out, a second, and ultimatelymore important,
factor was emerging that would play a crucial role in the future of Java.This second force was, of course,
the World Wide Web. Had the Web not taken shape atabout the same time that Java was being
implemented, Java might have remained a usefulbut obscure language for programming consumer
electronics. However, with the emergenceof the World Wide Web, Java was propelled to the forefront of
computer language design,because the Web, too, demanded portable programs.

P Page 1
Benefits of Java
 Object Oriented : In java everything is an Object. Java can be easily extended since it is
based on the Object model.
 Platform independent: Unlike many other programming languages including C and C+
+ when Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is distributed over the web and
interpreted by virtual Machine (JVM) on whichever platform it is being run.
 Simple :Java is designed to be easy to learn. If you understand the basic concept of OOP
java would be easy to master.
 Secure : With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
 Architectural- neutral :Java compiler generates an architecture-neutral object file
format which makes the compiled code to be executable on many processors, with the
presence Java runtime system.
 Portable :being architectural neutral and having no implementation dependent aspects of
the specification makes Java portable. Compiler and Java is written in ANSI C with a
clean portability boundary which is a POSIX subset.
 Robust :Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.
 Multi-threaded : With Java's multi-threaded feature it is possible to write programs that
can do many tasks simultaneously. This design feature allows developers to construct
smoothly running interactive applications.
 Interpreted :Java byte code is translated on the fly to native machine instructions and is
not stored anywhere. The development process is more rapid and analytical since the
linking is an incremental and light weight process.
 High Performance: With the use of Just-In-Time compilers Java enables high
performance.
 Distributed :Java is designed for the distributed environment of the internet.
 Dynamic : Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.

Typical Java Development Environment


We now explain the commonly used steps in creating and executing a Java application using
a Java development environment (illustrated in Fig. 1.1).
Java programs normally go through five phases—

1.Edit
2.Compile
3.Load
4.Verify
5.Execute.

P Page 2
Fig: Typical java environment

Phase 1: Creating a Program

Phase 1 consists of editing a file with aneditor program (normally known simply as an
editor). You type a Java program (typically referred to as source code) using the editor,
make any necessary corrections and save the program on a secondary storage device, such
as your hard drive. A file name ending with the .java extension indicates that the file contains
Java source code. On Windows, a simple editing program like Windows Notepad will suffice.
For organizations that develop substantial information systems, integrated development
environments (IDEs) are available from many major software suppliers, including
Sun Microsystems. IDEs provide tools that support the software development process,
including editors for writing and editing programs and debuggers for locating logic errors.
Popular IDEs include:

P Page 3
Eclipse (www.eclipse.org)
NetBeans (www.netbeans.org)
JBuilder (www.borland.com)
JCreator (www.jcreator.com)
BlueJ (www.blueJ.org),
jGRASP (www.jgrasp.org) and
jEdit (www.jedit.org).
we will be using netbeans as our IDE.

Phase 2: Compiling a Java Program into Bytecodes

In Phase 2, we use the command javac (the Java compiler) to compile a program. For example,
to compile a program called
HelloWorld.java
we would type
javac HelloWorld.java
in the command window of your system(i.ecommand Prompt in Windows). If the program compiles, the
compiler produces a .class file called HelloWorld.class that contains the compiled version of the
program. The class file contains the bytecodes that is executed by the java interpreter in (Phase 5).
Bytecodes are executed by the Java VirtualMachine (JVM). The JVM is one of the most widely used
virtual machines.Unlike machine language, which is dependent on specific computer hardware,
bytecodesare platform-independent instructions—they are not dependent on a particular hardware
platform. So Java’s bytecodes are portable—that is, the same bytecodes can executeon any platform
containing a JVM that understands the version of Java in which thebytecodes were compiled. The JVM is
invoked by the java command. For example, toexecute a Java application called
HelloWorld
you would type the command
javaHelloWorld
in a command window to invoke the JVM, which would then initiate the steps necessary
to execute the application. This begins Phase 3.

Phase 3: Loading a Program into Memory

In Phase 3, the program must be placed in memory before it can execute—known as loading.
The class loader takes the .class files containing the program’s bytecodes and transfers
them to primary memory. The class loader also loads any of the .class files provided
by Java that your program uses. The .class files can be loaded from a disk on your system.

Phase 4: Bytecode Verification

In Phase 4, as the classes are loaded, the bytecode verifier examines their bytecodes to ensure
that they are valid and do not violate Java’s security restrictions. Java enforces strong
security, to make sure that Java programs arriving over the network do not damage your
files or your system (as computer viruses and worms might).

Phase 5: Execution

In Phase 5, the JVM executes the program’s bytecodes, thus performing the actions specified
by the program. In early Java versions, the JVM was simply an interpreter for Java

P Page 4
bytecodes. This caused most Java programs to execute slowly because the JVM would interpret
and execute one bytecode at a time.
Note: Today’s JVMs typically execute bytecodes usinga combination of interpretation and so-called just-
in-time (JIT) compilation. In thisprocess, The JVM analyzes the bytecodes as they are interpreted,
searching for hot spots—parts of the bytecodes that execute frequently. For these parts, a just-in-time
(JIT) compiler—known as the Java HotSpot compiler—translates the bytecodes into the underlying
computer’s machine language. When the JVM encounters these compiled parts again,the faster machine-
language code executes. Thus Java programs actually go through twocompilation phases—one in which
source code is translated into bytecodes (for portabilityacross JVMs on different computer platforms) and
a second in which, during execution,the bytecodes are translated into machine language for the actual
computer on which the
program executes.

A First Program in Java: Printing a Line of Text


Every time you use a computer, you execute various applications that perform tasks for you. For
example, your e-mail application helps you send and receive e-mail, and your web browser lets you view
web pages from websites around the world. Computer programmers create such applications by writing
computer programs.
A Java application is a computer program that executes when you use the java command to launch the
Java Virtual Machine (JVM). Let us consider a simple application that displays a line of text. The
program and its output are shown below. The program illustrates several important Java language
features.
// Author:
//Date Created:
// Program to print a line of text
public class HelloWorld
{
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.println( "HelloWorld" );

} // end method main

} // end class Welcome1

Output:
Welcome to Java Programming!

Explanation:

In the above program // is a comment. Programmers insert comments to document programs and
improve their readability. This helps other people read and understand your programs. 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 author date and purpose of the
program. A comment that begins with // is called an end-of-line (or single-line) comment, because the
comment terminates at the end of the line on which it appears. A // comment also can begin in the middle
of a line and continue until the end of that line.

P Page 5
Traditional comments (also called multiple-line comments), such as
/* This is a traditional
comment. It can be
split over many lines */
can be spread over several lines. This type of comment begins with /* and ends with */. All text
between /* and */ is ignored by the compiler. Java incorporated traditional comments and end-of-line
comments from the C and C++ programming languages, respectively. In this book, we use end-of-line
comments.

Note:
Java also provides Javadoc comments that begins with /** and ends with */. As with
traditionalcomments, all text between the Javadoc comment is ignored by the compiler. Javadoc
comments enable programmers to embed program documentation directly in their programs. Such
comments are the preferred Java commenting format in industry. The javadoc utility program (part of
the Java SE Development Kit) reads Javadoc comments and uses them to prepare your program’s
documentation in HTMLformat.

public class HelloWorld


begins a class declaration for class Welcome1. Every program in Java consists of at least one class
declaration that is defined by us-the programmer. These are known as programmer-defined classes or
user-defined classes. The class keyword introduces a class declaration in Java and is immediately
followed by the class name (HelloWorld). Keywords (sometimes called reserved words) are reserved
for use by Java (we discuss the various keywords throughout the text) and are lowercase letters.

Note:
By convention, always begin a class name’s identifier with a capital letter and start each
subsequent word in the identifier with a capital letter. Java programmers know that such identifiers
normally represent Java classes, so naming your classes in this manner makes your programs more
readable. A Java class name is an identifier - a series of characters consisting of letters, digits,
underscores ( _ ) and dollar signs ($) that does not begin with a digit and does not contain spaces.

Java is case sensitive—that is, uppercase and lowercase letters are distinct, so a1 and A1 are
different identifiers.
A public class must be placed in a file that has the same name as the class (in terms of both
spellingand capitalization) plus the .java extension; otherwise, a compilation error occurs.

public static void main( String args[] )


is the starting point of every Java application. Java class declarations normally contain one or more
methods. For a Java application, exactly one of the methods must be called main and must be defined as
shown in above program, otherwise, the JVM will not execute the application. Methods are able to
perform tasks and return information when they complete their tasks. Keyword voidindicates that this
method will perform a task but willnot return any information when it completes its task.

System.out.println( "Welcome to Java Programming!" );


P Page 6
This statement instructs the computer to perform an action—namely, to print the string of characters
contained between the double quotation marks (but not the quotation marks themselves). The string in the
parentheses is the argument to the method. When System.out.println completes its task, it positions the
output cursor (the location where the next character will be displayed) to the beginning of the next line
in the command window.

Compiling and Executing Your First Java Application


1: To prepare to compile the program, open a command window and change to thedirectory where
the program is stored (Use the command cd tochange directories).

To compile the program, type

javac HelloWorld.java

If the program contains no syntax errors, the preceding command creates a new file
calledHelloWorld.class (known as the class filefor HelloWorld) containing the Java bytecodes that
represent our application. When we use the java command to execute the application,these bytecodes will
be executed by the JVM.

2. To execute the program, type

java HelloWorld
This launches the JVM, which loads the “.class” file for class HelloWorld. Note that the “.class” filename
extension is omitted from the preceding command; otherwise, the JVM will not executethe program. The
JVM calls method main. Next, the statement of main displays

"Welcome to Java Programming!"

P Page 7
Basic Syntax:
About Java programs, it is very important to keep in mind the following points.

 Case Sensitivity - Java is case sensitive which means identifier Hello and hello would
have different meaning in Java.
 Class Names - For all class names the first letter should be in Upper Case.

If several words are used to form a name of the class each inner words first letter should
be in Upper Case.

Example class MyFirstJavaClass


 Method Names - All method names should start with a Lower Case letter.

If several words are used to form the name of the method, then each inner word's first
letter should be in Upper Case.

Example public void myMethodName()


 Program File Name - Name of the program file should exactly match the class name.

When saving the file you should save it using the class name (Remember java is case
sensitive) and append '.java' to the end of the name. (if the file name and the class name
do not match your program will not compile).

Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
 public static void main(String args[]) - java program processing starts from the main()
method which is a mandatory part of every java program..

P Page 8
Java program structure
As we know java program is a collection of classes, a java program may contain many classes of which
only one class defines a main method. Classes contain data members and methods that operate on the data members
of the class. A java program may contain one or more sections as shown below:

Documentation Section
Package Statement
Import Statement
Interface Statement
Class Definition
Main Method Class
{
Main Method Definition
}

Java tokens
Unlike Cprogram which is a collection of function, java program is basically a collection of
classes. A class is defined by a set of declaration statements and methods containing executable
statements. Most statement contains expressions, which describe the actions to be carried out on data.
Smallest individual units in a program are knows as tokens. The compiler recognizes them for building up
expressions and statements.
There are five types of tokens. They are:
1. keywords
2. identifiers
3. literals
4. operators
5. seperators

Now that you have seen several short Java programs, it is time to more formally describethe atomic
elements of Java. In simple terms Java programs are a collection of whitespaces, comments and tokens.

Whitespace
Java is a free-form language. This means that you do not need to follow any special
indentationrules. For instance, the Example program could have been written all on one line or in
anyother strange way you felt like typing it, as long as there was at least one whitespace characterbetween
each token. In Java,whitespace is a space, tab, or newline.

Comments
There are three types of comments in Java. we 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 HTMLfile
that documents your program. The documentation comment begins with a /** and ends with a */.

P Page 9
Identifiers
Identifiers are used for class names, method names, and variable names. An identifier maybe any
descriptive sequence of uppercase and lowercase letters, numbers, or the underscoreand dollar-sign
characters. They must not begin with a number. Again, Java is case-sensitive, so VALUE is a different
identifier than Value.
Some examples of valid identifiers are

AverageTemp count $flag this_is_me num1

Invalid identifier names include these:

5rate average-temp

All java components require names. Names used for classes, variables and methods are called
identifiers.

In java there are several points to remember about identifiers. They are as follows:

 All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an


underscore (_).
 After the first character identifiers can have any combination of characters.
 A key word cannot be used as an identifier.
 Most importantly identifiers are case sensitive.
 Examples of legal identifiers:age, $salary, _value, __1_value
 Examples of illegal identifiers : 123abc, -salary

Literals
Literals in java are a sequence of characters that represent constant values to be stored in
variables. Aconstant value in Java is created by using a literal representation of it.
In java there are five major types of literals. They are:
a) Integer literals
b) Floating point literals
c) Character literals
d) Stirng literals
e) Boolean literals

For example, hereare 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 isa character
constant, and the last is a string.

P Page 10
Separators
In Java, there are a few characters that are used as separators. The most commonly usedseparator
in Java is the semicolon, 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
expressionsin control statements, and
surrounding cast types.

{} Braces Used to contain the values of automatically


initialized arrays. Also usedto 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 tochain statements
together inside a for statement.

. Period Used to separate package names from


subpackages and classes. Alsoused to separate a
variable or method from a reference variable.

The Java Keywords


There are 50 keywords currently defined in the Java language (see Table 2-1). These keywords,
combined with the syntax of the operators and separators, form the foundation of the Java
language. These keywords cannot be used as names for a variable, class, or method.

abstract continue for new switch


assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while

Note: The keywords const and goto are reserved but not used.
In addition to the keywords, Java reserves the following: true, false, and null. These arevalues defined by
Java. You may not use these words for the names of variables, classes, and so on.

P Page 11
Operators
An operator is a symbol that takes one or more arguments and operates on them to produce a result.
Operators are of many types discussed later.

Java Standard Edition Development Kit (JDK) 6

We will write our programs with the Java Standard Edition DevelopmentKit (JDK) 6. You can download
the latest version of JDK 6 and its documentation from
java.sun.com/javase/6/download.jsp.

Installing the Java Standard Edition Development Kit (JDK)


Before you can run the applications or build yourown applications, you must install the Java Standard
Edition Development Kit (JDK) 6or a Java development tool that supports Java SE 6.

After downloading the JDK installer, double click the installer program to begininstalling the JDK.
Accept all the default installation options. Ifyou change the default installation directory, be sure to write
down the exact name andlocation of the directory you choose, as you will need this information later in
the installationprocess. On Windows 7, the JDK is placed in the following directory by default:
C:\Program Files(x86)\Java\jdk1.6.0

Setting the PATH Environment Variable


The PATH environment variable on your computer designates which directories the computer
searches when looking for applications, such as the applications that enable you to
compile and run your Java applications.
You will now learn how to set the PATH environment variable on your computer to indicate
where the JDK’s tools are installed.

Steps for setting path environment variable

1.Opening the System Properties dialog.


For windows 7 Start>Control Panel>System and Security>System>Advanced
system settings or right click computer, select properties and then select Advanced
system settings.System Propertiesdialog for windows 7 appears as shown below.

P Page 12
2.Opening the Environment Variables dialog. Select the Advanced tab at the top of
the System Properties dialog. Click the Environment Variables button to
display the Environment Variables dialog. The environment variable dialog box is as
shown below.

P Page 13
3.Creating and setting the PATH variable. Click new on the system variable. new
System Variable dialog box appears. On the variable name type path and on the variable
value give the directory where your jdk is installed as shown below.

Click the OK button.

Note: If you do not set the PATH variable correctly, you willreceive a message like:
'javac' is not recognized as an internal or external command,
operable program or batch file.
When you try to compile your java application.In this case, go back to the beginning of this section
and recheck your steps.

P Page 14
Introductionto Java Applications
A First Program in Java: Printing a Line of Text

//Author: …………………
//Date:………………….
/* program to print a
Line of text */
public class HelloWorld
{
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.println( "Hello world" );
}
}
Output:

Hello world

Explanation:

In the above program // is a comment. Programmers insert comments to document programs and
improve their readability. This helps other people read and understand your programs. 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 author date and purpose of the
program. A comment that begins with // is called an end-of-line (or single-line) comment, because the
comment terminates at the end of the line on which it appears. A // comment also can begin in the middle
of a line and continue until the end of that line.
Traditional comments (also called multiple-line comments), such as
/* This is a traditional
comment. It can be
split over many lines */
can be spread over several lines. This type of comment begins with /* and ends with */. All text
between /* and */ is ignored by the compiler. Java incorporated traditional comments and end-of-line
comments from the C and C++ programming languages, respectively. In this book, we use end-of-line
comments.
Note: Java also provides Javadoc comments that begins with /** and ends with */. As with traditional
comments, all text between the Javadoc comment is ignored by the compiler. Javadoc comments enable
programmers to embed program documentation directly in their programs. Such comments are the
preferred Java commenting format in industry. The javadoc utility program (part of the Java SE
Development Kit) reads Javadoc comments and uses them to prepare your program’s documentation in
HTML
format.

public class Welcome1


begins a class declaration for class Welcome1. Every program in Java consists of at least one class
declaration that is defined by you—the programmer. These are known as programmer-defined classes
or user-defined classes. The class keyword introduces a class declaration in Java and is immediately

P Page 15
followed by the class name (Welcome1). Keywords (sometimes called reserved words) are reserved for
use by Java (we discuss the various keywords throughout the text) and are lowercase letters.

Note:
By convention, always begin a class name’s identifier with a capital letter and start each subsequent word in the
identifier with a capital letter. Java programmers know that such identifiers normally represent Java classes, so naming your
classes in this manner makes your programs more readable. A Java class name is an identifier - a series of characters
consisting of letters, digits, underscores ( _ ) and dollar signs ($) that does not begin with a digit and does not contain spaces.

Java is case sensitive—that is, uppercase and lowercase letters are distinct, so a1 and A1 are different identifiers.
A public class must be placed in a file that has the same name as the class (in terms of both spelling
and capitalization) plus the .java extension; otherwise, a compilation error occurs.

public static void main( String args[] )


is the starting point of every Java application. Java class declarations normally contain one or more
methods. For a Java application, exactly one of the methods must be called main and must be defined as
shown in above program, otherwise, the JVM will not execute the application. Methods are able to
perform tasks and return information when they complete their tasks. Keyword voidindicates that this
method will perform a task but will
not return any information when it completes its task.

System.out.println( "Welcome to Java Programming!" );


This command is an example of a subroutine call statement. This statement instructs the computer to
perform an action—namely, to print the string of characters contained between the double quotation
marks (but not the quotation marks themselves). The string in the parentheses is the argument to the
method. This subroutine is a built-in subroutine one that is already defined as part of the language.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.println. While too complicated toexplain in detail at this time, briefly,
System is a predefined class that provides access to thesystem,out is the output stream object that is
connected to the console and println is the method of object out.
Note:
When System.out.println completes its task, it positions the output cursor (the location where
the next character will be displayed) to the beginning of the next line in the command window.

Variables and datatypes

P Page 16
Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory.

Based on the data type of a variable, the operating system allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals, or characters in these variables.

There are two data types available in Java:

 Primitive Data Types


 Reference/Object Data Types

Primitive Data Types:


There are eight primitive data types supported by Java. Primitive data types are predefined by the
language and named by a key word. Let us now look into detail about the eight primitive data
types.

byte:
 Byte data type is a 8-bit signed two's complement integer.
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers, since a
byte is four times smaller than an int.
 Example : byte a = 100 , byte b = -50

short:
 Short data type is a 16-bit signed two's complement integer.
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767(inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an int
 Default value is 0.
 Example : short s= 10000 , short r = -20000

int:
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648.(-2^31)
 Maximum value is 2,147,483,647(inclusive).(2^31 -1)

P Page 17
 Int is generally used as the default data type for integral values unless there is a concern
about memory.
 The default value is 0.
 Example : int a = 100000, int b = -200000

long:
 Long data type is a 64-bit signed two's complement integer.
 Minimum value is -9,223,372,036,854,775,808.(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
 This type is used when a wider range than int is needed.
 Default value is 0L.
 Example : long a = 100000L, int b = -200000L

float:
 Float data type is a single-precision 32-bit IEEE 754 floating point.
 Float is mainly used to save memory in large arrays of floating point numbers.
 Default value is 0.0f.
 Float data type is never used for precise values such as currency.
 Example : float f1 = 234.5f
 Note: when storing a value in float variable, we need the letter ’f’ at the end like in
above statement.

double:
 double data type is a double-precision 64-bit IEEE 754 floating point.
 This data type is generally used as the default data type for decimal values. generally the
default choice.
 Double data type should never be used for precise values such as currency.
 Default value is 0.0d.
 Example : double d1 = 123.4

boolean:
 boolean data type represents one bit of information.
 There are only two possible values : true and false.
 This data type is used for simple flags that track true/false conditions.
 Default value is false.
 Example : boolean one = true

char:
P Page 18
 char data type is a single 16-bit Unicode character.
 Minimum value is '\u0000' (or 0).
 Maximum value is '\uffff' (or 65,535 inclusive).
 Char data type is used to store any character.
 Example . char letterA ='A'

Fig Basic Data types in Java

Reference Data Types:


 Reference variables are created using defined constructors of the classes. They are used
to access objects. These variables are declared to be of a specific type that cannot be
changed. For example, Employee, Puppy etc.
 Class objects, and various type of array variables come under reference data type.
 Default value of any reference variable is null.
 A reference variable can be used to refer to any object of the declared type or any
compatible type.
 Example : Animal animal = new Animal("giraffe");

Declaration of variables

In Java, all variables must be declared before they can be used. Declaration of variable
does three things:

P Page 19
1. it tells compiler what the variable name is.

2. it specifies what type of data the variable will hold.

3. the place of declaration specifies the scope of the variable.

The basic form of a variable declaration is shown here:

Data_type variable_name;

In case of similar data-type you can declare variable as:

Data_type variable1, variable2,……………………..variableN;

Giving values to variables

A variable must be given a value after it has been declared before it is used in an expression. This
can be achieved in two ways:

a) By using an assignment statement

b) By using predefined class in java

By using assignment statement:

Simple method of giving value to a variable is through the assignment statement as


follow:

variableName = value;

for e.g:

int x = 200;

float y = 23.56f;

char ch = ‘d’;

By using predefined class in java:

P Page 20
There a number of classes in java that can be used to take input from the user. Some of
them are DataInputStream, Scanner etc. we use the method nextInt() of Scanner class. The
Scanner class is inside the package java.util. So to use Scanner class in your program you must
import its package. This can be done as:

import java.util.Scanner

or

import java.util.*

Scanner input = new Scanner( System.in ); (We use the new operator in Java to create an
instance of a class)

Here input is a reference variable.

A Scanner classenables a program to read data (e.g., numbers) for use in a program. The datacan come
from many sources, such as a file on disk or the user at the keyboard. Beforeusing a Scanner, the program
must create it and specify the source of the data.The equal sign (=) indicates that Scanner variable input
should be initialized(i.e., prepared for use in the program) in its declaration with the result of the
expressionnew Scanner( System.in ) to the right of the equal sign. This expression creates a
Scanner object that reads data typed by the user at the keyboard. Recall that the standardoutput object,
System.out, allows Java applications to display characters in the commandwindow. Similarly, the
standard input object, System.in, enables Java applications toread information typed by the user. So,
above statement creates a Scanner that enables the applicationto read information typed by the user at the
keyboard.
Now we use Scanner object input’s nextInt method to obtain an integer from the user at the
keyboard.At this point the program waits for the user to type the number and press the Enter
key to submit the number to the program.

Scope of variables: We will now explain the various variable types available in Java Language
according to the scope of the varibale. There are three kinds of variables in Java:

 Local variables
 Instance variables
 Class/static variables

Local variables :

P Page 21
 Local variables are declared in methods, constructors, or blocks.
 Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor or block.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method, constructor or block.
 Local variables are implemented at stack level internally.
 There is no default value for local variables so local variables should be declared and an
initial value should be assigned before the first use.

Example:
Here age is a local variable. This is defined inside myAge() method and its scope is limited to
this method only.

publicclassTest
{
publicvoid myAge()
{
int age =0;
age = age +7;
System.out.println("my age is : "+ age);
}

publicstaticvoid main(String args[])


{
Test test =newTest();
test.myAge();
}
}

This would produce following result:

My age is: 7

Example:
Following example uses age without initializing it, so it would give an error at the time of
compilation.

publicclassTest{
publicvoid myAge(){
int age;
age = age +7;
System.out.println("my age is : "+ age);
}

publicstaticvoid main(String args[]){


Test test =newTest();
test.myAge();
}

P Page 22
}

This would produce following error while compiling it:

Test.java:4:variable number might not have been initialized


age = age + 7;
^
1 error

Instance variables :
 Instance variables are declared in a class, but outside a method, constructor or any block.
 When a space is allocated for an object in the heap a slot for each instance variable value
is created.
 Instance variables are created when an object is created with the use of the key word
'new' and destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object.s state that must be present through
out the class.
 Instance variables can be declared in class level before or after use.
 Access modifiers can be given for instance variables.
 The instance variables are visible for all methods, constructors and block in the class.
Normally it is recommended to make these variables private (access level).However
visibility for subclasses can be given for these variables with the use of access modifiers.
 Instance variables have default values. For numbers the default value is 0, for Booleans it
is false and for object references it is null. Values can be assigned during the declaration
or within the constructor.
 Instance variables can be accessed directly by calling the variable name inside the class.
However within static methods and different class (when instance variables are given
accessibility) the should be called using the fully qualified name .
ObjectReference.VariableName.

Example:
import java.io.*;

publicclassEmployee{
// this instance variable is visible for any child class.
publicString name;

// salary variable is visible in Employee class only.


privatedouble salary;

// The name variable is assigned in the constructor.


publicEmployee(String empName){
name = empName;
}

// The salary variable is assigned a value.

P Page 23
publicvoid setSalary(double empSal){
salary = empSal;
}

// This method prints the employee details.


publicvoid printEmp(){
System.out.println("name : "+ name );
System.out.println("salary :"+ salary);
}

publicstaticvoid main(String args[]){


Employee empOne =newEmployee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}

This would produce following result:

name : Ransika
salary :1000.0

Class/static variables :
 Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
 Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final and static. Constant variables never
change from their initial value.
 Static variables are stored in static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the program
stops.
 Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.
 Default values are same as instance variables. For numbers the default value is 0, for
Booleans it is false and for object references it is null. Values can be assigned during the
declaration or within the constructor. Additionally values can be assigned in special static
initializer blocks.
 Static variables can be accessed by calling with the class name .
ClassName.VariableName.
 When declaring class variables as public static final, then variables names (constants) are
all in upper case. If the static variables are not public and final the naming syntax is the
same as instance and local variables.

Example:

P Page 24
import java.io.*;

publicclassEmployee{
// salary variable is a private static variable
privatestaticdouble salary;

// DEPARTMENT is a constant
publicstaticfinalString DEPARTMENT ="Development ";

publicstaticvoid main(String args[]){


salary =1000;
System.out.println(DEPARTMENT+"average salary:"+salary);
}
}

This would produce following result:

Development average salary:1000

Note: If the variables are access from an outside class the constant should be accessed as
Employee.DEPARTMENT

Symbolic Constants

Unlike symbolic constants in c/c++ which are defined using #define statement and const, the
symbolic constants in java are declared by using the keyword final and also the symbolic
constants are declared by specifying type in java.

A constant is declared as follow:

final type symbolic-name = value ;

note:

symbolic constants name are written in capital letters to distinguish them from other
variables. However this is a convention not a rule.

use symbolic constants when your program uses a fixed constant number throughout
the program.

The final modifier in Java means that that named value is a constant and cannot be
modified.

Program to illustrate the concept of symbolic constant

publicclass SymbolicConstant {

P Page 25
publicstaticvoid main(String args[]){
finalfloat PI= 3.142f; //static is not permitted only final is permitted
int radius=5;
float areaOfCircle=PI*radius*radius;
System.out.print("area of cirlce="+areaOfCircle);

}
}
Output:
area of cirlce=78.55

publicclass SymbolicConstant {
finalstaticfloatPI= 3.142f; //the modifier static is compulsory here
publicstaticvoid main(String args[]){

int radius=5;
float areaOfCircle=PI*radius*radius;
System.out.print("area of cirlce="+areaOfCircle);

}
}
Output:
area of cirlce=78.55

Type Casting
The process of converting one data type to another is called casting.
Rules:
Four integer datatype can be cast to any other type except Boolean.
Two floating point datatype can be cast to any other except Boolean.

Automatic conversion

P Page 26
Conversion of small size data type to larger size datatype is automatic conversion and there is no loss of
informationAny “wider” data type can have a lower data type assigneddirectly to it and the promotion to
the new type will occurautomatically. This is known as automatic conversion or widening or promotion.
The following programs illustrate this point.

publicclass TypeCasting{
publicstaticvoid main(String args[]){
byte b=50;
System.out.println("b = "+b);
short s;
s=b;
System.out.println("converting b to s:value of s is = "+s);
int i;
i=b;
System.out.println("converting b to i:value of i is = "+i);
long l;
l=b;
System.out.println("converting b to l:value of l is = "+l);
float f;
f=b;
System.out.println("converting b to f:value of f is = "+f);
double d;
d=b;
System.out.println("converting b to d:value of d is = "+d);

}
}
Output:
b = 50
converting b to s:value of s is = 50
converting b to i:value of i is = 50
converting b to l:value of l is = 50
converting b to f:value of f is = 50.0
converting b to d:value of d is = 50.0

we can reduce a wider type to a narrower type by casting it. we do this by putting the data type
name in parentheses andputting this name in front of the value you wish to convert. There is loss
of information in this case. The following program illustrates this point.

publicclass TypeCasting{
publicstaticvoid main(String args[]){

P Page 27
short s=1986;
System.out.println("s = "+s);
byte b;
b=(byte)s; /*here we have to do type casting since size of byte is
smaller than the size of s. this is called narrowing and there is loss of
information*/
System.out.println("converting s to b:value of b is = "+b);
int i;
i=s;
System.out.println("converting s to i:value of i is = "+i);
long l;
l=s;
System.out.println("converting s to l:value of l is = "+l);
float f;
f=s;
System.out.println("converting s to f:value of f is = "+f);
double d;
d=s;
System.out.println("converting s to d:value of d is = "+d);

}
}
Output:
s = 1986
converting s to b:value of b is = -62
converting s to i:value of i is = 1986
converting s to l:value of l is = 1986
converting s to f:value of f is = 1986.0
converting s to d:value of d is = 1986.0

program 3:

publicclass TypeCasting{
publicstaticvoid main(String args[]){

P Page 28
int i=4782996;
System.out.println("i = "+i);
byte b;
b=(byte)i; /*here we have to do type casting since size of byte is
smaller than the size of int. this is called narrowing and there is loss of
information*/
System.out.println("converting i to b:value of b is = "+b);
short s;
s=(short)i;/*here we have to do type casting since size of short is
smaller than the size of int. this is called narrowing and there is loss of
information*/

System.out.println("converting i to s:value of s is = "+s);


longl;
l=i;
System.out.println("converting i to l:value of l is = "+l);
float f;
f=i;
System.out.println("converting i to f:value of f is = "+f);
double d;
d=i;
System.out.println("converting i to d:value of d is = "+d);

}
}

Output:
i = 4782996
converting i to b:value of b is = -108
converting i to s:value of s is = -1132
converting i to l:value of l is = 4782996
converting i to f:value of f is = 4782996.0
converting i to d:value of d is = 4782996.0
Note:
Java defines several type promotion rules that apply to expressions. They are as follows: First,
all byte, short, and char values are promoted to int, as just described. Then, if one operand
is a long, the whole expression is promoted to long. If one operand is a float, the entire
expression is promoted to float. If any of the operands is double, the result is double.

Operators, precedence and expression


P Page 29
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations.

Operators are used in program to manipulate data and variables.

The data and variable on which the operator acts upon are called operands.

For e.g. 8+9

Here, + is operator and since it acts upon 8 and 9 they are called operands.

Operator in java can be classified as:

a. Arithmetic operator:
Arithmetic operators perform arithmetic operation.
Java provides all the basic arithmetic operators.

Operators Meaning
+ Addition
- Subtraction
/ Division
* Multiplication
% Modulo Division

b. Relational operator:
When we want to compare two quantities (operands) and depending upon their
relation, take certain decisions, we use relational operator. For e.g. we may
compare the age of two person, price of two item etc.
The value of relational expression is either 1 (if condition is true) or 0 (if
condition is false).
Java supports 6 relational operators.

Relational operator Meaning


< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

Note: Arithmetic operators have high priority than relational operator.


Relational operator are used in decision control instruction as well as in loop
control instruction.

P Page 30
c. Logical operator:
Logical operator performs logical operation.
Java has the following three logical operator:

Logical operator Meaning


&& AND
|| OR
! NOT

Condition Condition2 Condition1&&condition2 Condition1||condition2 ! !condittion2


1 condition1
0 0 0 0 1 1
0 1 0 1 1 0
1 0 0 1 0 1
1 1 1 1 0 0

Note: the logical operators && and || are used when we want to test more than one condition and
make decision.

Logical operator also yield a value of either 1 or 0.

They are used in decision control instruction.

d. Assignment operator:

Assignment operator is used to assign the result of an expression to a variable or


simply to assign a value to a variable.

For e.g.

A = 3;

A = 3+4-9;

Assignment operator can be combined with arithmetic operator to form short-


hand assignment operator. For e.g.

a+=b means a=a+b

a-=b means a=a-b

a*=b means a=a*b

a/=b means a=a/b

a%=b means a=a%b

P Page 31
e. Increment and decrement operator:
The operator ++ and – are called increment and decrement operator respectively.
The increment operator ++ adds 1 to the operand while the decrement operator –
subtracts 1 from the operand.
Both the increment and decrement operator may appear either in the front of
variable or after the variable. If they appear in front, they are called prefix and if
they appear after, they are called postfix.
For e.g.

Pre increment Post increment


++a a++

Pre decrement Post decrement


--a a--

Note: In case of prefix first perform the operation (increment or decrement)


then use the value in expression.
In case of post fix first use the value in expression and then perform
the operation (increment or decrement).

f. Bitwise operator:
Bitwise operator perform operation of data at bit level.
These operators are used for testing the bits or shifting them right or left.

Bitwise operator Meaning


& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
>>> Shift right with zero fill

g. Special operators

P Page 32
Java supports some special operators of interest such as:

a)Conditional Operator ( ? : ):

Conditional operator is also known as the ternary operator. This operator


consists of three operands and is used to evaluate boolean expressions. The goal
of the operator is to decide which value should be assigned to the variable. The
operator is written as :

variable x = (expression) ? value if true : value if false

b)instanceof operator
the instance is an object reference operator and returns true if the object
on the left-hand side is an instance of the class given on the right hand side. This operator is used to
determine whether the object belongs to a particular class or not.

Operator precedence
Operators are shown in decreasing order of precedence from top to bottom

Precedence of Java Operators:


Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedenace than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedenace operators will be evaluated first.

Category  Operator  Associativity 


Postfix  () [] . (dot operator) Left to right 
Unary  ++ - - ! ~ Right to left 
Multiplicative   * / %  Left to right 
Additive   + -  Left to right 
Shift   >>>>><<   Left to right 
Relational   >>= <<=   Left to right 
Equality   == !=  Left to right 
Bitwise AND  &  Left to right 
Bitwise XOR  ^  Left to right 
Bitwise OR  |  Left to right 

P Page 33
Logical AND  &&  Left to right 
Logical OR  ||  Left to right 
Conditional  ?:  Right to left 
Assignment  = += -= *= /= %= >>= <<= &= ^= |=  Right to left 
Comma  ,  Left to right 

When there are more than one operator of same precedence we go by the rule of associativity. When we
say that operators are applied from left to right, we are referring to their associativity.
Some operators associate from right to left.

Control Flow in java


Decision control instruction:

Decision making statements in Java programming.There are two types of decision making
statements in Java. They are:

 if statements
 switch statements

The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.

Syntax:
The syntax of an if statement is:

if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}

If the boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement(after the closing curly brace)
will be executed.

Example:
public class Test {

public static void main(String args[]){


int x = 10;

P Page 34
if( x < 20 ){
System.out.print("This is if statement");
}
}
}

This would produce following result:

This is if statement

The if...else Statement:


An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.

Syntax:
The syntax of a if...else is:

if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}

Example:
public class Test {

public static void main(String args[]){


int x = 30;

if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}

This would produce following result:

This is else statement

P Page 35
The if...else if...else Statement:
An if statement can be followed by an optional else if...else statement, which is very usefull to
test various conditions using single if...else if statement.

When using if , else if , else statements there are few points to keep in mind.

 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of he remaining else if's or else's will be tested.

Syntax:
The syntax of a if...else is:

if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}

Example:
public class Test {

public static void main(String args[]){


int x = 30;

if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}

This would produce following result:

Value of X is 30

P Page 36
Nested if...else Statement:
It is always legal to nest if-else statements, which means you can use one if or else if statement
inside another if or else if statement.

Syntax:
The syntax for a nested if...else is as follows:

if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}

You can nest else if...else in the similar way as we have nested if statement.

Example:
public class Test {

public static void main(String args[]){


int x = 30;
int y = 10;

if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
}

This would produce following result:

X = 30 and Y = 10

The switch Statement:


A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each case.

P Page 37
Syntax:
The syntax of enhanced for loop is:

switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}

The following rules apply to a switch statement:

 The variable used in a switch statement can only be a byte, short, int, or char.
 You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
 The value for a case must be the same data type as the variable in the switch, and it must
be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.

Example:

public class Test {

public static void main(String args[]){


//char grade = args[0].charAt(0);
char grade = 'C';

switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :

P Page 38
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}

Compile and run above program using various command line arguments. This would produce
following result:

$ java Test
Well done
Your grade is a C
$

Looping mechanism in Java


Java has very flexible three looping mechanisms. You can use one of the following three loops:

 while Loop
 do...while Loop
 for Loop

As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop:


A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:

The syntax of a while loop is:

while(Boolean_expression)
{
//Statements
}

When executing, if the boolean_expression result is true then the actions inside the loop will be
executed. This will continue as long as the expression result is true.

P Page 39
Here key point of the while loop is that the loop might not ever run. When the expression is
tested and the result is false, the loop body will be skipped and the first statement after the while
loop will be executed.

Example:

public class Test {

public static void main(String args[]) {


int x = 10;

while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

This would produce following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The do...while Loop:


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.

Syntax:

The syntax of a do...while loop is:

do
{
//Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.

P Page 40
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in
the loop execute again. This process repeats until the Boolean expression is false.

Example:

public class Test {

public static void main(String args[]){


int x = 10;

do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}

This would produce following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The for Loop:


A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.

A for loop is useful when you know how many times a task is to be repeated.

Syntax:

The syntax of a for loop is:

for(initialization; Boolean_expression; update)


{
//Statements
}

Here is the flow of control in a for loop:

P Page 41
 The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here, as
long as a semicolon appears.
 Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop does not execute and flow of control jumps to the next
statement past the for loop.
 After the body of the for loop executes, the flow of control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement
can be left blank, as long as a semicolon appears after the Boolean expression.
 The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then update step,then Boolean expression). After the
Boolean expression is false, the for loop terminates.

Example:

public class Test {

public static void main(String args[]) {

for(int x = 10; x < 20; x = x+1) {


System.out.println("value of x : " + x );

}
}
}

This would produce following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Note: Enhanced for loop in Java:


As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.

Syntax:

The syntax of enhanced for loop is:

for(declaration : expression)
{
//Statements

P Page 42
}

 Declaration . The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for
block and its value would be the same as the current array element.
 Expression . This evaluate to the array you need to loop through. The expression can be
an array variable or method call that returns an array.

Example:

//using enhanced for loop

public class EnhanceFor {

public static void main(String[] args) {

int array[]={12,45,34,23};

for(int i=0;i<4;i++)

if (array[i]%2==0)

System.out.println(array[i]);

//using enhanced for loop

public class EnhanceFor {

public static void main(String[] args) {

int array[]={12,45,34,23};

for(int i:array)

if(i%2==0)

System.out.println(i);

P Page 43
run:

12

34

The break Keyword:


The break keyword is used to stop the entire loop. The break keyword must be used inside any
loop or a switch statement.

The break keyword will stop the execution of the innermost loop and start executing the next line
of code after the block.

Syntax:

The syntax of a break is a single statement inside any loop:

break;

Example:

public class Break {

public static void main(String args[]) {

int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {

if( x == 30 ) {

break;

System.out.println( x );

run:

P Page 44
10

20

The continue Keyword:


The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.

 In a for loop, the continue keyword causes flow of control to immediately jump to the
update statement.
 In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.

Syntax:

The syntax of a continue is a single statement inside any loop:

continue;

Example:

public class Continue {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.println( x );
}
}
}

run:

10
20
40
50

P Page 45
Math
Math class methods allow the programmer to perform certain common mathematical calculations.
Here we use various math class method to perform several operation.The class Math contains methods
for performing basic numeric operations such as the elementary exponential, logarithm, square root,
and trigonometric functions.

Field Detail
E
public static final double E
The double value that is closer than any other to e, the base of the natural logarithms.

PI
public static final double PI
The double value that is closer than any other to pi, the ratio of the circumference of a circle to
its diameter.

Method Detail
sin
public static double sin(double a)

parameters

a - an angle, in radians.

note:Returns the trigonometric sine of an angle. Special cases:

 If the argument is NaN or an infinity, then the result is NaN.


 If the argument is zero, then the result is a zero with the same sign as the argument.

toRadians
public static double toRadians(double angdeg)
Converts an angle measured in degrees to an approximately equivalent angle measured in
radians. The conversion from degrees to radians is generally inexact.

Parameters:

angdeg - an angle, in degrees

Returns:

P Page 46
the measurement of the angle angdeg in radians.

log
public static double log(double a)
Returns the natural logarithm (base e) of a double value. Special cases:

 If the argument is NaN or less than zero, then the result is NaN.
 If the argument is positive infinity, then the result is positive infinity.
 If the argument is positive zero or negative zero, then the result is negative infinity.

The computed result must be within 1 ulp of the exact result. Results must be semi-
monotonic.

Parameters:

a - a value

Returns:

the value ln a, the natural logarithm of a.

log10
public static double log10(double a)
Returns the base 10 logarithm of a double value. Special cases:

 If the argument is NaN or less than zero, then the result is NaN.
 If the argument is positive infinity, then the result is positive infinity.
 If the argument is positive zero or negative zero, then the result is negative infinity.
 If the argument is equal to 10n for integer n, then the result is n.

The computed result must be within 1 ulp of the exact result. Results must be semi-
monotonic.

Parameters:

a - a value

Returns:

the base 10 logarithm of a.

sqrt
public static double sqrt(double a)
Returns the correctly rounded positive square root of a double value. Special cases:

 If the argument is NaN or less than zero, then the result is NaN.
 If the argument is positive infinity, then the result is positive infinity.

P Page 47
 If the argument is positive zero or negative zero, then the result is the same as the
argument.

Otherwise, the result is the double value closest to the true mathematical square root of the
argument value.
Parameters:

a - a value.

Returns:

the positive square root of a. If the argument is NaN or less than zero, the result is NaN.

public static double pow(double a,double b)

random
public static double random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Returned values are chosen pseudorandomly with (approximately) uniform distribution from
that range.

abs
public static int abs(int a)
Returns the absolute value of an int value. If the argument is not negative, the argument is
returned. If the argument is negative, the negation of the argument is returned.

abs
public static long abs(long a)
Returns the absolute value of a long value. If the argument is not negative, the argument is
returned. If the argument is negative, the negation of the argument is returned.

abs
public static float abs(float a)
Returns the absolute value of a float value. If the argument is not negative, the argument is
returned. If the argument is negative, the negation of the argument is returned.

abs
public static double abs(double a)
Returns the absolute value of a double value. If the argument is not negative, the argument is
returned. If the argument is negative, the negation of the argument is returned.

max
public static int max(int a,
int b)
Returns the greater of two int values. That is, the result is the argument closer to the value of
Integer.MAX_VALUE. If the arguments have the same value, the result is that same value.

Parameters:

P Page 48
a - an argument.

b - another argument.

Returns:

the larger of a and b.

max
public static long max(long a,long b)
Returns the greater of two long values. That is, the result is the argument closer to the value of
Long.MAX_VALUE. If the arguments have the same value, the result is that same value.

Parameters:

a - an argument.

b - another argument.

Returns:

the larger of a and b.

max
public static float max(float a,
float b)
Returns the greater of two float values. That is, the result is the argument closer to positive
infinity. If the arguments have the same value, the result is that same value. If either value is
NaN, then the result is NaN. Unlike the numerical comparison operators, this method considers
negative zero to be strictly smaller than positive zero. If one argument is positive zero and the
other negative zero, the result is positive zero.

Parameters:

a - an argument.

b - another argument.

Returns:

the larger of a and b.

max
public static double max(double a,double b)
Returns the greater of two double values. That is, the result is the argument closer to positive
infinity. If the arguments have the same value, the result is that same value. If either value is
NaN, then the result is NaN. Unlike the numerical comparison operators, this method considers

P Page 49
negative zero to be strictly smaller than positive zero. If one argument is positive zero and the
other negative zero, the result is positive zero.

Parameters:

a - an argument.

b - another argument.

Returns:

the larger of a and b.

min
public static int min(int a,
int b)
Returns the smaller of two int values. That is, the result the argument closer to the value of
Integer.MIN_VALUE. If the arguments have the same value, the result is that same value.

Parameters:

a - an argument.

b - another argument.

Returns:

the smaller of a and b.

min
public static long min(long a,
long b)
Returns the smaller of two long values. That is, the result is the argument closer to the value of
Long.MIN_VALUE. If the arguments have the same value, the result is that same value.

Parameters:

a - an argument.

b - another argument.

Returns:

the smaller of a and b.

min
public static float min(float a,
float b)

P Page 50
Returns the smaller of two float values. That is, the result is the value closer to negative
infinity. If the arguments have the same value, the result is that same value. If either value is
NaN, then the result is NaN. Unlike the numerical comparison operators, this method considers
negative zero to be strictly smaller than positive zero. If one argument is positive zero and the
other is negative zero, the result is negative zero.

Parameters:

a - an argument.

b - another argument.

Returns:

the smaller of a and b.

min
public static double min(double a,
double b)
Returns the smaller of two double values. That is, the result is the value closer to negative
infinity. If the arguments have the same value, the result is that same value. If either value is
NaN, then the result is NaN. Unlike the numerical comparison operators, this method considers
negative zero to be strictly smaller than positive zero. If one argument is positive zero and the
other is negative zero, the result is negative zero.

Parameters:

a - an argument.

b - another argument.

Returns:

the smaller of a and b.

P Page 51
P Page 52
Strings
In java’s String, is not a simple type. Nor is it simplyan array of characters. Rather, String is
defined as an object, and a full description of it requires anunderstanding of several object-related
features.
The String type is used to declare string variables. You can also declare arrays of strings.
Aquoted string constant can be assigned to a String variable. A variable of type String can
be assigned to another variable of type String. You can use an object of type String as an
argument to println( ). For example, consider the following fragment:

String str = "this is a test";


System.out.println(str);

Here, str is an object of type String. It is assigned the string “this is a test”. This string isdisplayed by the
println( ) statement.As you will see later, String objects have many special features and attributes that
make them quite powerful and easy to use.

publicclass StringProgram {
publicstaticvoid main(String args[]){
String name = "Ram Shrestha";//String name = new String("Ram Shrestha");

System.out.println("my name is " +name);


}
}
Output:
my name is Ram Shrestha

publicclass StringProgram {
publicstaticvoid main(String args[]){

String name1 = new String("Ram Shrestha");


String nameInUpperCase=name1.toUpperCase();
//String class contains toUpperCase() method to convert string to upper case

System.out.println("name in upper case is "+nameInUpperCase);


String nameInLowerCase=name1.toLowerCase();
//String class contains tolowerCase() method to convert string to lower case

System.out.println("name in lower case is "+nameInLowerCase);


String name2 = new String("Hari Shrestha");
int result;
result=name1.compareTo(name2);
//string class contains compareTo() method to compare two string

if(result==0)
System.out.println("the two words are same");
if(result<0)
System.out.println(name1+" comes first in dictionary order than
"+name2);
if(result>0)

P Page 53
System.out.println(name2+" comes first in dictionary order
"+name1);
char check='@';
String emailAddress = "bmanpatigmail.com";
result=emailAddress.indexOf(check);
//indexof returns position in which the character is found, if not found returns -1
System.out.println(result);
if(result==-1)
System.out.println("invalid email address");

}
}
Run:
name in upper case is RAM SHRESTHA
name in lower case is ram shrestha
Hari Shrestha comes first in dictionary order Ram Shrestha
-1
invalid email address

//additional program to illustrate the concept of String


public class StringProgram {
public static void main(String[] args) {
String str1="This Is Java Programming";
int lengthOfString=str1.length();//Returns the length of this string.
System.out.println("Length of String= "+lengthOfString);
String str2="This Is C Programming";
String trimStr1=str1.trim();//Returns a copy of the string, with leading and trailing
//whitespace omitted.
System.out.println(trimStr1);
b=str1.equals(str3);
System.out.println("boolean value "+b);
b=str1.equalsIgnoreCase(str3);
System.out.println("boolean value "+b);
String str4="";
//b=str4.isEmpty();
// System.out.println("boolean value "+b);
if(str4.isEmpty())
System.out.println("string is empty");
}

}
run:
Length of String= 24
test value7
test value0
boolean value false
THIS IS JAVA PROGRAMMING
this is java programming
This Is Java Programming
boolean value false

P Page 54
boolean value true
string is empty
Arrays
An array is a group of like-typed variables that are referred to by a common name. Arrays of
any type can be created and may have one or more dimensions. Aspecific element in an array
is accessed by its index. Arrays offer a convenient means of grouping related information.
NOTE:
If you are familiar with C/C++, be careful. Arrays in Java work differently than they do in
those languages.

One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you first
must create an array variable of the desired type. The general form of a one-dimensional
array declaration is:

data-type variable-name[ ];

Here, type determines the data type of each element that array comprises of. Thus, the type for the array
determines what type of data the array will hold. For example, the following declares an array named
month_days with the type “array of int”:

int monthDays[];

Note to c/c++ programmer:


Although this declaration establishes the fact that monthDays is an array variable, no array
actually exists. In fact, the value of monthDays is set to null, which represents an array with no value. To
link monthDays with an actual, physical array of integers, you must allocate one using new and assign it
to monthDays. new is a special operator that allocates memory.

we will look more closely at new in a later chapter, but we need to use it now to allocate memory for
arrays. The general form of new as it applies to one-dimensional arrays appears as follows:
array-var = new type[size];

Here, type specifies the type of data being allocated, size specifies the number of elements inthe array,
and array-var is the array variable that is linked to the array. That is, to use new toallocate an array, you
must specify the type and number of elements to allocate. The elementsin the array allocated by new will
automatically be initialized to zero. This example allocatesa 12-element array of integers and links them
to monthDays.

monthDays = new int[12];

After this statement executes, monthDays will refer to an array of 12 integers. Further, allelements in the
array will be initialized to zero.

Hence, Obtaining an array is a two-step process.


1. First, you must declare a variable of the desired array type.
2. Second, you must allocate the memory that will hold the array, using new, and assign it to the array
variable. Thus, in Java all arrays are dynamically allocated.

Following example will make you clear about above discussed points:

P Page 55
publicclass Array {
publicstaticvoid main(String args[]){
intmonthDays[];
monthDays=newint[12];
monthDays[0]=31;
monthDays[1]=28;
monthDays[2]=31;
monthDays[3]=30;
monthDays[4]=31;
monthDays[5]=30;
monthDays[6]=31;
monthDays[7]=31;
monthDays[8]=30;
monthDays[9]=31;
monthDays[10]=30;
monthDays[11]=31;
System.out.println("January has " +monthDays[0] + " days");
System.out.println("February has " +monthDays[1] + " days");
System.out.println("March has " +monthDays[2] + " days");
System.out.println("April has " +monthDays[3] + " days");
System.out.println("May has " +monthDays[4] + " days");
System.out.println("June has " +monthDays[5] + " days");
System.out.println("July has " +monthDays[6] + " days");
System.out.println("August has " +monthDays[7] + " days");
System.out.println("September has " +monthDays[8] + " days");
System.out.println("October has " +monthDays[9] + " days");
System.out.println("November has " +monthDays[10] + " days");
System.out.println("December has " +monthDays[11] + " days");

}
}

run:
January has 31 days
February has 28 days
March has 31 days
April has 30 days
May has 31 days
June has 30 days
July has 31 days
August has 31 days
September has 30 days
October has 31 days
November has 30 days
December has 31 days

P Page 56
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, lookand act
like regular multidimensional arrays. However, as you will see, there are a coupleof subtle differences. To
declare a multidimensional array variable, specify each additionalindex using another set of square
brackets. For example, the following declares a twodimensionalarray variable called twoD.

int twoD[][] = new int[4][5];

This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented asan array of
arrays of int.

publicclassTwoDArray {
publicstaticvoid main(String args[]){
int twoD[][];
twoD=newint[4][5];
int i,j,k=0;
for(i=0;i<4;i++)
for(j=0;j<5;j++){
twoD[i][j]=k;
k++;
}
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
System.out.print(twoD[i][j]+" ");
System.out.println();
}
}
}
Output:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19

Note: Alternative Array Declaration Syntax


There is a second form that may be used to declare an array:

type[ ] var-name;

Here, the square brackets follow the type specifier, and not the name of the array variable.For example,
the following two declarations are equivalent:

int al[] = new int[3];


int[] a2 = new int[3];

The following declarations are also equivalent:

char twod1[][] = new char[3][4];


char[][] twod2 = new char[3][4];

P Page 57
This alternative declaration form offers convenience when declaring several arrays at thesame time. For
example,
int[] nums, nums2, nums3; // create three arrays

creates three array variables of type int. It is the same as writing

int nums[], nums2[], nums3[]; // create three arrays

Built in Subroutines and functions

Subroutine is a set of program instructions that have been chunked together and given a name.
there are a lot of subroutines that have already been written for us.

In java, every subroutine is contained in a class or in an object. There are many classes that are
defined as the standard part of the java language.

Classes in java have two different functions:

1) first of all, a class can group together variables and subroutines. These variables and
subroutines can be marked with keyword “static”.

2) second they are used to describe object. In this role, the class of an object specifies what
subroutines and variables are contained in that object. In this role the class is a type and the
object is the variable.
Note: hence, every subroutine is contained either in a class or in an object.

Subroutine call statement for a static subroutine takes the form


Subroutine-name(arguments);
If the subroutine that is being called is in the same class,
Or
Class-name.subroutine-name(arguments);
If the subroutine is defined elsewhere in a different class.

API’s, Packages and Javadoc

As computers and their user interface have become easier to use, they have also become more complex
for programmers to deal with.
You can write programs for simple console-style user interface using just a few subroutines that write
output to the console and read the user’s typed data.
A modern graphical user interface with windows, buttons, scroll bars, menus, text-input boxes and so on
might makes the thing easier for the user but it forces the programmer to cope with a huge array of

P Page 58
possibilities. The programmer deals with these complexity in the form of great numbers of subroutines
that are provided for managing the user interface as well as other purposes.
Toolboxes:
Suppose you want to program for macintosh computer, then you must deal with macintosh
toolbox, a collection of well over thousand different subroutines. There are routines for opening and
closing windows, for drawing geometric figures and text to windows, for adding button to windows, and
for responding to mouse clicks on the window. There are still other routines for creating menus and for
reacting to user selections from menus. Apart from the user interface, there are routines for opening files
and reading data from them, for communicating over a network, for sending output to a printer and in
general for doing all the standard things that a computer has to do.
Windows provides its own set of subroutines for programmers to use and they are quite different
from the subroutines used on the Mac. Linux has several different GUI toolboxes for the programmer to
choose from.

The Java class library contains thousands of predefined classes and interfaces that programmerscan use to
write their own applications. These classes are grouped into packages basedon their functionality.
For example, the classes and interfaces used for file processing are
grouped into the
java.iopackage,
and the classes and interfaces for networking applicationsare grouped into the
java.netpackage.
The Java API documentation lists the publicand protected members of each class and the public
members of each interface inthe Java class library. The documentation overviews all the classes and
interfaces, summarizestheir members (i.e., the fields, constructors and methods of classes, and the fields
andmethods of interfaces) and provides detailed descriptions of each member. Most Java programmers
rely on this documentation when writing programs. Normally, programmerswould search the API to find
the following:

1. The package that contains a particular class or interface.


2. Relationships between a particular class or interface and other classes and interfaces.
3. Class or interface constants—normally declared as public static final fields.
4. Constructors to determine how an object of the class can be initialized.
5. The methods of a class to determine whether they are static or non-static, thenumber and types of the
arguments you need to pass, the return types and anyexceptions that might be thrown from the method.
In addition, programmers often rely on the documentation to discover classes andinterfaces that they have
not used before.

For this reason, we demonstrate the documentationwith classes you know and classes you may not have
studied yet. We show how to usethe documentation to locate the information you need to use a class or
interface effectively.The Java API documentation can be downloaded to your local hard disk or viewed
online.
To download the Java API documentation, go to http://docs.oracle.com/javase/6/docs/api/ and select
download link.

We have also used several built in subroutines in our programs. Like from math class we have used sqrt(),
from class String we have used toUpperCase(), toLowerCase(), equalsTo(), length() etc.

P Page 59
Using classes from packages
Let us say that you want to use the class java.awt.color in your program. Here java.awt is the package
name and color is the class name. now suppose you want to declare variable rectArea of type color, then
you can write
java.awt.Color rectArea;
this is just an ordinary variable declaration of the form type-name variable-name;
ofcourse, using the full name of every class can get tiresome, so java makes it possible to avoid using the
fullname of a class by importing the class. If you put:
import java.awt.Color;
in your program at the beginning of java source code, then in rest of the file you can abbreviate the full
name java.awt.Color to just the simple name of the class, Color.the statement above is called the import
directive and will allow you to write
Color rectArea; in your program.

Note: there is a shortcut for importing all the classes from a given package. You can import all the classes
from java.awt by writing import directive as:
import java.awt.*;

P Page 60
Object oriented
programming in Java
Classes and object

T he class is at the core of Java. It is the logical construct upon which the entire Javalanguage is built because it
defines the shape and nature of an object.Theclass forms the basis for object-oriented programming in Java. Any concept
you wishto implement in a Java program must be encapsulated within a class.Here we will discuss the basic elements of a
class and learn how a class can beused to create objects. You will also learn about methods, constructors, and the this
keyword.

Class Fundamentals
Classes have been used since the beginning of this book. However, until now, only the most
basic form of a class has been used. The classes created in the preceding chaptersprimarily exist simply to
encapsulate the main( ) method, which has been used to demonstratethe basics of the Java syntax. As you will see,
classes are substantially more powerful than thelimited ones presented so far.Perhaps the most important thing to
understand about a class is that it defines a new datatype. Once defined, this new type can be used to create objects of
that type. Thus, a class isa template for an object, and an object is an instance of a class.
The General Form of a Class
When you define a class, you declare its exact form and nature. You do this by specifying thedata that it contains and the
code that operates on that data. While very simple classes maycontain only code or only data, most real-world classes
contain both. As you will see, a classcode defines the interface to its data.

Aclass is declared by use of the class keyword. The classes that have been used up to thispoint are actually very limited
examples of its complete form. Classes can (and usually do)get much more complex. 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
}
// ...
type methodNameN(parameter-list) {
// body of method
}
}

P Page 61
The data, or variables, defined within a classare called instance variables. The code iscontained within methods.
Collectively, the methods and variables defined within a class arecalled membersof the class. In most classes, the instance
variables are acted upon and accessedby the methods defined for that class. Thus, as a general rule, it is the methods that
determinehow a class’ data can be used.

Variables defined within a class are called instance variables because each instance of theclass (that is, each object of the
class) contains its own copy of these variables. Thus, the datafor one object is separate and unique from the data for
another.We will come back to this pointshortly, but it is an important concept to learn early.

A Simple Class
Let’s begin our study of the class with a simple example. Here is a class called Box that defines
three instance variables: width, height, and depth. Currently, Box does not contain anymethods:

class Box {
double width;
double height;
double depth;
}

As stated, a class defines a new type of data. In this case, the new data type is called Box.You will use this name to declare
objects of type Box. It is important to remember that a classdeclaration only creates a template; it does not create an
actual object. Thus, the precedingcode does not cause any objects of type Box to come into existence.To actually create a
Box object, you will use a statement like the following:

Box mybox = new Box(); // create a Box object called mybox

After this statement executes, mybox will be an instance of Box. Thus, it will have “physical” reality. For the moment,
don’t worry about the details of this statement.As mentioned earlier, each time you create an instance of a class, you are
creating an objectthat contains its own copy of each instance variable defined by the class. Thus, every Boxobject
will contain its own copies of the instance variables width, height, and depth.

Accessing instance variable


Toaccess these variables, you will use the dot (.) operator. The dot operator links the name of theobject with the
name of an instance variable. For example, to assign the width variable ofmybox the value 100, you would use the
following statement:

mybox.width = 100;

This statement tells the compiler to assign the copy of width that is contained within themybox object the value
of 100. In general, you use the dot operator to access both the instancevariables and the methods within an object.

Here is a complete program that uses the Box 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[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;

P Page 62
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}

You should call the file that contains this program BoxDemo.java, because the main( ) methodis in the class called
BoxDemo, not the class called Box. When you compile this program, youwill find that two .class files have been created,
one for Box and one for BoxDemo. The Java compiler automatically puts each class into its own .class file.
Note: It is not necessary for both theBox and the BoxDemo class to actually be in the same source file. You could put
each classin its own file, called Box.java and BoxDemo.java, respectively.To run this program, you must execute
BoxDemo.class.

When you do, you will see thefollowing output:

Volume is 3000.0

As stated earlier, each object has its own copies of the instance variables. This means thatif you have two Box objects,
each has its own copy of depth, width, and height. It is importantto understand that changes to the instance variables of
one object have no effect on the instancevariables 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 {
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);
}
}

Run:

Volume is 3000.0
Volume is 162.0

As you can see, mybox1’s data is completely separate from the data contained in mybox2.

Declaring Objects

P Page 63
As just explained, when you create a class, you are creating a new data type. You can use thistype to declare objects of
that type. However, obtaining objects of a class is a two-step process:
First, you must declare a variable of the class type. This variable does not define an object.Instead, it is
simply a variable that can refer to an object.
Second, you must acquire an actual,physical copy of the object and assign it to that variable. You can do
this using the new operator.

Note: The new operator dynamically allocates (that is, allocates at run time) memory for an object
and returns a reference to it.

This reference is, more or less, the address in memory of the objectallocated by new. This reference is then stored in the
variable. Thus, in Java, all class objectsmust be dynamically allocated. Let’s look at the details of this procedure.In the
preceding sample programs, a line similar to the following is used to declare an
object of type Box:

Box mybox = new Box();

This statement combines the two steps just described. It can be rewritten like this to show
each step more clearly:

Box mybox; // declare reference to object


mybox = new Box(); // allocate a Box object
The first line declares mybox as a reference to an object of type Box. After this line executes,mybox contains the value
null, which indicates that it does not yet point to an actual object.Any attempt to use mybox at this point will result in a
compile-time error. The next lineallocates an actual object and assigns a reference to it to mybox. After the second line
executes,you can use mybox as if it were a Box object. But in reality, mybox simply holds the memoryaddress of the
actual Box object. The effect of these two lines of code is depicted in Figure 6-1.
A Closer Look at new
As just explained, the new operator dynamically allocates memory for an object. It has this
general form:
class-var = new classname( );

Declaring an object of type Box

Here, class-var is a variable of the class type being created. The classname is the name of theclass that is being
instantiated. The class name followed by parentheses specifies the constructorfor the class. Aconstructor defines what
occurs when an object of a class is created. Constructorsare an important part of all classes and have many significant
attributes. Most real-worldclasses explicitly define their own constructors within their class definition. However, if
noexplicit constructor is specified, then Java will automatically supply a default constructor.

This is the case with Box. For now, we will use the default constructor. Soon, you will seehow to define your own
constructors.At this point, you might be wondering why you do not need to use new for such things
as integers or characters. The answer is that Java’s primitive types are not implemented asobjects. Rather, they are
implemented as “normal” variables. Java can implement the primitive types more efficiently.Later, you will see object

P Page 64
versions of the primitive types that are available for your use inthose situations in which complete objects of these types
are needed.

Let’s once again review the distinction between a class and an object. A class creates anew data type that can be used to
create objects. That is, a class creates a logical frameworkthat defines the relationship between its members. When you
declare an object of a class, youare creating an instance of that class. Thus, a class is a logical construct. An object has
physicalreality. (That is, an object occupies space in memory.) It is important to keep this distinctionclearly in mind.

Assigning Object Reference Variables


Object reference variables act differently than you might expect when an assignment takes
place. For example, what do you think the following fragment does?

Box b1 = new Box();


Box b2 = b1;

You might think that b2 is being assigned a reference to a copy of the object referred to byb1. That is, you might think that
b1 and b2 refer to separate and distinct objects. However,this would be wrong. Instead, after this fragment executes, b1
and b2 will both refer to thesame object. The assignment of b1 to b2 did not allocate any memory or copy any part of
theoriginal object. It simply makes b2 refer to the same object as does b1. Thus, any changesmade to the object through
b2 will affect the object to which b1 is referring, since they are thesame object.
This situation is depicted here:

Although b1 and b2 both refer to the same object, they are not linked in any other way.For example, a subsequent
assignment to b1 will simply unhook b1 from the original object
without affecting the object or affecting b2. For example:
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.

Introducing Methods
As mentioned at the beginning of this chapter, classes usually consist of two things: instancevariables and methods. The
topic of methods is a large one because Java gives them so much
power and flexibility. However, thereare some fundamentals that you need to learn now so that you can begin to add
methods toyour classes.

This is the general form of a method:

Return_type functionName(parameter-list) {
// body of method
}

Here,
Return_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 typemust be void.
The name of the method is specified by functionName. This can be any legal identifierother than those
already used by other items within the current scope.
The parameter-list is asequence of type and identifier pairs separated by commas. Parameters are
essentially variablesthat receive the value of the arguments passed to the method when it is called. If the
methodhas no parameters, then the parameter list will be empty.

P Page 65
Note:
Methods that have a return type other than void return a value to the calling routine using
the following form of the return statement:

return value;

Here, value is the value returned.

Later, you will see how to create various types of methods, includingthose that take parameters and those that return
values.

Adding a Method to the Box Class

Although it is perfectly fine to create a class that contains only data, it rarely happens. Mostof the time, you will use
methods to access the instance variables defined by the class. In fact,methods define the interface to most classes. This
allows the class implementor to hide thespecific layout of internal data structures behind cleaner method abstractions. In
additionto defining methods that provide access to data, you can also define methods that are usedinternally by the class
itself.

Let’s begin by adding a method to the Box class. It may have occurred to you while lookingat the preceding programs that
the computation of a box’s volume was something that wasbest handled by the Box class rather than the BoxDemo class.
After all, since the volume ofa box is dependent upon the size of the box, it makes sense to have the Box class compute
it.To do this, you must add a method to Box, as shown here:

// This program includes a method inside the box class.


class Box {
double width;
double height;
double depth;
// 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
mybox2.volume();
}
}
This program generates the following output, which is the same as the previous version.
Volume is 3000.0
Volume is 162.0
Look closely at the following two lines of code:
mybox1.volume();
mybox2.volume();

P Page 66
The first line here invokes the volume( ) method on mybox1. That is, it calls volume( )relative to the mybox1 object,
using the object’s name followed by the dot operator. Thus,the call to mybox1.volume( ) displays the volume of the box
defined by mybox1, and thecall to mybox2.volume( ) displays the volume of the box defined by mybox2. Each
timevolume( ) is invoked, it displays the volume for the specified box.There is something very important to notice inside
the volume( ) method: the instancevariables width, height, and depth are referred to directly, without preceding
them with an
object name or the dot operator. When a method uses an instance variable that is defined by
its class, it does so directly, without explicit reference to an object and without use of the dot
operator.

Note:When an instance variable is accessed by code that is not part of the class
in which that instance variable is defined, it must be done through an object, by use of the
dot operator. However, when an instance variable is accessed by code that is part of the same
class as the instance variable, that variable can be referred to directly. The same thing applies
to methods.

Returning a Value
While the implementation of volume( ) does move the computation of a box’s volume insidethe Box class where it
belongs, it is not the best way to do it. For example, what if anotherpart of your program wanted to know the volume of a
box, but not display its value? Abetterway to implement volume( ) is to have it compute the volume of the box and return
the resultto the caller. The following example, an improved version of the preceding program, does
just that:
// Now, volume() returns the volume of a box.
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo4 {
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;
// 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, when volume( ) is called, it is put on the right side of an assignmentstatement. On the left is a variable, in
this case vol, that will receive the value returned byvolume( ). Thus, after

vol = mybox1.volume();

executes, the value of mybox1.volume( ) is 3,000 and this value then is stored in vol.There are two important things to
understand about returning values:

P Page 67
• The type of data returned by a method must be compatible with the return typespecified by the method. For example, if
the return type of some method is boolean,you could not return an integer.

• The variable receiving the value returned by a method (such as vol, in this case) mustalso be compatible with the return
type specified for the method.

One more point: The preceding program can be written a bit more efficiently becausethere is actually no need for the vol
variable. The call to volume( ) could have been used inthe println( ) statement directly, as shown here:

System.out.println("Volume is " + mybox1.volume());

In this case, when println( ) is executed, mybox1.volume( ) will be called automatically and
its value will be passed to println( ).

Adding a Method That Takes Parameters


While some methods don’t need parameters, most do. Parameters allow a method to begeneralized. That is, a
parameterized method can operate on a variety of data and/or be usedin a number of slightly different situations. To
illustrate this point, let’s use a very simpleexample. Here is a method that returns the square of the number 10:
int square()
{
return 10 * 10;
}
While this method does, indeed, return the value of 10 squared, its use is very limited.
However, if you modify the method so that it takes a parameter, as shown next, then you
can make square( ) much more useful.
int square(int i)
{
return i * i;
}
Now, square( ) will return the square of whatever value it is called with. That is, square( ) isnow a general-purpose
method that can compute the square of any integer value, rather thanjust 10.
Here is an example:
int x, y;
x = square(5); // x equals 25
x = square(9); // x equals 81
y = 2;
x = square(y); // x equals 4
In the first call to square( ), the value 5 will be passed into parameter i. In the second call, i
will receive the value 9. The third invocation passes the value of y, which is 2 in this example.
As these examples show, square( ) is able to return the square of whatever data it is passed.
It is important to keep the two terms parameter and argument straight. A parameter is a
variable defined by a method that receives a value when the method is called. For example,
in square( ), i is a parameter. An argument is a value that is passed to a method when it is
invoked. For example, square(100) passes 100 as an argument. Inside square( ), the parameter i
receives that value.

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 can’t 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.

P Page 68
class Box {
double width;
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);
// 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.

Constructors
It can be tedious to initialize all of the variables in a class each time an instance is created. Evenwhen you add convenience
functions like setDim( ), it would be simpler and more conciseto have all of the setup done at the time the object is first
created. Because the requirementfor initialization is so common, Java allows objects to initialize themselves when they
arecreated. This automatic initialization is performed through the use of a constructor.Aconstructor 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 constructoris 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. This isbecause the implicit return type of a class’ constructor is the class type itself. It
is the constructor’sjob to initialize the internal state of an object so that the code creating an instance will havea fully
initialized, usable object immediately.

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.
Let’s 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;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");

P Page 69
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
Volume is 1000.0

As you can see, both mybox1 and mybox2 were initialized by the Box( ) constructor when
they were created. Since the constructor gives all boxes the same dimensions, 10 by 10 by 10,
both mybox1 and mybox2 will have the same volume. The println( ) statement inside Box( )
is for the sake of illustration only. Most constructors will not display anything. They will
simply initialize an object.
Before moving on, let’s reexamine the new operator. As you know, when you allocate an
object, you use the following general form:
class-var = new classname( );
Now you can understand why the parentheses are needed after the class name. What is actually
happening is that the constructor for the class is being called. Thus, in the line
Box mybox1 = new Box();
new Box( ) is calling the Box( ) constructor. When you do not explicitly define a constructor
for a class, then Java creates a default constructor for the class. This is why the preceding line
of code worked in earlier versions of Box that did not define a constructor. The default
constructor automatically initializes all instance variables to zero. The default constructor is
often sufficient for simple classes, but it usually won’t do for more sophisticated ones. Once
you define your own constructor, the default constructor is no longer used.

Parameterized Constructors
While the Box( ) constructor in the preceding example does initialize a Box object, it is notvery useful—all
boxes have the same dimensions. What is needed is a way to construct Boxobjects of various dimensions. The easy
solution is to add parameters to the constructor. Asyou can probably guess, this makes them much more useful. For

P Page 70
example, the following versionof Box defines a parameterized constructor that sets the dimensions of a box as specified
bythose parameters. Pay special attention to how Box objects are created.

/* Here, Box uses a parameterized constructor to


initialize the dimensions of a box.
*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}

class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
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);
}
}

run:
Volume is 3000.0
Volume is 162.0

As you can see, each object is initialized as specified in the parameters to its constructor.For example, in the following
line,

Box mybox1 = new Box(10, 20, 15);

the values 10, 20, and 15 are passed to the Box( ) constructor when new creates the object.
Thus, mybox1’s copy of width, height, and depth will contain the values 10, 20, and 15,
respectively.

The this Keyword


Sometimes a method will need to refer to the object that invoked it. To allow this, Java definesthe this keyword. this can
be used inside any method to refer to the current object. That is,this is always a reference to the object on which the
method was invoked. You can use thisanywhere a reference to an object of the current class’ type is permitted.To better
understand what this refers to, consider the following version of Box( ):

P Page 71
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}

This version of Box( ) operates exactly like the earlier version. The use of this is redundant,but perfectly correct. Inside
Box( ), this will always refer to the invoking object. While it isredundant in this case, this is useful in other contexts, one
of which is explained in the nextsection.

Instance Variable Hiding


As you know, it is illegal in Java to declare two local variables with the same name insidethe same or enclosing
scopes. Interestingly, you can have local variables, including formalparameters to methods, which overlap with the names
of the class’ instance variables. However,when a local variable has the same name as an instance variable, the local
variable hides theinstance variable. This is why width, height, and depth were not used as the names of theparameters to
the Box( ) constructor inside the Box class. If they had been, then width wouldhave referred to the formal parameter,
hiding the instance variable width. While it is usually
easier to simply use different names, there is another way around this situation. Because thislets you refer directly to the
object, you can use it to resolve any name space collisions thatmight occur between instance variables and local variables.
For example, here is anotherversion of Box( ), which uses width, height, and depth for parameter names and then
usesthis to access the instance variables by the same name:

// Use this to resolve name-space collisions.


Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}

Aword of caution: The use of this in such a context can sometimes be confusing, andsome programmers are careful not
to use local variables and formal parameter names thathide instance variables. Of course, other programmers believe
the contrary—that it is a goodconvention to use the same names for clarity, and use this to overcome the instance
variablehiding. It is a matter of taste which approach you adopt.

Garbage Collection
Since objects are dynamically allocated by using the new operator, you might be wonderinghow such objects are
destroyed and their memory released for later reallocation. In somelanguages, such as C++, dynamically allocated objects
must be manually released by use ofa delete operator. Java takes a different approach; it handles deallocation for you
automatically.The technique that accomplishes this is called garbage collection. It works like this: when noreferences to
an object exist, that object is assumed to be no longer needed, and the memoryoccupied by the object can be reclaimed.
There is no explicit need to destroy objects as in C++.Garbage collection only occurs sporadically (if at all) during the
execution of your program.It will not occur simply because one or more objects exist that are no longer used.
Furthermore,different Java run-time implementations will take varying approaches to garbage collection,but for the most
part, you should not have to think about it while writing your programs.

The finalize( ) Method


Sometimes an object will need to perform some action when it is destroyed. For example, ifan object is holding some non-
Java resource such as a file handle or character font, then youmight want to make sure these resources are freed before an
object is destroyed. To handlesuch situations, Java provides a mechanism called finalization.

By using finalization, you candefine specific actions that will occur when an object is just about to be reclaimed by
thegarbage collector.To add a finalizer to a class, you simply define the finalize( ) method. The Java run timecalls that
method whenever it is about to recycle an object of that class. Inside the finalize( )method, you will specify those actions

P Page 72
that must be performed before an object is destroyed.The garbage collector runs periodically, checking for objects that are
no longer referenced byany running state or indirectly through other referenced objects. Right before an asset is freed,the
Java run time calls the finalize( ) method on the object.
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 definedoutside its class.
It is important to understand that finalize( ) is only called just prior to garbage collection.It is not called when an object
goes out-of-scope, for example. This means that you cannotknow when—or even if—finalize( ) will be executed.
Therefore, your program should provideother means of releasing system resources, etc., used by the object. It must not
rely on finalize( )for normal program operation.

A Closer Look at
Methods and Classes
P Page 73
Overloading Methods
In Java it is possible to define two or more methods within the same class that share thesame name, as long as their
parameter declarations are different. When this is the case, themethods are said to be overloaded, and the process is
referred to as method overloading. Methodoverloading is one of the ways that Java supports polymorphism. Method
overloading is one of Java’s most exciting and useful features.When an overloaded method is invoked, Java uses the type
and/or number ofarguments as its guide to determine which version of the overloaded method to actuallycall. Thus,
overloaded methods must differ in the type and/or number of their parameters.While overloaded methods may have
different return types, the return type alone is
insufficient to distinguish two versions of a method. When Java encounters a call to anoverloaded method, it simply
executes the version of the method whose parameters matchthe arguments used in the call.
Here is a simple example that illustrates method overloading:
// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
run:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625

As you can see, test( ) is overloaded four times. The first version takes no parameters,the second takes one integer
parameter, the third takes two integer parameters, and thefourth takes one double parameter. The fact that the fourth
version of test( ) also returns avalue is of no consequence relative to overloading, since return types do not play a role
inoverload resolution.When an overloaded method is called, Java looks for a match between the argumentsused to call the
method and the method’s parameters. However, this match need not alwaysbe exact.

P Page 74
Overloading Constructors
In addition to overloading normal methods, you can also overload constructor methods. In
fact, for most real-world classes that you create, overloaded constructors will be the norm,
not the exception. To understand why, let’s return to the Box class developed in the preceding
chapter. Following is the latest version of Box:
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}

As you can see, the Box( ) constructor requires three parameters. This means that all
declarations of Box objects must pass three arguments to the Box( ) constructor. For example,
the following statement is currently invalid:

Box ob = new Box();

Since Box( ) requires three arguments, it’s an error to call it without them. This raises some important questions. What if
you simply wanted a box and did not care (or know)what its initial dimensions were? Or, what if you want to be able to
initialize a cube byspecifying only one value that would be used for all three dimensions? As the Box classis currently
written, these other options are not available to you.
Fortunately, the solution to these problems is quite easy: simply overload the Boxconstructor so that it handles the
situations just described. Here is a program that containsan improved version of Box that does just that:

/* Here, Box defines three constructors to initialize


the dimensions of a box various ways.
*/
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}

P Page 75
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
run:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0

As you can see, the proper overloaded constructor is called based upon the parameters
specified when new is executed.

Using Objects as Parameters


So far, we have only been using simple types as parameters to methods. However, it is bothcorrect and common
to pass objects to methods. For example, consider the following shortprogram:

// Objects may be passed to methods.

P Page 76
class Test {
int a, b;

Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b)
return true;
else
return false;
}
}

class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
This program generates the following output:
ob1 == ob2: true
ob1 == ob3: false
As you can see, the equals( ) method inside Test compares two objects for equality andreturns the result. That is, it
compares the invoking object with the one that it is passed. Ifthey contain the same values, then the method returns true.
Otherwise, it returns false. Noticethat the parameter o in equals( ) specifies Test as its type. Although Test is a class type
createdby the program, it is used in just the same way as Java’s built-in types.One of the most common uses of object
parameters involves constructors. Frequently, youwill want to construct a new object so that it is initially the same as some
existing object. To dothis, you must define a constructor that takes an object of its class as a parameter.

A Closer Look at Argument Passing


In general, there are two ways that a computer language can pass an argument to a subroutine:

The first way is call-by-value:This approach copies the value of an argument into the formalparameter of the subroutine.
Therefore, changes made to the parameter of the subroutinehave no effect on the argument.

The second way an argument can be passed is call-by-reference: In this approach, a reference to an argument (not the
value of the argument) is passed to theparameter. Inside the subroutine, this reference is used to access the actual argument
specifiedin the call. This means that changes made to the parameter will affect the argument used tocall the subroutine. As
you will see, Java uses both approaches, depending upon what is passed.

In Java, when you pass a primitive type to a method, it is passed by value. Thus, whatoccurs to the parameter that receives
the argument has no effect outside the method. Forexample, consider the following program:

// Primitive types are passed by value.


class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}

P Page 77
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: "+a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +a + " " + b);
}
}

run:
a and b before call: 15 20
a and b after call: 15 20

As you can see, the operations that occur inside meth( ) have no effect on the values of a and b
used in the call; their values here did not change to 30 and 10.

When you pass an object to a method, the situation changes dramatically, because objectsare passed by what is effectively
call-by-reference. Keep in mind that when you create avariable of a class type, you are only creating a reference to an
object. Thus, when you passthis reference to a method, the parameter that receives it will refer to the same object as
thatreferred to by the argument. This effectively means that objects are passed to methods by useof call-by-reference.
Changes to the object inside the method do affect the object used as anargument.

For example,
the following version of Box allows one object to initialize another:

// Here, Box allows one object to initialize another.


class Box {
double width;
double height;
double depth;
// Notice this constructor. It takes an object of type Box.
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified

Box(double w, double h, double d) {


width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}

class OverloadCons2 {
public static void main(String args[]) {
// create boxes using the various constructors

P Page 78
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1); // create copy of mybox1
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
// get volume of clone
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}
}
As you will see when you begin to create your own classes, providing many forms
of constructors is usually required to allow objects to be constructed in a convenient and
efficient manner.

For example, consider the following program:

// Objects are passed by reference.


class Test {
int a, b;

Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +ob.a + " " + ob.b);
}
}
This program generates the following output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
As you can see, in this case, the actions inside meth( ) have affected the object used as an
argument.
As a point of interest, when an object reference is passed to a method, the reference itself
is passed by use of call-by-value. However, since the value being passed refers to an object,
the copy of that value will still refer to the same object that its corresponding argument does.
REMEMBER When a primitive type is passed to a method, it is done by use of call-by-value. Objects
are implicitly passed by use of call-by-reference.
Returning Objects
Amethod can return any type of data, including class types that you create. For example, inthe following
program, the incrByTen( ) method returns an object in which the value of a isten greater than it is in the invoking object.

// Returning an object.
class Test {

P Page 79
int a;

Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
}

class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "+ ob2.a);
}
}
run:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22

As you can see, each time incrByTen( ) is invoked, a new object is created, and a reference
to it is returned to the calling routine.
The preceding program makes another important point: Since all objects are dynamically
allocated using new, you don’t need to worry about an object going out-of-scope because the
method in which it was created terminates. The object will continue to exist as long as there is
a reference to it somewhere in your program. When there are no references to it, the object will
be reclaimed the next time garbage collection takes place.

Access specifier
Java’s access specifiers are

1. public,
2. private, and

P Page 80
3. protected.

Note: Java also defines a defaultaccess level.

protected applies only when inheritance is involved. The other access specifiersare described next.
Let’s begin by defining public and private. When a member of a class is modified bythe public specifier, then that
member can be accessed by any other code. When a memberof a class is specified as private, then that member can only
be accessed by other members ofits class. Now you can understand why main( ) has always been preceded by the
publicspecifier. It is called by code that is outside the program—that is, by the Java run-timesystem. When no access
specifier is used, then by default the member of a class is public
within its own package, but cannot be accessed outside of its package.

In the classes developed so far, all members of a class have used the default access mode,which is essentially public.
However, this is not what you will typically want to be the case.Usually, you will want to restrict access to the data
members of a class—allowing accessonly through methods. Also, there will be times when you will want to define
methodsthat are private to a class.An access specifier precedes the rest of a member’s type specification. That is, it
mustbegin a member’s declaration statement. Here is an example:

public int i;
private double j;
private int myMethod(int a, char b) { // ...

To understand the effects of public and private access, consider the following program:

/* This program demonstrates the difference between


public and private.
*/
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}

class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " +ob.b + " " + ob.getc());
}
}

As you can see, inside the Test class, a uses default access, which for this example is thesame as specifying public. b is
explicitly specified as public. Member c is given privateaccess. This means that it cannot be accessed by code outside of
its class. So, inside theAccessTest class, c cannot be used directly. It must be accessed through its public methods:setc( )
and getc( ). If you were to remove the comment symbol from the beginning of the
following line,

P Page 81
// ob.c = 100; // Error!

Understanding static
There will be times when you will want to define a class member that will be usedindependently of any object of that
class. Normally, a class member must be accessed onlyin conjunction with an object of its class. However, it is possible to
create a member that canbe used by itself, without reference to a specific instance. To create such a member, precedeits
declaration with the keyword static. When a member is declared static, it can be accessedbefore any objects of its class
are created, and without reference to any object.

You can declareboth methods and variables to be 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 ofits 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 toinheritance and is described in the
next chapter.)

If you need to do computation in order to initialize your static variables, you can declare astatic block that gets executed
exactly once, when the class is first loaded. The followingexample shows a class that has a static method, some static
variables, and a static initializationblock:

// 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[]) {
meth(42);
}
}

As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set to 3,then the static block
executes, which prints a message and then initializes b to a * 4 or 12. Thenmain( ) is called, which calls meth( ), passing
42 to x. The three println( ) statements refer to thetwo static variables a and b, as well as to the local variable x.

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 usedindependently of any object. To do
so, you need only specify the name of their class followedby the dot operator. For example, if you wish to call a static
method from outside its class, youcan do so using the following general form:

classname.method( )

P Page 82
Here, classname is the name of the class in which the static method is declared. As you cansee, this format is similar to
that used to call non-static methods through object-reference
variables. A static variable can be accessed in the same way—by use of the dot operator on
the name of the class. This is how Java implements a controlled version of global methods
and global variables.
Here is an example. Inside main( ), the static method callme( ) and the static variable b
are accessed through their class name StaticDemo.
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}

class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
run:
a = 42
b = 99

Introducing final
A variable can be declared as final. Doing so prevents its contents from being modified.This means that you
must initialize a final variable when it is declared. For example:

final int FILE_NEW = 1;


final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;

Subsequent parts of your program can now use FILE_OPEN, etc., as if they were constants,without fear that a value has
been changed.It is a common coding convention to choose all uppercase identifiers for final variables.Variables declared
as final do not occupy memory on a per-instance basis. Thus, a final
variable is essentially a constant.The keyword final can also be applied to methods, but its meaning is
substantiallydifferent than when it is applied to variables. This second usage of final is described in the
next chapter, when inheritance is described.

Introducing Nested and Inner Classes


It is possible to define a class within another class; such classes are known as nested classes.
The scope of a nested class is bounded by the scope of its enclosing class.
Thus, if class B isdefined within class A, then B does not exist independently of A.
A nested class has accessto the members, including private members, of the class in which it is nested. However,
theenclosing class does not have access to the members of the nested class.

A nested class thatis declared directly within its enclosing class scope is a member of its enclosing class. It
isalso possible to declare a nested class that is local to a block.There are two types of nested classes: static and
non-static. A static nested class is onethat has the static modifier applied. Because it is static, it must access the
members of itsenclosing class through an object. That is, it cannot refer to members of its enclosing classdirectly.
Because of this restriction, static nested classes are seldom used.

The most important type of nested class is the inner class. An inner class is a non-staticnested class. It has access to all of
the variables and methods of its outer class and may referto them directly in the same way that other non-static members
of the outer class do.

P Page 83
The following program illustrates how to define and use an inner class. The class namedOuter has one instance variable
named outer_x, one instance method named test( ), anddefines one inner class called Inner.

// Demonstrate an inner class.


class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}

class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
run:
display: outer_x = 100

In the program, an inner class named Inner is defined within the scope of class Outer.Therefore, any code in class Inner
can directly access the variable outer_x. An instancemethod named display( ) is defined inside Inner. This method
displays outer_x on thestandard output stream. The main( ) method of InnerClassDemo creates an instance ofclass
Outer and invokes its test( ) method. That method creates an instance of class Innerand the display( ) method is called.It
is important to realize that an instance of Inner can be created only within the scopeof class Outer. The Java compiler
generates an error message if any code outside of classOuter attempts to instantiate class Inner. (In general, an inner class
instance must becreated by an enclosing scope.) You can, however, create an instance of Inner outside ofOuter by
qualifying its name with Outer, as in Outer.Inner.
As explained, an inner class has access to all of the members of its enclosing class, butthe reverse is not true. Members of
the inner class are known only within the scope of theinner class and may not be used by the outer class. For example,

// This program will not compile.


class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
int y = 10; // y is local to Inner
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}

void showy() {
System.out.println(y); // error, y not known here!
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}

P Page 84
Here, y is declared as an instance variable of Inner. Thus, it is not known outside of thatclass and it cannot be used by
showy( ).Although we have been focusing on inner classes declared as members within an outer
class scope, it is possible to define inner classes within any block scope. For example, youcan define a nested class within
the block defined by a method or even within the body of afor loop, as this next program shows.

// Define an inner class within a for loop.


class Outer {
int outer_x = 100;
void test() {
for(int i=0; i<10; i++) {
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
Inner inner = new Inner();
inner.display();
}
}
}

class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
Run:
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100

display: outer_x = 100


display: outer_x = 100
While nested classes are not applicable to all stiuations, they are particularly helpful when
handling events. We will return to the topic of nested classes in Chapter 22. There you will
see how inner classes can be used to simplify the code needed to handle certain types of
events. You will also learn about anonymous inner classes, which are inner classes that don’t
have a name.
One final point: Nested classes were not allowed by the original 1.0 specification for Java.
They were added by Java 1.1.

Using Command-Line Arguments


Sometimes you will want to pass information into a program when you run it. This is
accomplished by passing command-line arguments to main( ). A command-line argument is
the information that directly follows the program’s name on the command line when it is
executed. To access the command-line arguments inside a Java program is quite easy—
they are stored as strings in a String array passed to the args parameter of main( ). The first
command-line argument is stored at args[0], the second at args[1], and so on. For example,
the following program displays all of the command-line arguments that it is called with:
// Display all command-line arguments.
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +

P Page 85
args[i]);
}
}
Try executing this program, as shown here:
java CommandLine this is a test 100 -1
When you do, you will see the following output:
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1
REMEMBER All command-line arguments are passed as strings. You must convert numeric values
to their internal forms manually, as explained in Chapter 16.

But, unlike many other languages that implement


strings as character arrays, Java implements strings as objects of type String.
Implementing strings as built-in objects allows Java to provide a full complement of
features that make string handling convenient. For example, Java has methods to compare
two strings, search for a substring, concatenate two strings, and change the case of letters
within a string. Also, String objects can be constructed a number of ways, making it easy to
obtain a string when needed.

Inheritance
Using inheritance, you can create a generalclass that defines traits common to a set of related items. This class can then be
inheritedby other, more specific classes, each adding those things that are unique to it.
In the terminologyof Java, a class that is inherited is called a superclass. The class that does the inheriting is calleda
subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of theinstance variables and methods
defined by the superclass and adds its own, unique elements.
Remember, once you have created a superclass that defines the general aspects of an object, that superclass can be
inherited to form specialized classes. Each subclass simply adds its own unique attributes. This is the essence of
inheritance.

Inheritance Basics
To inherit a class, you simply incorporate the definition of one class into another by usingthe extends keyword.

The general form of a class declaration that inherits a superclass is shown here:
class subclass-name extends superclass-name {
// body of class
}

Note:You can only specify one superclass for any subclass that you create. Java does not
support the inheritance of multiple superclasses into a single subclass. You can, as stated,
create a hierarchy of inheritance in which a subclass becomes a superclass of another subclass.

Member Access and Inheritance


Although a subclass includes all of the members of its superclass, it cannot access those
members of the superclass that have been declared as private.
Note:A class member that has been declared as private will remain private to its class. It is
not accessible by any code outside its class, including subclasses.

A Superclass Variable Can Reference a Subclass Object


Areference variable of a superclass can be assigned a reference to any subclass derived from
that superclass.

P Page 86
354507056735190;
9808182018
;

Interface
Java does not support multiple inheritance i.e. classes in java cannot have more than one
superclass. For e.g. Definition of class like following in invalid in java

class A extends B extends C

P Page 87
{
……………..
……………..
}
A large number of real-life application requires the use of multiple inheritance where a class
inherits properties and method from several distinct classes. For this purpose java provides an
alternate approach called interface to support the concept of multiple inheritance. A java class
cannot be a subclass of more than one superclass, but it can implement more than one interface
thus supporting multiple inheritance.

Defining Interface

An interface is basically a kind of class in the sense that interface contains methods and
variables. But there is a major difference between a class and interface. The difference is that
interfaces define only abstract methods and final fields. Hence interface has abstract method it
does not specify any code to implement these method. It is the responsibility of the class that
implements an interface to define the code for implementation of these methods.
The general form of interface definition is:

interface InterfaceName
{
Variable declaration;
Method declaration;
}
Here Interface is keyword and InterfaceName is any valid java name.
Variables are declared as:
static finalreturn-type variableName = value;
Method are declared as:
Return-type methodName (parameters);
Note: no any implementation code is provided in definition of interface, it is the responsibility of
the class that implements the interface to provide the implementation code.

For e.g.
interface Area
{
final static double pi = 3.14;
double computer (double x, double y);
void show();
}

Difference between class and interface

Class Interface
The members of class can have constant or The members of interface can have only
variables constants

P Page 88
Class can contain abstract as well as non- Interface can only have abstract method
abstract method
Class can contain the definition of method Interface cannot contain the definition of
method. It is the responsibility of class that
implements interface to provide the definition
Class can be used to declare objects Interface cannot be used to declare objects
Class can use various access specifiers like Interface can only use the public access
public, private or protected specifier.

Extending interface
Like classes interface can also be extended. The interface that extends another interface is called
subinterface. The new subinterface will inherit all the members of the superinterface. Interface is
inherited from another interface using keyword extends as shown below:

interface name2 extends name1


{
//body of name2
}

The situation where interface is used is illustrated by the following example.


We can put all the constant in one interface and the methods in the other. This will enable us to
use only the constants where the methods are not required and to use only methods where
constants are not required. For example:

interface ItemConstants
{
static final int code = 1001;
static final String name =” fan”;
}
interface ItemMethods
{
void display();
}

Now if we want to use only constants in an interface called name1 then we can do:
Interface name1 extends ItemConstants
{

}
Now if we want to use only methods in an interface called name2 then we can do:

Interface name2 extends ItemConstants


{

}
Also if we want to use constants as well as method in an interface called name3 then we can do:

P Page 89
Interface name3 extends ItemConstants, ItemMethods
{

}
Note: When interface extends another interface, subinterface connot define the methods declared
in superinterface.
It is the responsibility of any class that implements the derived interface to define all the
methods.

Implementing interfaces

Interfaces are normally used as “superclasses” whose properties are inherited by classes. Class
can implement interface using keyword implements as shown below:

class ClassName implements InterfaceName


{
//body of class
}

A class can extend another class and at the same time implement an interface. This is done as:

class ClassName extends SuperClass implements InterfaceName


{
//body of class
}
To implement multiple interface we implement class as:
class ClassName implements InterfaceName1, InterfaceName2, ………
{
//body of class
}

Example program:

interface Area
{
final static double pi = 3.14;
double compute (double x, double y);
}

class Rectangleimplements Area


{
public float compute (double x, double y)
{
return( x*y);

P Page 90
}

class Circle implements Area


{
public float compute (double x, double y)
{
return( pi*x*x);
}
}

class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Circle circ = new Circle();
Area area;//interface object
area = rect;//area refers to rect object
System.out.println(“area of rectangle=”+area.compute(10,45));
area = circ;//area refers to circ object
System.out.println(“area of rectangle=”+area.compute(10,0));
}
}

Packages

P Page 91
One way of reusing the code already created is by extending the classes and implementing the
interfaces. But this is limited to reusing the classes within a program. What if we want to use
classes from other programs without physically copying them into the program under
development. This can be achieved in java by using the concept of packages. Package is similar
to header file and class libraries in other language.

What is package?
Packages are Java’s way of grouping varieties of classes and/or interface together. This grouping
is usually done according to the functionality of classes in the package. Packages in java are
classified into two categories:
a) Java API packages
b) user defined packages

Java API packages


Java API packages provided a large number of classes grouped into different packages according
to functionality. Most of the time we use classes from Java API packages. Figure below shows
some of the java API packages that are frequently used in the programs:

java

lang util io awt net applet

Using java api packages or system packages

We know that the packages are organized in a hieararchical structure as shown above. The above
figure shows that the package named java contains the package named awt. Since the package is
collection of either related classes and/or interface the packages contain class. For e.g. the
package awt contains various classes required for implementing graphical user interface.
Accessing class from packages
There are two ways of accessing the classes stored in a package.
1) if we want to use only one class from a package we specify the fully classified class name of
the class that we want to use. This is done by using the package name containing the class and
then appending it with dot operator. For e.g. to use class called Color in awt package we write:
import java.awt.Colour;
2) if we want to use many classe from a package we use asterisk(*). Asterisk represents all the
class in a file. So if we want to use many classes from package from package awt. The we write:
import java.awt.*;
Note: Import is a keyword that imports classes.
Import statement must be the first statement after the package name.

Creating user defined packages

P Page 92
We can create our own package in java. To create package in java we must first declare the name
of the package using the package keyword followed by package name and then we write the
definition of the classes that we want to be in that package. For example if we want class named
FirstClass to be inside package firstPackage then we write:

package firstPackage;
public class FirstClass
{
//body of class
}

Note: We can also create package hierarchy. This is done by specifying multiple names in a
package statement, separated by dots. E.g.
package firstPackage.secondPackage;
This approach allows us to group related classes into a package and then group related
package into larger package.
In any package many class can be included but there should be only one class with public
modifier.

Multithreaded programming

The process of executing several programs simultaneously is called multitasking or


multithreading. Multithreading is a conceptual programming paradigm where a program or

P Page 93
process is divided into two or more subprograms or processes. This is similar to dividing a large
task into subtasks and then assigning them to different people for executing independently and
simultaneously.
But most of computers have only one processor but it seems that it is performing many task at
once creating illusion of multitasking. This illusion is created by switching the processor
between the processes very fast.
A multithreaded program contains two or more parts that can run concurrently. Each part of such
a program is called a thread and each thread defines a separate path of execution.
Process: A process consists of the memory space allocated by the operating system that can
contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A
process remains running until all of the non-daemon threads are done executing.

Multithreading enables you to write very efficient programs that make maximum use of the
CPU, because idle time can be kept to a minimum.

Life Cycle of a Thread:


A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. Following diagram shows complete life cycle of a thread.

Above-mentioned stages are explained here:

 New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
 Runnable: After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
 Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task.A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
 Timed waiting: A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.
 Terminated: A runnable thread enters the terminated state when it completes its task or
otherwise terminates.

Thread Priorities:

P Page 94
Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.

Java priorities are in the range between MIN_PRIORITY (a constant of 1) and


MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).

Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads. However, thread priorities cannot guarantee the order in
which threads execute and very much platform dependentant.

Creating threads

Java defines two ways in which this can be accomplished:

 You can implement the Runnable interface.


 You can extend the Thread class itself.

Extending the Thread class


This method includes the following steps:
1. declare the class as extending the Thread class
2. implement the run() method that is responsible for executing the sequence of code that the
thread will execute.
3. create a thread object and call the start() method to initiate the thread execution.

Step1. Declaring the class


class MyThread extends Thread
{

Step 2. Implement the run method


Public void run()
{
//thread code here
}

Step 3. Create thread object and call start()


MyThread thread1 = new MyThread();
Thread1.start();

Example program
class ThreadA extends Thread{
public void run(){
for(int i=1;i<10;i++){
System.out.println("From ThreadA:"+i);

P Page 95
}
System.out.println("Exiting ThreadA");
}
}

class ThreadB extends Thread{


public void run(){
for(int i=1;i<10;i++){
System.out.println("From ThreadB:"+i);
}
System.out.println("Exiting ThreadB");
}
}

class ThreadC extends Thread{


public void run(){
for(int i=1;i<10;i++){
System.out.println("From ThreadC:"+i);
}
System.out.println("Exiting ThreadC");
}
}

public class ThreadTest {

public static void main(String[] args) {


ThreadA a = new ThreadA();
ThreadB b = new ThreadB();
ThreadC c = new ThreadC();
System.out.println("Start thread a");
a.start();
System.out.println("Start thread b");
b.start();
System.out.println("Start thread c");
c.start();
}

Implementing the Runnable interface


This method includes following steps:
Step 1. Declare the class as implementing the Runnable interface
Step 2. Implement the run() method
Step 3. Create a thread by defining an object that is instantiated from this runnable class as the
target of the thread
Step 4. Call the thread’s start() method to the thread.

P Page 96
class ThreadB implements Runnable
{
public void run()
{
for(int i=1; i<=10;i++)
System.out.println(“\tThreadB”+i);
}
System.out.println(“end of threadB);
}
class RunnableTest
{
public static void main(String args[])
{
ThreadB thread2 = new ThreadB();
Thread thread3 = new Thread(thread2);
Thread3.start();
System.out.println(“end of main thread”);
}
}

Applet and Application

P Page 97
Applets are small java programs that are primarily used in internet programming. They can be
transported over the internet from one computer to another and run using the AppletViewer or
any web browser that supports java. An applet like application can do many things for us like
arithmetic operation, play sound, display graphics etc.
In short: an applet is a java program that runs in a web browser.

Local and remote applets


An applet developed locally and stored in a local system is called local applet. When a webpage
is trying to find a local applet it does not need internet connection.
A remote applet is that which is developed by someone else and stored on a remote computer. If
our system is connected to internet we can download the remote applet into our system and run
it.

There are some important differences between an applet and a standalone Java application,
including the following:

 An applet is a Java class that extends the java.applet.Applet class.


 A main() method is not invoked on an applet, and an applet class will not define main().
 Applets are designed to be embedded within an HTML page.
 When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
 A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
 The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
 Applets have strict security rules that are enforced by the Web browser. The security of
an applet is often referred to as sandbox security, comparing the applet to a child playing
in a sandbox with various rules that must be followed.
 Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.

Writing simple applet

Until now we have been creating java application program with a single main() method that
created objects, set instance variables and ran methods. Now we will be creating applets.
The steps involved in developing and testing an applet are:

1. Building an applet code (.java file)


2. Creating and executing applet (.class file)
3. Designing a webpage using HTML tags
4. Preparing <APPLET> tag
5. Incorporating <APPLET> tag into the webpage
6. Creating HTML file
7. Testing the applet

Step 1. Building an applet code

P Page 98
Applet generally uses the methods of two classes named

a) Applet and
b) Graphics

These class are defined in the package java.applet and java.awt respectively.
The Applet class contains method init(), start(), and point() that our applet must inherit.
In case of application, main() method is called to initiate the execution of the program. Similarly
in applet a series of method for starting running and stopping the applet is called by the jvm in
browser.
The paint() method of the Applet class, when it is called, actually displays the result of the applet
code on the screen. The output may be text, graphics or sound. The paint() method uses the
methods in class Graphics to perform output operation. Hence paint() method requires an
graphics object as an argument so that it can call graphics method to perform output operation.

public void paint (Graphics g){


//applet code
}

An applet program will have general format as:

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

public class AppletClassName extends Applet{


…………………….
…………………….
public void paint(Graphics g){
…………………..
…………………..
}
……………………
……………………
}

An example program:

P Page 99
import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorldApplet extends Applet


{
public void paint (Graphics g)
{
g.drawString(“hello world”);
}
}

Life Cycle of an Applet:


Four methods in the Applet class give you the framework on which you build any serious applet:

 init():Applet enter the initialization state when it is first loaded. This is achieved by
calling init() method.This method is intended for whatever initialization is needed for
your applet. It is called after the param tags inside the applet tag have been processed. At
this stage, we may do the following if required:

a) Create objects required by object


b) Set up initial values
c) Load images or fonts
d) Set up colors

The initialization is done only one in the applet life cycle. To provide any of the behavior
mentioned above we must override the init() method.

public void init ()


{
//body
}
 start(): This method is automatically called after the browser calls the init() method. It is
also called whenever the user returns to the page containing the applet after having gone
off to other pages. This method may be called more than once.

public void start()


{
//body
}

 stop(): This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.

P Page 100
public void stop()
{
//body
}

 destroy(): This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.

public void destroy()


{
//body
}

 paint(): Invoked immediately after the start() method, and also any time the applet needs
to repaint itself in the browser. The paint() method is actually inherited from the
java.awt.Component class.

public void paint(Graphics g)


{
//body
}

Step 2: creating an executable applet

Executable applet is obtained by compiling the .java file of the applet class. This
gives .class file of the applet class. Compiling the applet is very similar to compiling the
application. We use the same command javac to compile the applet.

Step 3: designing the webpage

As we know that applets are program runned by the webbrowser. Webbrowser runs
webpage. So we must place applet in the webpage so that webbrowser can execute it.

A webpage is basically made up of text and HTML tags that can be interpreted by a
webbrowser or appletviewer.a webpage is also known as HTML page or HTML document. Web
pages are stored using a file extension .html or htm. A HTML page consists of following section:

1. comment section(optional)
2. head section(optional)
3. body section

<html>
<!
………………..

P Page 101
………………..
>
<head>
<title>welcome to java applet</title>
</head>
<body>

</body>
</html>

Step 4: preparing applet tag


<APPLET> tag is used to specify name of the applet and the size the applet requires. <APPLET>
tags attribute CODE is used to specify the name of the applet, WIDTH and HEIGHT is used to
specify the size of the applet. <APPLET> tag is closed by </APPLET>.

Hence the Whole applet tags looks like:

<APPLET
CODE = HelloWorldApplet.class
WIDTH = 100
HEIGHT = 200>
</APPLET>

Step 5: Adding applet to html file


In this step we add the applet tag in the html file where out applet is to be runed.
NOTE : the applet tag is placed in the body section of webpage. As shown below:
<HTML>
<!THIS PAGE CONTAINS APPLET TAG>
<HEAD>
<TITLE>
WELCOME TO JAVA APPLET
</TITLE>
</HEAD>
<BODY>
<APPLET
CODE = HelloWorldApplet.class
WIDTH = 100
HEIGHT = 200>
</APPLET>
</BODY>
</HTML>

Step 6:Running the applet


After creating applet file as well as html file containing applet. We can run the html file
and see the output in java enabled browser or java applet viewer.

P Page 102
An applet to find sum of two number:

Application Conversion to Applets:


It is easy to convert a graphical Java application (that is, an application that uses the AWT and
that you can start with the java program launcher) into an applet that you can embed in a web
page.

Here are the specific steps for converting an application to an applet.

 Make an HTML page with the appropriate tag to load the applet code.
 Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet
cannot be loaded.
 Eliminate the main method in the application. Do not construct a frame window for the
application. Your application will be displayed inside the browser.
 Move any initialization code from the frame window constructor to the init method of the
applet. You don't need to explicitly construct the applet object.the browser instantiates it
for you and calls the init method.
 Remove the call to setSize; for applets, sizing is done with the width and height
parameters in the HTML file.
 Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates
when the browser exits.
 If the application calls setTitle, eliminate the call to the method. Applets cannot have title
bars. (You can, of course, title the web page itself, using the HTML title tag.)
 Don't call setVisible(true). The applet is displayed automatically

Graphical User Interface

P Page 103
Graphical User Interface (GUI) offers user interaction via some graphical components. For
example our underlying Operating System also offers GUI via window,frame,Panel, Button,
Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc. These all are known as
components. Using these components we can create an interactive user interface for an
application.

GUI provides result to end user in response to raised events.GUI is entirely based events. For
example clicking over a button, closing a window, opening a window, typing something in a
textarea etc. These activities are known as events.GUI makes it easier for the end user to use an
application. It also makes them interesting.

Basic Terminologies
Term Description

Component is an object having a graphical representation that can be displayed on the


Component screen and that can interact with the user. For examples buttons, checkboxes, list and
scrollbars of a graphical user interface.

Container object is a component that can contain other components.Components added to


a container are tracked in a list. The order of the list will define the components' front-to-
Container
back stacking order within the container. If no index is specified when adding a component
to a container, it will be added to the end of the list.

Panel provides space in which an application can attach any other components, including
Panel
other panels.

Window is a rectangular area which is displayed on the screen. In different window we can
execute different program and display different data. Window provide us with multitasking
Window
environment. A window must have either a frame, dialog, or another window defined as its
owner when it's constructed.

A Frame is a top-level window with a title and a border. The size of the frame includes any
Frame area designated for the border. Frame encapsulates window. It and has a title bar, menu
bar, borders, and resizing corners.

Canvas component represents a blank rectangular area of the screen onto which the
Canvas application can draw. Application can also trap input events from the use from that blank
area of Canvas component.

Examples of GUI based Applications


Following are some of the examples for GUI based applications.

P Page 104
 Automated Teller Machine (ATM)
 Airline Ticketing System
 Information Kiosks at railway stations
 Mobile Applications
 Navigation Systems

Advantages of GUI over CUI


 GUI provides graphical icons to interact while the CUI (Character User Interface) offers
the simple text-based interfaces.
 GUI makes the application more entertaining and interesting on the other hand CUI does
not.
 GUI offers click and execute environment while in CUI every time we have to enter the
command for a task.
 New user can easily interact with graphical user interface by the visual indicators but it is
difficult in Character user interface.
 GUI offers a lot of controls of file system and the operating system while in CUI you
have to use commands which is difficult to remember.
 Windows concept in GUI allow the user to view, manipulate and control the multiple
applications at once while in CUI user can control one task at a time.
 GUI provides multitasking environment so as the CUI also does but CUI does not
provide same ease as the GUI do.
 Using GUI it is easier to control and navigate the operating system which becomes very
slow in command user interface. GUI can be easily customized.

Exception, stream and I/O

What in exception handling?


- An exception is an indication of a problem that occurs during a program’s execution.
- Exception handling enables you to create applications that can resolve (or handle) exceptions.
- Exception Handling enable programmers to write robust and fault-tolerant programs (i.e., programs that are
able to deal with problems that may arise and continue executing).

Example: Divide by Zero without ExceptionHandling

package ExceptionHandling;

import java.util.Scanner;

P Page 105
public class ExceptionTest {
public static void main(String args[]){

Scanner input = new Scanner(System.in);


System.out.println("Enter first number :");
int num = input.nextInt();
System.out.println("Enter second number :");
int denum = input.nextInt();
int result = num/denum;
System.out.println("The result is "+result);

The term “stream” refers to ordered data that is read from or written to a file.

File processing is a subset of Java’s stream-processing capabilities, which enable a program to read and write data in
memory, in files and over network connections.

We have two goals in this chapter—to introduce file-processing concepts (making the reader more comfortable with
using files programmatically) and to provide the reader with sufficient stream-processing capabilities to support the
networking features

We discuss two forms of file processing here—text-file processing and object serialization.

Hierarchy of data contained in files

P Page 106
Files and Streams
Java views each file as a sequential stream of bytes.

File streams can be used to input and output data as either characters or bytes.

Streams that input and output bytes to files are known as byte-based streams, storing data in its binary format. Streams
that input and output characters to files are known as character-basedstreams, storing data as a sequence of characters.

Note: For instance, if the value 5 were being stored using a byte-based stream, it would be stored in the binary format of
the numeric value 5, or 101.
If the value 5 were being stored using a character-based stream, it would be stored in the binary format of the
character 5, or 00000000 00110101 (this is the binary for the numeric value 53, which indicates the character 5 in the Unicode
character set).
Files that are created using byte-based streams are referred to as binary files, while files created using character-based
streams are referred to as text files.

P Page 107
Java can also associate streams with different devices.

In fact, Java creates three stream objects that are associated with devices when a Java program begins executing— System.in,
System.out and System.err.

Object System.in (the standard input stream object) normally enables a program to input bytes from the keyboard; object
System.out (the standard output stream object) normally enables a program to output data to the screen; and object System.err
(the standard error stream object) normally enables a program to output error messages to the screen.

Each of these streams can be redirected.

For System.in, this capability enables the program to read bytes from a different source. For System.out and System.err, this
capability enables the output to be sent to a different location, such as a file on disk.

Class System provides methods setIn, setOut and setErr to redirect the standard input, output and error streams, respectively.

APPLETS IN JAVA

What is an applet?
—Java programs that can be embedded in HyperText Markup Language (HTML)
documents(i.e., web pages).
— When a browser loads a web page containing an applet, the applet downloads into the web
browser and executes.
—The browser that executes an applet is known as the applet container.

Simple Java Applet: Drawing a String


—Now let’s build an applet of our own. We begin with a simple applet thatdraws "Welcome to
Java Programming!"on the applet.

MULTITHREADING IN JAVA
-Java makes concurrency available to you through the language and APIs. You specify that an
application contains separatethreads of execution, where each thread has its own method-call
stack and program counter, allowing it to execute concurrently with other threads while sharing
application-wide resources such as memory with these other threads.
-This capability, calledmultithreading, is not available in the core C and C++ languages,which
influenced the design of Java.

Creating and Executing Threads


-The preferred means of creating multithreaded Java applications is by implementing the
Runnableinterface (of packagejava.lang).
-ARunnableobject represents a “task” that canexecute concurrently with other tasks.
-TheRunnableinterface declares a single method, run, which contains the code that defines the
task that aRunnableobject should perform.

P Page 108
-When a thread executing aRunnableis created and started, the thread calls theRunnableobject’s
runmethod, which executes in the new thread.

NETWORKING IN JAVA

The socket is simply a softwareconstruct that represents one endpoint of a connection. We show
how to create andmanipulate stream sockets and datagram sockets.

P Page 109
Withstream sockets, a process establishes aconnectionto another process. While the
connection is in place, data flows between the processes in continuous streams. Stream
sockets are said to provide aconnection-oriented service. The protocol used for transmission is
the popular TCP(Transmission Control Protocol).

Withdatagram sockets, individual packetsof information are transmitted. This is not appropriate
for everyday programmers, because the protocol used—UDP, the User Datagram Protocol—is
aconnectionless service, and thus does not guarantee that packets arrive in any particular order.
With UDP, packets can even be lost or duplicated. Significant extra programming is required on
your part to deal with these problems (if you choose to do so).

Understanding URL

The Internet offers many protocols. TheHypertext Transfer Protocol(HTTP), whichforms the
basis of the World Wide Web, uses URIs (Uniform Resource Identifiers) to identify data on the
Internet. URIs that specify the locations of documents are called URLs (Uniform Resource
Locators). Common URLs refer to files or directories and can reference objects that perform
complex tasks, such as database lookups and Internet searches. If you know the HTTP URL of a
publicly available HTML document anywhere on the web, you can access it through HTTP.

P Page 110

You might also like