0% found this document useful (0 votes)
19 views157 pages

Java Programming Concepts for 4th Sem

The document provides an overview of Object-Oriented Programming (OOP) principles and Java programming, including key concepts such as classes, objects, inheritance, and polymorphism. It discusses the evolution of Java, highlighting its history, features, and advantages over procedural programming. Additionally, it emphasizes Java's portability, security, and performance, while comparing it to C and C++.

Uploaded by

sarojinisri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views157 pages

Java Programming Concepts for 4th Sem

The document provides an overview of Object-Oriented Programming (OOP) principles and Java programming, including key concepts such as classes, objects, inheritance, and polymorphism. It discusses the evolution of Java, highlighting its history, features, and advantages over procedural programming. Additionally, it emphasizes Java's portability, security, and performance, while comparing it to C and C++.

Uploaded by

sarojinisri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

lOMoARcPSD|50662627

Java Programming 4th Sem

Computer science (Periyar University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

PROGRAMMING IN JAVA
UNIT-I
Introduction to OOPS: Paradigms of Programming Languages – Basic concepts of Object-Oriented Programming
– Differences between Procedure Oriented Programming and Object-Oriented programming - Benefits of OOPs –
Application of OOPs. Java: History – Java features – Java Environment – JDK – API. Introduction to Java:
Types of java program – Creating and Executing a Java program – Java Tokens- Java Virtual Machine (JVM) –
Command Line Arguments –Comments in Java program.
INTRODUCTION TO OOPS:
The Object-Oriented programming paradigm plays an important role in human-computer interface. It has
different components that take real world objects and perform actions on them, making live interactions between
man and the machine. Following are the components of OOPS −
⮚ This paradigm describes a real-life system where interactions are among real objects.
⮚ It models applications as a group of related objects that interact with each other.
⮚ The programming entity is modelled as a class that signifies the collection of related real-world objects.
⮚ Programming starts with the concept of real-world objects and classes.
⮚ The application is divided into numerous packages.
⮚ A package is a collection of classes.
⮚ A class is an encapsulated group of similar real-world objects.

BASIC CONCEPTS OF OOPS:


Object-Oriented Programming is a paradigm that provides many concepts, such as:
⮚ Class
⮚ Object
⮚ Message passing
⮚ Abstraction
⮚ Encapsulation
⮚ Inheritance
⮚ Polymorphism
⮚ Dynamic Binding
Objects:
Objects are the runtime entities in an object-oriented system. They may represent a place,
person or any other data that the program has to handle. Program objects should be chosen to
match the real world objects.
When a program is executed, the objects interact by sending messages to one another. For
e.g., if “customer” and “account” are two objects, they communicate by requesting and sending
the bank balance.
So, objects contain data and code to manipulate the data called member functions.

Classes:
A class is a collection of objects. It is generic in nature. All objects of a class have the same
characteristics and interact with one another. A class has two components. They are:
● The data members
● The member functions

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

While data members are the features of the real world entity the user tries to represent,
member functions act on data members to use them. For e.g., if furniture is a class, then chair
is an object.
Furniture Chair;
Other e.g.,
Flower rose;
Data abstraction and Encapsulation:
Data abstraction is the phenomenon of revealing only the important features of an object,
and not considering the unimportant details. After abstracting those important details/features,
they are bounded by functions. This process is called data encapsulation. Data encapsulation
restricts the direct access of data by program or the external programming entities.
For e.g.,
Furniture chair;
Chair is an object, whose main features are:
1. a seat, (2) three or four legs, (3) a back rester. So, this is data abstraction.
The other details hidden are if it is made of steel/ iron/ wood/ plastic, color of the chair,
etc.
If the function called get details () will enable the program to get the details of the shape of
the chair, it is called data encapsulation. This is because only the function has the rights to
access the data.
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of another
class. It is possible by inheriting hierarchy.
Inheritance implements one of the major advantages of OOPs called reusability.
Reusability is the concept of using the same code with or without changes to configure another
object.
Polymorphism:
It is the ability to take more than one form. A function can have a different set of arguments
with the same label; this is function overloading. An operator can perform an added function;
this is called the operator overloading. For e.g.,

int add(int,int);
void add(s1,s2);
int add(int, int, float);
int add(float, float);
In the first function, the function add (int, int) adds two integer numbers. In the second
function, the function add(s1, s2) adds two strings. This is operator overloading.
The first function add (int, int) adds two integers and the third function add (int, int, float)
adds three values. This is function overloading.

Dynamic Binding:
Binding refers to the process of linking segments of code to be executed, when the
procedure containing the segment of code is called. This is said to be static or dynamic in nature.
If the procedure call invokes the correct segment of code at the compilation time, it is static
binding. If the procedure call invokes the correct segment of code at the run time, it is dynamic
binding. (i.e., the program will not know which procedure is going to be called until the
particular instant of execution comes).

Message Passing:
The creation of objects, by default, supports the communication of objects. A message from
one object will invoke the procedure in another object, so as to produce a desired result.
Message passing involves specifying the name of the object, the name of the function
(message), and the information to be sent.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Employee. Salary (name);


Where
Employee = object;
Salary = name;
Name = information.
Objects have a life cycle. They can be created and destroyed. So, message passing is also
possible only until the object is alive.
Procedural Programming vs Object-Oriented Programming:
Procedural Oriented Programming Object-Oriented Programming
The program is divided into small parts The program is divided into small parts
called functions. called objects.
Top-down approach. Bottom-up approach.
There is no access specifiers in procedural Object-oriented programming has access
programming. specifiers like private, public, protected, etc.
Adding new data and functions is not easy. Adding new data and function is easy.
Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.
Overloading is not possible. Overloading is possible
There is no concept of data hiding and The concept of data hiding and inheritance is
inheritance. used.
The function is more important than the data. Data is more important than function.
Based on the unreal world. Based on the real world.
Used for designing medium-sized programs. used for designing large and complex
programs
Uses the concept of procedure abstraction. Uses the concept of data abstraction.
Code reusability absent Code reusability present
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
#include <stdio.h> #include <iostream>
int main() { using namespace std;
int number1, number2, sum; int main() {
printf("Enter two integers: "); int first_number, second_number, sum;
scanf("%d %d", &number1, &number2);
cout << "Enter two integers: ";
// calculating sum cin >> first_number >> second_number;
sum = number1 + number2;
// sum of two numbers in stored in variable
printf("%d + %d = %d", number1, sumOfTwoNumbers
number2, sum); sum = first_number + second_number;
return 0;
} // prints sum
cout << first_number << " + " <<
second_number << " = " << sum;

return 0;
}

Output: Output:
Enter two integers: Enter two integers:
12 12
11 11
12+11=23 12+11=23

Benefits of OOPS:
▪ Modularity for easier troubleshooting
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

▪ Refuse of code through inheritance


▪ Flexibility through polymorphism
▪ Effective problem solving

Application of oops:
o Real time systems
o Client server systems
o Hypertext and hypermedia
o Object oriented database
o Neural networks and parallel programming
o AI Expert systems
o Simulation and modelling systems
o Office automation systems
o CIM/CAD/CAM Systems
o Computer aided designs

JAVA EVOLUTION
Java History
Java is a general-purpose, object-oriented programming language developed by Sun Microsystems of the USA in
1991.
Originally called Oak by James Gosling. Java was designed for the development of software for consumer
electronic devices like TVs, VCR and Other electronic machines.
The goal had a strong impact on the development team to make the language simple, portable and reliable.
Table 1.4.1.a shows important milestones in the development of Java.

JAVA MILE STONES

Year Development
1990 Sun Microsystems decided to develop special software that could be used to
manipulate consumer electronic devices. A term of Sun Microsystems
programmers headed by James Gosling was formed to undertake this task.
1991 After exploring the possibility of using the most popular object-oriented
language C++, the team announced a new language named “Oak”.
1992 The team, known as Green Project team by Sun, demonstrated the application of
their new language to control a list of home appliances using a hand-held device
with a tiny touch-sensitive screen.
1993 The World Wide Web (WWW) appeared on the Internet and transformed the text-
based Internet into a graphical-rich environment. The Green Project team came up
with the idea of developing Web applets (tiny programs) using the new language
that could run on all types of computers connected to the Internet.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

1994 The team developed a Web browser called “HotJave” to locate and run applet
programs on Internet. HotJava demonstrated the power of the new language, thus
making it instantly popular among the Internet users.
1995 Oak was renamed “Java”, due to some legal snags. Java is just a name and is not an
acronym. Many popular companies including Netscape and Microsoft announced
their support for Java.
Java established itself not only as a leader for Internet programming but also as a
1996 general-purpose object-oriented programming language. Sun releases Java
Development Kit 1.0
1997 Sun releases Java Development Kit 1.1 (JDK 1.1)
1998 Sun releases Java 2 with version 1.2 of the Software Development Kit (SDK 1.2)
1999 Sun releases Java 2 Platform, Standard Edition (J2SE) and Enterprise Edition
(J2EE)

2000 J2SE with SDK 1.3 was released


2002 J2SE with SDK 1.4 was released
2004 J2SE with JDK 5.0 (Instead of JDK 1.5) was released. This is known as J2SE 5.0
2006 Java SE6
2011 Java SE 7
2014 Java SE 8
2017 Java SE 9
2018 Java SE 10
2018 Java SE 11
2019 Java SE 12
2019 Java SE 13
2020 Java SE 14
2020 Java SE 15
2021 Java SE 16
2021 Java SE 17
2022 Java SE 18
2022 Java SE 19
2023 Java SE 20
2023 Java SE 21(LTS)

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Compiled and Interpreted


A computer language is either compiled or interpreted. Java combines both these
approaches thus making Java a two-stage system. First, the Java compiler translates
source code into bytecode instruction. Byte codes are not machine instructions and in the
next stage Java interpreter generates machine code that can be directly executed by the
machine that is running the Java program.
Platform-Independent and Portable
Java programs can be easily moved from one computer to another, anywhere and
anytime. Changes and upgrades in operating system, processors and system resources
will not force any changes in Java programs.

Java ensures portability in two ways.

⮚ Java compiler generates bytecode that can be implemented on any machine.


⮚ The sizes of the primitive data types are machine-independent.
Object-Oriented
Java is a pure object-oriented language. All program code and data reside within
objects and classes and they are arranged in packages that we use in our programs by
inheritance. The object model in Java is simple and easy to extend. Robust and Secure
Java provides many safeguards to ensure reliable code. It has strict compile and
run time checking for data types. Java also has the concepts of exception handling, which
captures errors and eliminates any risk of crashing the system.
Security is an important issue for a language that is used for programming on the
Internet. The absence of pointers in Java ensures that programs cannot access memory
locations without proper authorization.
Distributed
Java is designed as a distributed language for creating applications on networks.
Java applications can open and access objects on the Internet as easily as they can do in a
local system. So multiple programmers at multiple remote locations collaborate and work
together on a single project.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Familiar, Simple and Small


Java does not use pointers, pre-processor header files etc. Java eliminates operator
overloading, multiple inheritance. So, it is considered as a simple and small language. To
make the language look familiar to the existing programmers, it is modeled on C and C++
language.
Multithreaded and Interactive
Java handling multiple tasks simultaneously is called multithreaded. We need
not wait for the application to finish one task before beginning the other. For example,
we can listen to music while scrolling a page and at the same time download an applet
from a distinct computer.
High Performance
Java performance is impressive for an interpreted language, mainly due to the use
of intermediate byte code. Java architecture designed to reduce overheads during runtime
and incorporating multithreading enhances the overall execution speed of Java programs.
Dynamic and Extensible
Java programs carry with them substantial amounts of run-time type information
that is used to verify and resolve accesses to objects at run time. This makes it possible to
dynamically link code in a safe and extensible manner.
How Java Differs from C And C++
Java is a lot like C and C++ but the major difference between Java with C and
C++. Java is a pure object-oriented language. Java also adds some new features. C and
C++ features that were omitted from Java are:
Java and C
⮚ Java does not include the C unique statement keywords sizeof, and
typeof
⮚ Java does not contain the data types struct and union
⮚ Java does not define the type modifiers keywords auto, extern,
register, signed, and unsigned
⮚ Java does not support and explicit pointer type
⮚ Java does not have a pre-processor and therefore we cannot use #define,
#include, and # ifdef statements

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

⮚ Java requires that the functions with no arguments must be declared with
empty parenthesis and not with the void keyword as done in C
⮚ Java adds new operators such as instanceof and >>>
⮚ Java adds labeled break and continue statements
⮚ Java adds many features required for object-oriented programming

Java and C++


⮚ Java does not support operator overloading
⮚ Java does not have template classes as in C++
⮚ Java does not support multiple inheritances of classes. This is
accomplished using a new feature called “interface”
⮚ Java does not support global variables. Every variables and method is
declared within a class and forms part of that class
⮚ Java does not use pointers
⮚ Java has replaced the destructor function with a finalize () function
⮚ There are no header files in Java

Java and Internet


Java is associated with the Internet because of the fact that the first application
program written in Java was HotJava, a Web browser to run applets on Internet. Internet
users can use Java to create applet programs and run them locally using a “Java-enabled
browser”. Download an applet located on Internet and run it on local computer using Java-
enabled browser as shown in Fig

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Java and World Wide Web


World Wide Web (WWW) is an open-ended information retrieval system
designed to be used in the Internet’ environment. The system contains Web pages that
provide both information and controls. The Web system is open-ended and we can
navigate to a new document in any direction as shown in Fig. Web pages contain HTML
tags that enable us to find, retrieve, manipulate and display documents worldwide.

Web structure of information search

Java communicates with Web pages through a tag called <APPLET>.


Fig: shows this process with the following steps:

Java’s interaction with the web

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

1. The user sends request for HTML document to remote computer’ Web Server. The
Web Server is a program that accepts request, processes the request, and sends the
required document.
2. The HTML document is returned to the user’s browser. The document contains the
APPLET tag, which identifies the applet.
3. The applet byte code is transferred to the user’s computer.
4. The Java-enabled browser on the user’s computer interprets the byte codes and
provides output.
5. The user may have further interaction with the applet but with no further downloading
from the provider’s Web server.
Web Browsers
Web browsers are used to navigate through the information found on the net. They
allow us to retrieve the information spread across the Internet and display it using HTML.
Web browsers are
⮚ Hot Java
⮚ Netscape Navigator
⮚ Internet Explorer
Hardware And Software Requirements
Java is currently supported on Windows 95, Windows NT, Windows XP, Sun
Solaris, Macintosh and UNIX machines.
The minimum hardware and software requirements for Windows 95 version of Java
are
⮚ IBM-compatible 486 system
⮚ Minimum of 8 MB memory
⮚ Windows 95 software
⮚ A Windows-compatible sound card, if necessary
⮚ A hard drive
⮚ A CD-ROM drives
⮚ A Microsoft-compatible mouse
Java Support Systems
Systems to support Java for delivering information on the Internet as shown
below.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Support systems Description


⮚ Internet connection - Local computer should be connected to the
Internet.
⮚ Web Server - A program that accepts requests and sends
the required document.
⮚ Web Browser - A program that provide access to WWW
and runs Java applets.
⮚ HTML - A language for creating hypertext for the
Web.
⮚ APPLET Tag - For placing Java applets in HTML

document.
⮚ Java Code - Java code is used for defining Java applets.
⮚ Byte Code - Compiled code and transferred to the user
Computer
Java Environment
Java Environment includes a large number of development tools known as Java
Development Kit (JDK) and classes and methods known as Java Standard
Library (JSL) or Application Programming Interface (API).

Java Development Kit (JDK)


The Java Development Kit with a collection of tools that are used for
developing and running Java programs. Java development tools are:
⮚ Applet viewer – Enable us to run Java applets.
⮚ javac – Java compiler translates Java source code to byte code
files.
⮚ java – Java interpreter, which runs applets and applications by
reading & interpreting bytecode files into machine code
files
⮚ javap – Java disassembler, which enables us to convert byte code
files into a program description.
⮚ javah – Produce header files for us with native methods.

⮚ javadoc – Create HTML documents from Java source code files.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

⮚ jdb – Java debugger, which helps us to find errors in our


programs.

To create a Java program, we need to create a source code file using a text editor.
The source code compiled using the Java compiler javac and executed using the Java
interpreter java. The tools used to build and run application programs are shown in Fig.

Process of building and running Java application programs

Application Programming Interface (API)


The Java standard Library includes hundreds of classes and methods
grouped into several functional packages. Most common packages are
⮚ Language Package: A collection of classes and methods for
implementing basic features of Java.
⮚ Utilities Package: A collection of classes to provide utility functions such
as date and time manipulation.
⮚ Input/Output Package: A collection of classes to provide Input/
Output manipulation.
⮚ Networking Package: A collection of classes for communicating with other
computers via the Internet.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

⮚ AWT Package: The Abstract Window Tool Kit package contains


classes that implement platform independent GUI.
⮚ Applet Package: A collection of classes that allow us to create Java
applets.

SIMPLE AND MORE JAVA PROGRAM


We begin with a very simple Java program that prints a line of text as output.
Program: A simple Java program

/*
*Simple and More Of Java Program
* This code compute summation of two numbers
*/
class SimpleProgram
{
public static void main(String args[])
{
int a = 5, b = 5; // Declaration and initialization
int c; // Simple declaration
c = a + b;
[Link](“Summation of two numbers” + c);
}
}
program
Program is the simplest of all Java programs. Let us discuss the program line
by line and understand unique features that constitute a Java program.
The first line
class SimpleProgram
declares a class, Java is a pure object-oriented language and everything must be placed
inside a class. class is a keyword and SimpleProgram is a Java identifier that specifies
the name of the class to be defined.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Every class definition in Java begins with an opening brace “{“ and ends with a matching
closing brace “}”.
The third line
public static void main(String args[])
defines a method name main. This is the starting point for the interpreter to begin the
execution of the program. A Java application can have any number of classes but only
one of them must include a main method to initiate the execution. This line contains a
public keyword as an access modifier, static keyword, which declares this method
belongs to the entire class and not part of any object and void states that the main method
does not return any value.
String args[] declares a parameter named args, which contains any array of objects of
the class type String.
The statement

int a = 5 , b = 5;
declares variable x and y and initializes it to the value 5 and the statement int c;
merely declares a variable c. All of them have been declared as int type variables.
The executable statement in the program is
[Link](“Summation of two numbers: ” + c);
The println method is a member of the out object, which is a static data member of
System class. This line prints the result on the screen as
Summation of two numbers: 10
Here, the operator + acts as the concatenation operator of two strings. The value
of c is converted into string before concatenation. The method println always appends a
new line character to the end of the string. Every Java Program must end with a semicolon
( ; ).
In Java, the single-line comments begin with // and end at the end of the line as
shown on the lines of the declaration a, b and c. The multi-line comments by starting with
/* and end with a */ as shown at the beginning of the program.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

JAVA PROGRAM STRUCTURE


Java Program Structure as shown in Fig

Suggested
Documentation Section

Package Statement

Import Statements
Optional
Interface Statements

Class Definitions

Main Method Class


{
Main Method Definition Essential
}

General Structure of a Java program


Documentation Section
The documentation section comprises a set of comment lines giving the name of
the program, the author and other details. Comments must explain why and what of
classes and how of algorithms. In addition to the two styles, Java also uses third style of
comment /**…*/ known as documentation comment.
Package Statement
The first statement allowed in a Java file is a package statement. This statement
declares a package name and informs the compiler that classes defined here belong to this
package.

Example:
Package student;
Package statement is optional.
Import statements

Import statement is similar to the #include in C.


Example:
import [Link];
This statement instructs the interpreter to load the Test class in the package
student.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Interface statement
An interface is like a class but a group of method declarations. This is also an
optional section and is used only when we wish to implement the multiple inheritance
features in the program.
Class definition
A java program may contain multiple class definitions. Classes are the primary
and essential elements of a Java program.
Main Method class
A Java stand-alone program requires a main method as its starting point; this class
is the essential part of a Java program. The main method creates objects of various classes
and establishes communications between them. On reaching the end of main, the program
terminates and control passes back to the operating system.

JAVA TOKENS
Smallest individual units in a program are known as tokens. The smallest units of
the program are the characters used to write Java tokens. Java language includes five types
of tokens. They are:
⮚ Reserved Keywords
⮚ Identifiers
⮚ Literals
⮚ Operators
⮚ Separators
Reserved Keywords
Java language has reserved 50 words as keywords. Table 1.5.5.a list these
keywords. Keywords, combined with operators and separators according to syntax, form
the definition of the Java language. All keywords are to be written in lower-case letters.
Since keywords have specific meaning in Java, we cannot use them as names for variables,
classes, methods and so on.
Identifiers
Identifiers are programmer-designed tokens. They are used for naming classes,
methods, variables, objects, labels, packages and interfaces in a program.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Rules for forming Java identifier as


1. They can have alphabets, digits, and the underscore and dollar sign
characters.
2. They must not begin with a digit.

3. Uppercase and lowercase letters are distinct.


[Link] can be of any length.
Java Keywords

abstract assert boolean break


byte case catch char
class const continue default
do double else enum

extends final finally float


for goto if interface
implements import instanceof int
long native new package
private protected public return
short static stricfp super
switch synchronized this throw
throws transient try void
volatile while

Literals
Literals in Java are a sequence of characters (digit, letters, and other characters)
that represent constant value to be stored in variables. Java language specifies five types
of literals. They are:
⮚ Integer literals
⮚ Floating-point literals
⮚ Character literals
⮚ String literals
⮚ Boolean literals

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Operators
An operator is a symbol that takes one or more arguments and operates on them
to produce a result.
Separators
Separators are symbols used to indicate where groups of code are divided and
arranged. Table lists separators and their functions.

Table 1.5.5.b Java Separators

Name Purpose
Parentheses ( ) Used to enclose parameters in method definition and invocation, also used
for defining precedence in expression, containing expressions for
flow control, and surrounding cast types.

Braces { } Used to contain the values of automatically initialized arrays and


to define a block of code for classes, methods and local scopes

Brackets [ ] Used to declare array types and for dereferencing array values.

Semicolon ; Used to separate statements

Comma , Used to separate consecutive identifiers in a variable declaration,


also used to chain statement inside ’for’ statement

Period. Used to separate package names from sub-packages and


classes; also used to separate a variable or method from a
reference variable

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

JAVA STATEMENTS
The statements in Java are like sentences in natural language. Java
implements several types of statements in Fig

Fig : Classification of Java Statements

Implementing A Java Program


Implementing a Java application program involves a series of steps. They include:
⮚ Creating the program
⮚ Compiling the program
⮚ Running the program
Creating the program
We can create a program using any text editor. Assume that we have
entered the following program:
Program Simple program for testing

class SimpleProgramTest
{
public static void main(String args[])
{
[Link](“Welcome to Java” );
}
}

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

We must save this program in a file called [Link] ensuring


that the filename contains the class name properly. This file is called source file, all source
files will have the extension .java. If a program contains multiple classes, the file name
must be the class name of the class containing the main method.
Compiling the program
To compile the program, we must run the Java Compiler javac, with the name
of the source file on the command line as shown below:
>javac [Link]
If everything OK, the javac compiler creates a file called
[Link] containing the bytecodes of the program.
Running the program
We need to use the java interpreter to run a stand-alone program. At command
prompt, type
>java SimpleProgramTest
Now, the interpreter looks for the main method in the program and begins
execution from there. When executed, our program displays the results as:
Welcome to Java

JAVA VIRTUAL MACHINE


Java compiler produces an intermediate code known as byte code for machines
that do not exist. This machine is called the Java Virtual Machine and it exists only
inside the computer memory. Fig. 1.5.8.a shows the process of compiling a Java program
into bytecode, which is also referred to as virtual machine code.

Java Program Java Compiler Virtual Machine

Source Code Byte Code


Fig: Process of compilation

The virtual machine code is not machine specific. The machine specific code is
generated by the Java interpreter by acting as an intermediary between the virtual machine
and real machine as shown in Fig. 1.5.8.b.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Byte Code Java Interpreter Machine Code

Virtual Machine Real Machine


Fig: Process of converting byte code into machine code

COMMAND LINE ARGUMENTS


Command line arguments are parameters that are supplied to the application
program at time of invoking it for execution. We can write java programs that can receive
and use the arguments provided in the command line.
/*
* Program for Command line arguments as input
*/
class ComLineTest
{
public static void main(String args[])
{
int count , I = 0; String
string;
count = [Link];
[Link](“ No. of arguments = ” + count);
while ( i < count )
{

string = args[ i]; i = i +1;


[Link]( i +“ : ” + string );
}
}
}

The above program shows the use of command line arguments. Compile and
run the program with the command line as follows.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

>java ComLineTest BASIC FORTRAN C++ JAVA


Upon execution, the command line arguments BASIC FORTRAN C++ JAVA are passed to the
program through the array args . That is the element args[0] contains BASIC, args[1] contains FORTRAN,
and so on. These elements are accessed using the loop variables i as an index like
name = args[i]
The index i is incremented using a while loop until all the arguments are accessed. The
number arguments is obtained by statement

count = [Link];
The output of the program as:
No. of arguments = 4
1: BASIC
2: FORTRAN
3: C++
4: JAVA

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

PROGRAMMING IN JAVA
UNIT-II
Elements: Constants – Variables – Data types - Scope of variables – Type casting – Operators: Special
operators –Expressions – Evaluation of Expressions, Decision making and branching statements-
Decision making and Looping–break – labeled loop – continue Statement. Arrays: One Dimensional
Array – Creating an array – Array processing –Multidimensional Array – Vectors – Array List –
Advantages of Array List over Array Wrapper classes.

CONSTANTS, VARIABLES AND DATA TYPES


Constants and Symbolic constants

CONSTANTS:

Constants in Java refer to fixed values that do not change during the execution of a program. Types of
constant are as shown in Fig

Java Constants

Numeric constants Non-Numeric constants

Integer Constants Real constants Character constants String constants

Numeric Constants

Integer Constants
A whole number is called integer constants. An integer constant refers to a sequence of digits. There are
three types of integers, namely, decimal, octal and hexadecimal integer.
Decimal integers consist of a set of digits, 0 through 9, preceded by optional minus sign. Valid examples
are:

123 -231 0 253444


Embedded spaces, commas, and non-digit characters are not permitted between digits. For example
36 5689 20.000 $777456 are invalid numbers
An octal integer constant consists of any combination of digit from the set
0 through 7, with leading 0. Valid examples are:
046 123 0 0675
A hexadecimal integer constant consists of any combination of digit from the set 0 through 9 and A
through F and preceded by 0x or 0X

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Valid examples are:


0x3Bf7 0X27 0x
Real Constants
Number containing with decimal point is called real constants. There are
two types of notation, namely,
Decimal notation
Exponential (or scientific) notation.
In decimal notation a whole number followed by a decimal point and the fractional part, which is an
integer. Valid examples are:

0.376 .57 -.46 23.68


The general form of an Exponential notation is:
mantissa e-exponent
The mantissa is either a real number expressed in decimal notation or an integer. The exponent is an
integer with an optional plus or minus sign. The letter e separating the mantissa and the exponent can be
written in either lowercase or uppercase.

Valid examples are:


0.47E2 12e-7 1.8e+3 7.3E2 -6.0e-2
Non-Numeric Constants:
Character constants
A single character constant contains a single character enclosed within a
pair of single quote marks. Valid examples are: ‘6’ ‘s’ ‘W’ ‘;’ ‘ ’

String constants
A string constant is a sequence of characters enclosed between double quotes. The characters may be
alphabets, digits special characters and blank spaces.

Valid examples are:


“Hello” “3566” “%---$” “22-7”
Backslash character constants
Java supports some special backslash character constants that are used in output methods. The characters
combinations are known as escape sequences.
Table 2.3.1.b Backslash character constants

Constants meanings
‘ \ b’ back space
‘\f’ form feed

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

‘ \ n’ new line
‘ \r’ carriage return
‘ \ t’ horizontal tab
‘ \ ‘’ single quote
‘ \ “’ double quote
‘ \ \’ back slash

Symbolic constants
We often use certain unique constants in a program. These constants may appear repeatedly in a number
of places in the program. For example of such a constant is 3.142 representing the value of the
mathematical constant “pi”. We face two problems in the subsequent use of program. They are:

Problem in modification of the program.


Problem in understanding the program.
Modifiability
We may like to change the value of “pi” from 3.142 to 3.14159 to improve the accuracy of calculation. In
this case, we will have to search throughout the program and explicitly change the value of the constant
wherever it has been used. If any value is left unchanged, the program may produce incorrect outputs. A
constant is declared as follows:
final type symbolic-name = value; Valid examples are:
final int STRENGTH = 40; final PASS_MARK = 40; final float PI = 3.1459;
Rules for forming the symbolic constants are:
Symbolic names take the same form as variable names. But, they are written in CAPITALS.
After declaration of symbolic constants, they should not be assigned any other value within a program.
Symbolic constants are declared for types.
They cannot be declared inside a method. They should be used only a class data members in the beginning
of the class.

VARIABLES
A variable is an identifier that denotes a storage location used to store a data value. A variable may take
different values at different times during the execution of the program. Variable names may consist of
alphabets, digits, the underscore ( _) and dollar characters, with following conditions.

They must not begin with a digit


Uppercase and lowercase are distinct. This means that the variable Total is not the same as total or
TOTAL.
It should not be a keyword

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

White space is not allowed


Variable names can be of any length.
DATA TYPES
The size and type of values that can be stored in variable is called as Data type. Data types in Java under
various categories are shown in Fig.2..3.3.a.
Data types in Java
Primitive (Intrinsic) Non-Primitive (Derived)
Numeric Non-Numeric Classes Arrays
Interface
Integer Floating-Point Character Boolean
Fig.2.3.3.a Data types in Java
Integer Types
Integer types can hold whole numbers such as 456, -26, and 6873. Java supports four types of integers
are byte, short, int and long as in Fig.2.3.3.b. Java does not support the concept of unsigned types and
therefore all Java values are signed meaning they can be positive or negative. Table 2.3.3.c shows the
memory size of all the four integer data types.

Integer

byte long

short int
Fig.2.3.3.b Integer Data types
We must use a byte variable to handle smaller number. This improves the speed of execution of the
program. We can make integers long by appending the letter L or l at the end of the number.
Example: 123L or 123l.

Table 2.3.3.c Type and size Of Integer Types


Type Size
byte One byte
short Two bytes
int Four bytes
long Eight bytes

Floating Point Types


Integer types can hold only whole numbers and therefore we use another type known as floating point
type to hold numbers containing fractional parts such as 27.59 and -1.375. There are two kinds of floating

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

point storage in Java as shown in Fig.2.3.3.d


Floating Point

float double
Fig.2.3.3.d Floating-point data types
The float type values are single-precision numbers while the double types represent double-precision
numbers. Table 2.3.3.e gives the size of these two types.
Table 2.3.3.e Type And Size Of Floating Point
Type Size
float 4 bytes
double 8 bytes
Floating point numbers are treated as double-precision quantities. To force
them to be in single-precision mode, we must append f or F to the numbers.
Example:
1.23f 7.56923e5F
Double-precision types are used when we need greater precision in storage of floating point numbers. All
mathematical functions such as sin, cos and sqrt return double type values.
Character Type
In order to store character constants in memory, Java provided a character data type called char. The char
type assumes a size of 2 bytes but it can hold only a single character.

Boolean Type
Boolean type is used when we want to test a particular condition during the execution of the program.
There are only two values that a Boolean type can type: true or false. Boolean type denoted by the
keyword boolean and uses only one bit of storage. The words true and false cannot be used as the
identifier.

Declaration Of Variables
In Java, variables are the names of the storage locations. A variable must be declared before it is used in
the program. A variable can be used to store a value of any data type. After designing the variable names,
we must declare them to the complier. Declaration does three things:
It tells the compiler what the variable name is
It specifies what type of data the variable will hold.
The place of declaration decides the scope of the variables. The general form of declaration of a variable
is:
type variable1, variable2,……, variableN;
Variables are separated by commas. A declaration statement must end with a semicolon. Some valid
declarations are:

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

int rollno; float average; double pi;


byte b;
char c1, c2;
Giving Values To Variables
A variable must be given a value after it has been declared that before it is used in an expression. This can
be achieved in two ways:
By using an assignment statement
By using a read statement
Assignment Statement
A simple method of giving value to a variable is through the assignment statement as
variablename = value;
For Example:

rollno = 1;
c1 = ‘ x ‘;
Another method to assign a value to a variable at the time of its declaration as
type variablename = value;
For Example:
int rollno = 1;
float average = 68.66;
The process of giving initial values to variables is known as the initialization. The following are valid
Java statements:
float x, y, z; // declares three float variables
int m = 3, n = 6; // declares and initializes two Int variables

Getting Values of Variables


A program is written to manipulate a given set of data and to display or print the results. Java supports
two output methods that can be used to send the results to the screen.
print( ) method
println( ) method
The print( ) method sends information into a buffer. This buffer is not flushed until a new line (or end-
of-line) character is sent. As a result, the print( ) method prints output on one line until a new line character
is encountered.
For example, the statements,
[Link](“Hai ”); [Link](“Java ! “);
will display the words Hai Java ! on one line and waits for displaying further information on the same

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

line. We may display on next line by printing a new line character as follows:
[Link](“ \n “);
For Example:
[Link](“Hai ”); [Link](“ \n “);
[Link](“Java ! “);
will display the output in two lines as
Hai Java !
The println( ) method takes the information provided and displays it on a line followed by a line feed .
For Example, the statements
[Link](“Hai ”); [Link](“Java ! “);

will produce the following output:


Hai Java !

Scope of variables
Java variables are classified into three kinds
Instance variables: Instance variables are created when the objects are instantiated.
Class variables: Class variables are global to a class and belong to the entire set of objects that class
creates.
Local variables: Variables declared and used inside the methods are called local variables.

What is scope of variable?


The area of the program where the variable is accessible is called its scope.
In programming, a variable can be declared and defined inside a class, method, or block. It defines
the scope of the variable i.e. the visibility or accessibility of a variable. Variable declared inside a block
or method are not visible to outside. If we try to do so, we will get a compilation error. Note that the scope
of a variable can be nested.
We can declare variables anywhere in the program but it has limited scope.
A variable can be a parameter of a method or constructor.
A variable can be defined and declared inside the body of a method and constructor.
It can also be defined inside blocks and loops.
Variable declared inside main() function cannot be accessed outside the main() function

public class Demo


{
//instance variable

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

String name = "Andrew";


//class and static variable
static double height= 5.9;
public static void main(String args[])
{
//local variable
int marks = 72;
}
}

Type Casting
We need to store a value of one type into a variable of another type. In such situation, we must cast the
value to be stored by proceeding it with the type name in parentheses. The syntax is:
type variable1 = ( type ) variable2;
The process of converting one data type to another is called casting. Examples:

int m = 50;
byte n = ( byte ) m;
long c = ( long ) m;
Four integer types can be cast to any other type except Boolean. Similarly, the float and double can be
cast to any other type except Boolean. Casting to smaller type can result in a loss of data. Casting a floating
point value to an integer will result in a loss of the fractional part. Table 2.3.8.a. lists those casts, which
are guaranteed to result in no loss of information

Table Casts that results in No Loss Inforamtion


From To
byte short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
int long, float, double
long float, double
float double

Automatic Conversion
For some types, it is possible to assign a value of one type to a variable of a different type without a cast.
Java does the conversion of the assigned value automatically. This is known as automatic type conversion.
For example, int is large enough to hold a byte value. Therefore,

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

byte b = 75;
int a = b;
are valid statements.
The process of assigning a smaller type to a larger one is known as widening or promotion and that of
assigning a larger type to a smaller one is known as narrowing.

OPERATORS AND EXPRESSIONS


Introduction
Java supports a rich set of operators. An operator is a symbol that tells the computer to perform certain
mathematical or logical manipulations. Operators are used in programs to manipulate data and variables.

Java operators can be classified into a number of types are:


Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment and decrement operators
Conditional operators
Bitwise operators
Special operators
Special operators

Arithmetic Operators
Java provides all the basic arithmetic operators are listed in Table 2.4.2.a. The operators +, -, * and / all
work the same way as they do in other languages. These can operate on any built-in numeric data type of
Java. We cannot use these operators on Boolean type. The unary minus operator, in effect, multiplies its
single operand by -1. Therefore, a number preceded by a minus sign changes its sign.
Table: Arithmetic Operators
Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division(Remainder)

Arithmetic operators are used as

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

a-b a+b
a*b a/b
a%b -a+b
Integer Arithmetic
When both the operands in single arithmetic expression such as a + b are integers, the expressions is called
an integer expression, and the operation is called integer arithmetic. Integer arithmetic yields an integer
value. In above examples if a and b are integers the a =2 and b = 2 we have the following results:

a–b = 0
a+b = 4
a*b = 4
a/b = 1 (decimal part truncated)
a%b = 0 (remainder of integer division)
For modulo division ( % ), the sign of the result is always the sign of the first operand.

Real arithmetic
An arithmetic operation involving only real operands is called real arithmetic. A real operand may
assume values either in decimal or exponential notation. The floating-point modulus operator returns the
floating-point equivalent of an integer division. What this means is that the division is carried out with
both floating-point operands, but the resulting divisor is treated as an integer, resulting in a floating-point
remainder.
Mixed-mode Arithmetic
When one of the operand is real and the other is integer, the expression is called a mixed-mode arithmetic
expression. If either operand is of the real type, then the other operand is converted to real and the real
arithmetic is performed. The result will be a real. Thus
16 / 5.0 produce the result 3.1
Whereas
16 / 5 produce the result 1
Relational Operators
We often compare two quantities, and depending on their relation, take certain decisions. For example,
we may compare the age of two persons, or the price of two items, and so on. These comparisons can be
done with the help of relational operators. Java supports six relational operators as shown in Table
Table Relational Operators
Operator Meaning
< is less than
<= is less than equal

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

> is greater than


>= is greater than equal
== is equal to
!= is not equal to

A simple relational expression contains only one relational operator and is of the following form:
ae -1 relational operator ae – 2
When arithmetic expressions are used on either side of a relational operator, the arithmetic expressions
will be evaluated first and then the results compared. That is, arithmetic operators have a higher priority
over relational operators.
Logical Operators
Java has three logical operators as shown in Table. The logical operators && and || are used when we
want to form compound conditions by combining two or more relations. Example:

a > b && x = = 10
An expression combines two or more relational expression is called as logical expression or compound
relational expression. Logical expression also yields a value of true or false.

Table: Logical Operators


Operator Meaning
&& is logical AND
|| is logical OR
! is logical NOT

Assignment Operators
Assignment operators are used to assign the value of an expression to a variable. The form

v op= exp;

Where v is a variable, exp is an expression and op is a java binary operator. The operator op= is known
as the shorthand assignment operator.

The shorthand assignment operators are illustrated in Table 2.4.5.a.


Table Shorthand Assignment Operators
Statement with simple Statement with Assignment operator
Shorthand operator a= a + 1 a+=1

a =a-1 a-=1
a = a * ( n + 1) a*=n+1
a =a %b a%=b
a = a / ( n + 1) a/=n+1

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

The use of shorthand assignment operators has three advantages:


What appears on the left-hand side need not be repeated and therefore it becomes easier to write.
The statement is more concise and easier to read
Use of shorthand operator results in a more efficient code.
Increment and Decrement Operators
The increment and decrement operators:
++ and - -
The operator ++ adds 1 to the operand while -- subtracts 1. Both are unary operators and are used in the
following form:
++m; or m++;
--m; or m--;
We use the increment and decrement operators extensively in for and while loops.
Example:
m = 5;
y = ++m;
In this case, the value of y and m would be 6. Suppose, if we rewrite the above statements
m = 5;
y = m++;
Then, the value of y would be 5 and m would be 6. Prefix operator adds 1 to the operand and then the
result is assigned to the variable on left. Postfix operator first assigns the value to the variable on left and
then increments the operand.
Similar is the case, when we use ++( or --) in subscripted variables. That is the statement a[i++] = 10 is
equivalent to
a[ i ] = 10
i=i+1
Conditional Operators
The conditional pair ? : is a ternary operator available in Java. This operator is used to construct
conditional expressions of the form
exp1 ? exp2 : exp3
Where exp1,exp2, exp3 are expressions.
The operator ? : works as follows : exp1 is evaluated first. If it is nonzero (true), then the expression
exp2 is evaluated and becomes the value of the conditional expressions. If exp1 is false, exp3 is evaluated
and is value becomes the value of the conditional expression.
For Example:
a = 10;
b = 15;

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

x = (a > b) ? a : b;
In this example , the value of x is the value of b.

Bit Wise Operators


Java has a special operators is known as bitwise operators or manipulation of data at values of bit level.
These operators are used for testing the bits, or shifting them to the right or left as shown in Table
Table Bitwise Operators
Operator Meaning
& bitwise AND
! bitwise OR
^ bitwise Exclusive OR
~ one’s Complement
<< shift left
>> shift right
>>> shift right with zero fill
Special Operators
Java supports some special operators of interest such as instanceof
operator and member selection operator ( .).
Instanceof Operator
The instanceof 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 allows us to determine whether the object
belong to a particular class or not.
Example:
person instanceof student
is true if object person belong to the class student; otherwise it is false.
Dot operator
The dot operator ( . ) is used to access the instance variables and methods of class objects.
Example:
[Link]; // Reference to the variable age

[Link]( ); // Reference to the method salary()


It is also used to access classes and sub-packages from a package.

Arithmetic Expressions
An arithmetic expression is a combination of variables, constants, and operators
.Example of Java expression are shown in Table2.4.10.a.
Table2.4.10.a

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Expressions

Algebraic Expression Java Expression

ab-c a*b-c

ab a*b/c
c

Evaluation Of Expressions
Expressions are evaluated using assignment statement of the form
variable = expression;
variable is any valid Java variable name. When the statement is encountered, the expression is evaluated
first and the result then replaces the previous value of the variable on the left-hand side.
Examples of evaluation statements are l = x*y-z ;

m = y/z*x ;
The blank space around an operator is optional.
2.4.12 Precedence Of Arithmetic Operators
An arithmetic expression without any parentheses will be evaluated from left to right using the rules of
precedence of operators. There are two distinct priority levels in Java:
High priority * / % Low priority + -
The basic evaluation procedure includes two left-to-right passes through the expression. During the first
pass, the high priority operators are applied and second pass, the low priority operators are applied.
Consider the following evaluation statement:
x=a-b/3
When a = 9 and b = 6, the statement becomes
x=9–6/3
and evaluated as

First pass
x = 9 – 2 ( 6 / 3 evaluated )

Second pass
x=7 ( 9 - 2 evaluated )

Introducing parentheses into expression can change the order of evaluation. Parentheses may be nested,
and in such cases, the expression will proceed out from innermost set of parentheses. Every opening
parenthesis has a matching closing one. Parentheses allow us to change the order of priority.

TYPE CONVERSIONS IN EXPRESSIONS


Automatic Type Conversion

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Java permits mixing of constants and variables of different types in an expression, but during evaluation
it adheres to very strict rules of type conversion. If the operands are of different types, the ‘lower’ type is
automatically converted to the higher type before the operation proceeds. The

result is of the higher type. Table 2.4.13.a provides a reference chart for type conversion.
Table 2.4.13.a Automatic Type Conversion Chart
char byte short int long float double
char int int int int long float double
byte int int int int long float double
short int int int int long float double
int int int int int long float double
long long long long long long float double
float float float float float float float double
Double double double double double double double double

The final result of an expression is converted to the type of the variable on the left of the assignment sigh
before assigning the value to it. The following changes are occurs in final assignment.
float to int causes truncation of the fractional part.
double to float causes rounding of digits.
long to int causes dropping of the excess higher order bits.
Casting a Value
We need to store a value of one type into a variable of another type. In such situation, we must cast the
value to be stored by proceed it with the type name in parentheses. The general form of a cast is:
( type_name ) expression
Where type_name is one of the standard data types. The expression may be constant, variable or an
expression.
Examples of casts and their actions are
X = ( int ) 7.5 7.5 is converted to integer by truncation
A = ( int ) 21.3 / ( int )4.5 Evaluated as 21/4 and the result would be 5

Operator Precedence And Associativity


Each operator in Java has precedence associated with it. The operators at the higher level of precedence
are evaluated first. The operators of the same level

of precedence are evaluated from left to right or from right to left, depending on level. This is known as
the associativity property of an operator. Table 2.4.14.a provides a complete list of operators, their
precedence levels, and their rules of association.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Table 2.4.14.a Java Operators precedence and associativity

Operator Meaning Associativity Rank


. Member selection Left to Right 1
() Function call
[] Array element reference
- Unary minus Right to left 2
++ Increment
-- Decrement
! Logical Negation
~ One’s complement
(type) Casting
* Multiplication Left to Right 3
/ Division
% Modulus
+ Addition Left to Right 4
- Subtraction
<< Left shift Left to Right 5
>> Right shift
>>> Right shift with zero fill
< Less than Left to Right 6
<= Less than or equal to
> Greater than
>= Greater than or equal to
Instanceof Type comparison
== Equality Left to Right 7
!= Inequality
& Bitwise AND Left to Right 8
^ Bitwise XOR Left to Right 9
| Bitwise Or Left to Right 10
&& Logical AND Left to Right 11
|| Logical OR Left to Right 12
?: Conditional operator Right to Left 13
= Assignment operator Right to Left 14
Op= Shorthand assignment

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Unit Questions
Explain basic concepts of Object oriented programming.
What are the benefits of OOP? List a few areas of applications of OOP technology.
Explain features of Java.
What are the differences between Java & C and C++ & Java
Describe the structure of a typical Java program
What is a Token? List the various types of Tokens supported by Java.
What is Separators? Describe the various separators used in Java.
Explain Java virtual machine?
What are command line arguments? How are they useful?
Enumerate the rules for creating identifiers in Java.

DECISION MAKING WITH BRANCHING


Introduction
We have a number of situations, where we may have to change the order of execution of statements based
on certain conditions, or repeat a group of statements until certain specified conditions are met. This
involves a kind of decision making to see whether a particular condition has occurred or not and then
direct the computer to execute certain statements accordingly.
Control or decision-making statements are
if statements
switch statement
Conditional operator statement
Decision Making With simple If Statement
The if statement is a decision-making statement and is used to control the flow of execution of statements.
The general form is

if (test expression)
It allows the computer to evaluate the expression first and then, based on the value of expression is ‘true’
or ‘false’, it transfers the control to a particular statement

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Fig: Two-way branching


The if statement may be implemented in different forms based on the condition to be tested.
Simple if statement
if …else statement
Nested if…else statement
else if ladder.
Simple If Statement
The general form is
if ( test expression)
{
statement-block;
}
statement-x;

The ‘statement-block’ may be single or group of statements. If the test expression is true, the statement-
block will be executed; otherwise the execution will to the statement-x. (See Fig 2.5.2.b)
Entry

Example
if (age<18)

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

{
[Link](“The person is not eligible for vote”);
}

The If…Else Statement


The general form is

if ( test expression)
{
statement-block1;

}
else
{
statement-block2;
}
statement-x;

If the test expression is true, the statement-block1 will be executed; otherwise, the statement-block2 will
be executed, not both. In both the cases, the control is transferred to the statement-x.

Fig: Flowchart of if….else control


Example if (age<18)

{
[Link](“The person is not eligible for vote”);
}
else
{

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link](“The person is eligible for vote”);


}

Nesting Of If…Else Statement


The general form is
if ( test expression1)
{
if ( test expression2)
{
statement-block1;
}
else
{
statement-block2;
}
}
else
{
statement-block3;
}
statement-x;

If the test expression1 is false, the statement-block3 will be executed; otherwise it continues to perform
the second test. If test expression2 is true, the statement-block1 will be executed; other wise the statement-
block2 will be executed and then control is transferred to the statement-x.

Fig: Flowchart of Nesting Of If…Else Statement

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Example
class biggest
{
public static void main(String args[])
{
int a=10,b=20,c=30; [Link](“Largest no. is:”); if (a>b)
{
if (a>c)
{
[Link](“a is largest no.”);
}
else
{
[Link](“c is largest no.”);
} }
else
{

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

if (c>b)
{
[Link](“c is largest no.”);
}
else
{
[Link](“b is largest no.”);
}
}
}
}

The If…Else Ladder


The general form is
if ( test expression1)
statement-block1;

else if ( test expression2) statement-block2;

else if (test expression n) statement-block-n;


else
default -statement;
statement-x;

This construct is known as the else if ladder. The test conditions are evaluated from the top, downwards.
As soon as true test-condition is found, the statement associated with it is executed and control is
transferred to the statement-x. When all test n conditions become false, then the else containing default-
statement will be executed.
Example
if (marks>79) Grade=”Honours”;
else if(marks>59)
Grade=”first class”;

else if(marks>49)
Grade=”second class”; else if(marks>39)
Grade=”third class”; else
grade=”fail”;

The Switch Statement


The general form of the switch statement is switch ( expression)

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

case value-1:

case value-2:

block-1 break;

block-1 break; __________


__________
Default:
Default-block
Break;
}
Statement-x;
The expression is an integer expression or characters. value-1, value-2----
are constants or constant expressions and are known as case labels. Each of these values should be unique
within a switch statement. block-1, block-2,are statement lists and may contain zero or more statement.
There is no need to put braces around these blocks, case labels end with a colon ( : ).

When the switch is executed, the value of expression is compared with the values value-1, value-2,...........
if a case is found then the block of statements that follows the case are executed.

The break statement at the end of each block signals the end of the particular block and control is
transferred to the statement-x.
The default is an optional case. When the value of expression not match with any of the case, the default
case will be executed. If default statement not present, no action takes place when all matches fail and the
control goes to the statement-x. (See Fig.2.5.6.a)

Fig: Flowchart of Switch statement

EXAMPLE:

Index=marks/10;

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Switch (index)
{
Case 10:
Case 9:
Case 8:
Grade=”honours”;
Break;
Case 7:
Case 6:
Grade=”first class”;
Break;
Case 5:
Grade=”second class”;
Break;
Case 4:
Grade=”third class”;
Break;
Default:
Grade= “fail”;
Break;
}
DECISION MAKING WITH LOOPING
Introduction
The process of repeatedly executing a block of statements is known as looping. The statements in block
may be executed any number of times, from zero to infinite number is called an infinite loop. The program
loop consists of two segments are
Body of the loop
Control statement (tests certain conditions and then directs the repeated execution of the statements in the
body of the loop)
A Control structure may be classified either into two types are
Entry-controlled loop: The control conditions are tested before the start of the loop execution. If conditions
are not satisfied, the body of the loop will not be executed.
Exit-controlled loop: The test is performed at the end of the body of the loop and therefore body is
executed unconditionally for the first time.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

A looping process will follow four steps:


Setting and initialization of a counter.
Execution of the statements in the loop.
Test for a specified condition for execution of the loop.
Incrementing the counter.

They are three types looping construct are:


while construct
do construct
for construct

The While Statement


The general form is
Initialization;
while ( test condition )

{
Body of the loop
}
The while is an entry-controlled loop statement. The test condition is evaluated and if the condition is true,
then the body of the loop is executed. After execution of the body, the test condition is once again
evaluated and if it is true, the body is executed once again. These processes of repeated execution of the
body continue until the test condition finally becomes false and the control is transferred out of the loop.
On exit, the program continues with the statement immediately after the body of the loop.
Example
class total
{
public static void main(String args[])
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

{
int sum,n; sum=0; n=1;
while (n<=5)
{
sum=sum+n; n++;
}
[Link]("sum="+sum);
}
}
O/P is:sum= 15

The Do Statement
The general form is
Initialization; do
{

Body of the loop


}
while ( test condition );
The do-while is an exit-controlled loop statement. On do statement, the body of the loop will be executed
first. At the end of the loop, the test condition in the while statement is evaluated. If condition it true, the
program proceed to continues to evaluate the body of the loop once again. This process continues as long
as condition is true. When the condition becomes false, the loop will be terminated and control goes to
statement after the while statement.
class total
{
public static void main(String args[])
{
int sum,n; sum=0; n=1;
do
{
sum=sum+n; n++;
}
while(n<=5); [Link](“sum=”+sum);
}
}

O/P is : sum=15.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

The For Statement


The for loop is an entry-controlled loop. The general form is for (initialization ; test condition ; increment)
{
Body of the loop
}
The execution of the for statement is as
Initialization of the control variables is done using assignment statements.
The value of the control variable is tested using the test condition.
When the body of the loop is executed, the control is transferred back to the for statement after evaluating
the last statement in the loop. Now, the control variable is incremented using an assignment statement.
Additional features of for loop
The for loop has several capabilities that are not found in other loop constructs. For example more than
one variable can be initialized at a time in the for statement.

p = 1;
for (n = 0 ; n<17; ++n) can be rewritten as
for (p =1, n = 0 ; n<17; ++n)
Increment section may also have more than one part. For example
for (n = 0, m = 50 ; n<17; ++n, --m)
The test condition may have any compound relation and testing need not be limited only to the control
variable.
Example class total
{
public void static void main(String args[])
{
int sum,i;
sum=0; i=1;
for(i=1;i<=5;i++)
{
sum=sum+i;
}
[Link](“sum=”+sum);
}
}
o/p is :sum=15.

Nesting of for loops

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Nesting of loops, that is one for statement within another for statement, is allowed in java

.For example

Jump In Loops
Java permits a jump from one statement to the end or beginning of a loop as well as jump out of a loop.

Jumping Out of a Loop


An early exit from a loop can be accomplished by using break statement.
The general form is
break [label] ;
The break statement can be used within while, do, for loops. When the break statement is encountered
inside a loop, the loop is immediately exited. When the loops are nested, the break would exit from
containing it.
Example
import [Link].*; class break
{
public static void main(String args[]) throws IOException
{
DataInputStreamdis=newDataInputStream([Link]); [Link]("Enter positive numbers for
summation");

int x,i=1,n=5,sum=0;
while(i<=n)
{
x=[Link]([Link]()); if (x<0)
break; sum=sum+x; i++;
}
[Link]("sum is"+sum);
}
}
O/P is: C:\jdk1.4\bin>java brea

Enter positive numbers for summation 10


20
30
-40
sum is 60

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

BREAK:
The Java break statement is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop. We can use Java break
statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
Jump-statement;
break;

Flowchart of Break Statement

Example:

[Link]

//Java Program to demonstrate the use of break statement


//inside the for loop.
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
[Link](i);
}
}
}

Output:

1
2
3
4

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

LABELLED LOOP:

A label is a valid variable name that denotes the name of the loop to where the control of execution should
jump. To label a loop, place the label before the loop with a colon at the end. Therefore, a loop with the
label is called a labelled loop.

In layman terms, we can say that label is nothing but to provide a name to a loop. It is a good habit to
label a loop when using a nested loop. We can also use labels with continue and break statements.

There are three types of loop in Java:

for loop
while loop

Let's discuss the above three loops with labels.

for Loop
Labeling a for loop is useful when we want to break or continue a specific for loop according to
requirement. If we put a break statement inside an inner for loop, the compiler will jump out from the
inner loop and continue with the outer loop again.

What if we need to jump out from the outer loop using the break statement given inside the inner loop?
The answer is, we should define the label along with the colon(:) sign before the loop.

Syntax:

labelname:
for(initialization; condition; incr/decr)
{
//functionality of the loop
}

[Link]

public class LabeledForLoop


{
public static void main(String args[])
{
int i, j;
//outer loop
outer: //label
for(i=1;i<=5;i++)
{
[Link]();
//inner loop
inner: //label
for(j=1;j<=10;j++)
{
[Link](j + " ");
if(j==9)
break inner;
}
}
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

}
}

Output:

123456789

123456789

123456789

123456789

123456789

Java Labelled while Loop


Syntax:

labelName:
while ( ... )
{
//statements to execute
}

[Link]

public class LabledWhileLoop


{
public static void main(String args[])
{
int i = 0;
whilelabel:
while (i < 5)
{
[Link]("outer value of i= " + i);
i++;
forlabel:
for (int j = 0; j < 5; j++)
{
if (j > 0)
{
//execution transfer to the for loop
continue forlabel;
} //end of if
if (i > 1)
{
//execution transfer to the while loop
continue whilelabel;
} //end of if
[Link]("inner value of i= " + i + ", j= " + j);
} //end of for

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

} //end of while
} //end of main
}

Output:

Outer value of I=0


Inner value of I=1, j=0
Outer value of I=1
Outer value of I=2
Outer value of I=3
Outer value of I=4

Example:
loop1: for (int i=0;i<=10; i++)
{
loop2: while(x<100)
{
Y = i*x;
if(y>500)
break loop1;
}}

CONTINUE STATEMENTS:
The continue statement is used in loop control structure when you need to jump to the next iteration of
the loop immediately. It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It continues the current flow of the program and
skips the remaining code at the specified condition. In case of an inner loop, it continues the inner loop
only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
Example:
public class Continue Example
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
continue;
}

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link] (i);
}
}
}

ARRAYS
∙ An array is a group of contiguous or related data items that share a common name.
∙ A particular value is indicated by writing a number called index number or subscript in brackets
after the array name.
∙ Example: salary [10], It represent the salary of the 10th employee.
∙ Two types of Arrays are available
(i) One-Dimensional Array
(ii) Multi-Dimensional Array

One Dimensional Array


∙ A list of items can be given one variable name using only one subscript and such a
variable is called a single-subscripted variable or one-dimensional array.
Example: int number[]=new int[5];
∙ Java subscripts start with the value 0.

∙ The values to the array elements can be assigned as follows:


number[0]=20;
number[1]=30;
number[2]=40;
number[3]=50;
number[4]=60;

Creating An Array
∙ Creation of an array involves three steps.
Declare the array.
Create memory locations.
Put values into the memory location.

Declaration of Arrays
∙ Arrays in java can be declared in two forms.
Form1: type array_name[];
Form2: type[] array_name;
Example: int number[]; float[] marks;
Creation of Arrays

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

∙ After declaring an array, we need to create it in the memory.


array_name=new type[size];
Example: number =new int[5];
Initialization of Arrays:
∙ The final step is put values into the array created. This process is known as initialization.
Syntax: arrayname[subscript]=value;
Example: a[0]=25; number[4]=30;
∙ We can also initialize arrays automatically in the same way as the ordinary variables when
They are declared.
Syntax: type arrayname[]={list of values};
Example: int number[]={20,40,50,60};

Array length:
∙ The length of the array can be determined using length.
e.g., int num[]=new int[5]; int size=[Link];
//size=5
Two Dimensional Arrays
∙ In java, a table of items can be defined using two dimensional arrays.
∙ We can create a two-dimensional array as int myarray[][]; myarray=new int[3][4];
(Or) int myarray[][]=new int[3][4];
∙ This will create a table that can store 12 integer values, four across and three down.
∙ The value can be initialized by following their declaration with a list of initial values
enclosed in braces.
E.g., int table[2][3]={0,0,0,1,1,1};
(OR)
int table[][]={ {1, 2, 3}, {9, 8, 7} };
It initializes the element of the first row to zero and second row to one.
The initialization is done row by row.

Variable size arrays


∙ Java treats multidimensional array as “arrays of arrays”.
∙ It is possible to declare a two-dimensional array as follows:
int x[][]=new int[3][];
x[0]=new int[2];
x[1]=new int[4];
x[2]=new int[3];
∙ These statements create a two-dimensional array as having different lengths for each row.
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

VECTORS
For achieving the concepts of variable arguments to methods in Java through the use of the Vector
class contained in the [Link] package. This class can be used to create a generic dynamic array
known as vector that can hold objects of any type and any number. Vector are created like arrays
as

Vector intVect = new Vector( ); // declaring without size Vector list = new Vector( ); // declaring
with size
Vectors possess a number of advantages over arrays.
It is convenient to use vectors to store objects.
A vector can be used to store a list of objects that may vary in size.
We can add and delete objects from the list as and when required. A major condition in using
vectors is that we cannot directly store simple data type in a vector; we can only store objects.
Therefore, we need to convert simple type to objects by using wrapper classes. The vector class
supports a number of methods that can be used to manipulate the vectors created as listed in
Table3.5.5 a.

Table 3.5.5 a. Commonly Used Vector Methods

Method Call Task performed


[Link] (item) Adds the item specified to the list at the end
[Link] (10) Gives the name of the 10th object
List. Size( ) Gives the number of the object present
[Link] (item) Removes the specified item from list
[Link](n) Removes the item from in the nth position of
the list
[Link] ( ) Removes all the elements in the list [Link]
(array) Copies all items from list to array
[Link] (item, n) Inserts the item at nth position

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Example
import [Link].*; import [Link].*; class vect
{
public static void main(String args[]) throws IOException
{
Vector v=new Vector(); [Link]("cat"); [Link]("rat"); [Link]("snake");
[Link]("Goat"); [Link]("dog"); int len=[Link]();
String s[]=new String [len]; [Link](s); [Link]("Result is:"); for(int
i=0;i<len;i++)
{
[Link](s[i]);
}
}
}
Result is: catrat snake Goat dog

Array list
Java Array List class uses a dynamic array for storing the elements. It is like an array, but there is no size
limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It
is found in the [Link] package. It is like the Vector in C++.

The Array List in Java can have the duplicate elements also. It implements the List interface so we can
use all the methods of the List interface here. The Array List maintains the insertion order internally.

It inherits the Abstract List class and implements List interface.

Illustration:

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Advantages of array list over array:

Array and Array List are most used data types while developing any java applications. Both are used to store group of
objects. In this post I have tried to list down the advantages of using Array List over Arrays. Before discussing the
advantages of Array List, let’s see what the drawbacks of arrays are.

Arrays are of fixed length. You cannot change the size of the arrays once they are created.
You cannot accommodate an extra element in an array after they are created.
Memory is allocated to an array during its creation only, much before the actual elements are added to it.
Because of these drawbacks, use of arrays are less preferred. Instead of arrays, you can use Array List class which
addresses all these drawbacks. Here are some advantages of using Array List over arrays.

1) You can define Array List as re-sizable array. Size of the Array List is not fixed. Array List can grow and shrink
dynamically.

2) Elements can be inserted at or deleted from a particular position.

3) Array List class has many methods to manipulate the stored objects.

Array List class has methods to perform solo modifications ( add(), remove()… ), bulk modifications ( add All(),
remove All(), retain All()… ), searching( index Of(), last Index Of() ) and iterations( iterator() ).

4) If generics are not used, Array List can hold any type of objects.
5) Many are of the assumption that multiple insertion and removal operations on Array List will decrease the
performance of an application. But, there will be no significant change in the performance of an application if you use
Array List instead of arrays. Below example shows time taken to add 1000 string elements to Array List and array.

6) You can traverse an Array List in both the directions – forward and backward using List Iterator.
7) Array List can hold multiple null elements.

8) Array List can hold duplicate elements.

WRAPPER CLASSES
Vectors cannot handle primitive data type like int, float, long, char, and double. Primitive data
types may be converted into object by using the wrapper classes contained in the [Link]
package are listed in the following tables.
Table Wrapper Classes for Converting Simple Types
Simple type Wrapper Class
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
Table Converting Primitive Numbers to Object Numbers Using Constructor Methods
Constructor Calling Conversion Action
Integer IntVal = new Integer (i); Primitive integer to Integer
object

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Float FloatVal = new Float(f); Primitive float to Float object


Double DoubleVal = new Double(d); Primitive double to Double object Long LongVal = new
Long(l); Primitive long to Long object
Note: i, f, d and l are primitive data values denoting int, float, double and long data types. They
may constant or variables.
Table Converting Object Numbers to Primitive Numbers Using typeValue( ) Methods
Method Calling Conversion Action
int i = [Link]( ) Object to primitive integer float f =
[Link]( ) Object to primitive float double d = [Link]( ) Object
to primitive double long l = [Link]( ) Object to primitive long
Table Converting Numbers to String Using String( ) Methods

Method Calling Conversion Action


Str = [Link](i) Primitive integer to string
Str = [Link](f) Primitive float to string
Str = [Link](d) Primitive double to string
Str = [Link](l) Primitive long to string

Table Converting String Object to Numeric objects Using the Static Method ValueOf()
Method Calling Conversion Action
IntValue = [Link](str) Converts string to integer
object
FloatVal = Float..ValueOf(str) Converts string to float object
DoubleVal = [Link](str) Converts string to double
object
LongVal = [Link](str) Converts string to long object

Table Converting Numeric Strings to Primitive Numbers Using Parsing Methods


Method Calling Conversion Action
int i = [Link](str) Converts string to primitive integer long l
= [Link](str) Converts string to primitive long

Note: parseInt() and parseLong() methods throws a NumberFormatException if the value of the
str does not represent an integer.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

UNIT – III

Class and objects: Defining a class – Methods – Creating objects – accessing class members –
Constructors – Method overloading – Static members –Nesting of Methods – this keyword –
Command line input. Inheritance: Defining inheritance –types of inheritance– Overriding
methods – Final variables and methods – Final classes – Final methods -Abstract methods and
classes – Visibility Control- Interfaces: Defining interface – Extending interface - Implementing
Interface - Accessing interface variables. Strings: String Array String Methods – String Buffer
Class

CLASSES, OBJECTS AND METHODS


Introduction
Java is true object-oriented language and therefore the underlying structure
of all java program is classes. Class defines the state and behavior of the basic
program components known as objects. Classes create objects and objects use
methods to communicate between them.

Defining a Class
A class is a user-defined data type with a template that serves to define its
properties. Once the class type has been defined, we can create variables of that
type using declarations. In java these variables are called as instances of classes,
which are the actual objects.
The general form of a class definition is:
Class class name [extends superclass name]
{
[Fields declaration;]
[Methods declaration;]
}
Inside the square brackets is optional. For example
Class empty
{}
Because the body is empty, this class does not contain any properties and
cannot do anything. Class name and superclass name are any valid identifier.
The keyword extends indicates that the properties of the superclass name class
are executed to the class name class (is known as inheritance).

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Field declaration
By placing data fields inside the body of the class definition are called
instance variables because they are created whenever an object of the class is
instantiated.
Example:
class Sample
{
int a, b;
}
The class Sample contains two integer type instance variables (are also
called as member variables)
Methods Declaration
A class with only data fields has no life. Methods are declared inside the
body of the class but immediately after the declaration of instance variables. The
general form of a method declaration is
type methodname (parameter-list)
{
method-body;
}
Method declarations have four basic parts:
 The name of the method (methodname) is a valid identifier.
 The type of the value the method returns (type). This could be simple data
type such as int as well as any type. It could even be void type, if the
method does not return any value.
 A list of parameters (parameter-list) is always enclosed in parentheses.
This list contains variable names and types of all values we want to give to
the method as input.
Example:
(int m, float a, float b) // Three parameters
( ) //Empty list

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

 The body of the method actually describes the operations to be performed


on the data.

Example:
class Rectangle
{
int length;
int width;
void getData(int x,int y)
{
length=x;
width=y;
}
}
Here getData method which performs operations on the data such as
length & width data members.

Creating Objects
Creating an object is also referred to as instantiating an object. Object in
Java created using new operators. The new operator creates an object of the
specified class and returns a reference to that object. Here is an example of
creating an object of type Rectangle.
Rectangle rect1; //declare
rect1=new Rectangle ();
//instantiate
Accessing Class Members
In an outside the class, we cannot access the instance variables and the
methods directly. For this, we must use the concerned object and dot operator as
[Link] = value;
[Link] (parameter-list);
Where object name - is the name of the object
Variable name - is the name of the instance variable inside object that we

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

wish to access
Method name - is the method that we wish to call
Parameter-list - is a comma separated list of ‘actual values” that must
match in type and number with the parameter list of the
method name declared in the class.

Example
Class Rectangle
{
int l,w;
void get(int x,int y)
{
l=x;
w=y;
}
int rectarea()
{
int area=l*w;
return(area);
}
public static void main(String args[])
{
Rectangle r=new Rectangle();
[Link](15,10);
int result=[Link]();

}
O/P is:
[Link](“Area of Rectangle is”+result);
}
C:\jdk1.4\bin>java Rectangle
Area of Rectangle is150

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

CONSTRUCTORS
Java supports a special type of method is called a constructor,that enables an
object to initialize itself when it is created.
Rules for forming the constructors are
 Constructors have the same name as the class.
 They do not specify a return type, not even void. This is because they
return the instance of the class itself.

Example
class Rectangle
{
__________
__________
}

O/P is:
intl,w;Rectangle(intx,inty)
{
l=x;w=y;
}
int rectarea()
{
int area=l*w;
return(area);
}
public static void main(String args[])
{
Rectangle r=new Rectangle(15,10);int
result=[Link]();
[Link](“Area of Rectangle is”+result);
}
C:\jdk1.4\bin>java Rectangle

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Area of Rectangle is150

METHODS OVERLOADING
In Java, it is possible to create methods that have same name, but different
parameter lists and different definitions is called method overloading. When we
call a method in an object, java matches up the method name first and then the
number and type of parameters to decide which one of the definitions to execute
is known as polymorphism.

class Rectangle
{
int l,w;
void get()
{
l=20;
w=12;
}
void get(int x,int y)
{
l=x;
w=y;
}
int rectarea()
{
int area=l*w;
return(area);
}
public static void main(String args[])
{

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Rectangle r=new Rectangle();


[Link]();
int result1=[Link]();
[Link](“Area of first Rectangle is”+result1);
[Link](15,10);
int result=[Link]();
[Link](“Area of second Rectangle is”+result);
}
}
O/P is:
C:\jdk1.4\bin>java Rectangle
Area of first Rectangle is240
Area of second Rectangle is150

STATIC MEMBERS
We want to define a member that is common to all the objects accessed
without using a particular object. That is, the member belongs to the class as a
whole rather than the objects created from the class. Such members can be
defined as
static int count;
static int mix(int x, int y);
The members are declared as static are called as static members. The
static variables and static methods are often referred to as class variable and class
methods.
Static methods have several restrictions:
 They can only call other static methods
 They can only access static data.
 They cannot refer to this or super in any way

Example
class mathod
{
static float mul(float x,float y)

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

{
return(x*y);
}
static float divide(float x,float y)

{
return(x/y);
}
}
class mathmain
{
public static void main(String args[])
{
float a=[Link](4.0f,5.0f);
float b=[Link](4.5f,2.2f);
[Link]("a="+a);

[Link]("b="+b);
}
}

O/P is:
C:\jdk1.4\bin>java mathmain
a=20.0
b=2.0454545

NESTING OF METHODS

A method can be called by using only its name in another method of the
same class is known as nesting of methods.

Example
class nesting

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

{
int a,b;
nesting()
{
a=10;
b=20;

}
int large()
{
if(a>b)
{
return(a);
}
else
{
return(b);
}
}
void display()
{
int big=large();
[Link](“The biggest no. is”+big);
}
public static void main(String args[])
{
nesting n=new nesting();
[Link]();
}
}
O/P is: The biggest no. is20

INHERITANCE:

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Extending a Class
The mechanism of deriving a new class (subclass or derived class or child
class) from an old class (base or super or parent class) is called inheritance.

Syntax:

class Subclass-name extends Superclass-name


{
//methods and fields
}

The inheritance allows subclasses to inherit all the variables and methods
of their parent classes.
Inheritance may take different forms:
 Single inheritance (only one super class)
 Multiple inheritance (several super classes)
 Hierarchical inheritance (one super class, many subclasses)
 Multilevel inheritance (derived from derived class)
These form inheritance are shown in Fig.3.4.1.a. Java does not directly
implement multiple inheritance. However, this concept is implemented using a
secondary inheritance path in the form of interfaces.

Example:

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}

Output:
Programmer salary is: 40000.0

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Bonus of programmer is: 10000

Fig.3.4.1.a
Forms of Inheritance

Single
inheritance:
When a class
inherits another class,
it is known as a single inheritance.
Example:
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}
Output:
Barking….
Eating……

Multilevel inheritance:
When there is a chain of inheritance, it is known as multilevel inheritance.

Example:

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}
Output:
Weeping….
Barking…..
Eating…..
Hierarchical inheritance:
When two or more classes inherits a single class, it is known as hierarchical
inheritance.

Example:
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

//[Link]();//[Link]
}}
Output:
Meowing….
Eating……

Multiple inheritance:
In multiple inheritance, a single subclass extends from multiple superclasses.

Example:
class A{
void msg(){[Link]("Hello");}
}
class B{
void msg(){[Link]("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
[Link]();//Now which msg() method would be invoked?
}
}

Output:
Compile time error
Hybrid inheritance:

Hybrid inheritance is a combination of two or more types of inheritance.

Example:
Class c
{
Public void disp ()
{
[Link](“c”);
}
}

Class A extends C
{
Public void disp ()
{

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link](“A”);
}
}

Class B extends C
{
Public void disp ()
{
[Link](“B”);
}
}

Class D extends A
{
Public void disp ()
{
[Link](“D”);
}
Public static void main(string args[])
{
D obj =new D ();
[Link] ();
}
}

Output:
D
OVERRIDING METHODS
We want an object to respond to the same method but have different
behavior when that method is called. That means, we should override the method
defined in the superclass. This is possible by defining a method in the subclass
that has the same name, same arguments and same return type as a method in the
superclass. Then, when that method called, the method defined in the subclass is
invoked and executed instead of the one in the superclass. This is known as
overriding.
Example
class parentoverride
{
public void show()
{
[Link]("show method in Base class");

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

public void display()


{
[Link]("display method in Base class");
}
}

class childoverride extends parentoverride


{
public void show()

changed. Final variables, behave like class variables and they do not take any
space on individual objects of the class.

FINAL CLASSES
A class that cannot be sub-classed is called a final class. Declaring a class
final prevents any unwanted extensions to the class.

Examples:
final class Aclass { --------- }
final class Bclass extends Someclass { ---------- }
Any attempt to inherit these classes will cause an error.
FINALIZER METHODS
In Java run-time is an automatic garbage collecting system. It
automatically free ups the memory resources used by the objects. But object may
hold other non-object resources such a file descriptors or window system fonts.
The garbage collector cannot free these resources. In order to free these resources
we must use a finalize() method and it can be added to any class.
ABSTRACT METHODS AND CLASSES
Abstract method is a method that must always be redefined in a subclass,
thus making overriding compulsory. This is done by using the modifier keyword
abstract in the method definition.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Example:
abstract class shape
{
abstract void draw( );
}
When a class contains one or more abstract methods, it should also
declared abstract as in the example.
While using abstract classes, we must satisfy the following conditions:

 We cannot use abstract classes to instantiate objects directly.


 The abstract methods of an abstract class must be defined in its subclass.
 We cannot declare abstract constructors or abstract static methods.

VISIBILITY CONTROL
In inheritance inherit all the members of a class by a subclass using the
keyword extends. The variables and methods of class are visible everywhere in
the program we want to restrict the access to certain variables and methods from
outside the class. We can achieve this in Java by visibility modifiers or access
modifiers to the instance variables and methods. Java provides three types
modifiers: public, private and protected. Table 3.4.7.a shows the visibility
provided by various modifiers.
Table 3.4.7.a Visibility of Field in a Class
Access
Modifier
Access Public Protected Friendly Private Private
location (default) protected

Same class Yes Yes Yes Yes Yes

Subclass in
Yes Yes Yes Yes No
same package
Other classes
in same Yes Yes Yes No No
package

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Subclass in
Yes Yes No Yes No
other package
Non-Subclass
in other Yes No No No No
package

INTERFACE:
Introduction
Classes in Java cannot have more than one superclass. For instance a
definition like
class A extends B extends C
{

}
is not permitted in Java. Java provides alternate approaches known as interfaces
to support the concept of multiple inheritance. Although a Java class cannot be a
subclass of more than one superclass, it can implement more than one interface.

Defining Interfaces
The general form of an interface definition is:
interface interfaceName
{
variable declaration;
methods declaration;
}
Where interface – is the keyword
interfaceName – is any valid Java variable
Variables are declared as
Static final type VariableName = Value;
Methods declaration will contain only a list of methods without any body
statements.
Example:
return-type methodName1( parameter_list);

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

interface sports
{
static final int sptmark=70;
void display();
}
Extending Interfaces
Like classes, interface can also extend. The new interface will inherit all
the members of the superinterface. The general form of an interface is
interface name2 extends name1
{
body of name2
}
Example
interface student extends sports
{
static final int cobol=50;
static final int dbms=60;
void display2();
}

Implementing Interfaces
Interfaces are used as “superclasses whose properties are inherited by
classes. It is therefore necessary to create a class that inherits the given interface.
The general form is
class classname implements interfacename
{
body of classname
}
Here the class classname “implements” the interface interfacename. The
more general form is
class classname extends superclass
implements interfacename1,interfacename1, ………
{

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

body of classname
}

Here the class can extend another class while implementing interfaces.
When more than one interface, they are separated by a comma. The
implementation of interfaces can take various forms as shown in Fig. 3.6.4.a.

Interface A Class A D Interface

Implementation Extension Extension


Class B Class B E Interface
Implementation
Extension Extension
Class C
Class C

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Example
class student
{
int regno; String name;
public void get(int r,String n)
{
regno=r;name=n;

}
public void display1()
{
[Link]("Register no.:"+regno);[Link]("Name .:"+name);
}
}
interface mark
{
static final int cobol=70;static final int sport=60;public void display2();
}
class multiple extends student implements mark
{
int total;
public void display2()
{
total=cobol+sport; [Link]("cobol mark is:"+cobol);
[Link]("sport mark is:"+sport); [Link]("Total is:"+total);
}
public static void main(String args[])
{
multiple m=new multiple();[Link](100,"kumar"); m.display1();
m.display2();
}

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

O/P is:
Register no.:100 Name .:kumarcobol mark is:70 sport mark is:60 Total is:130

Accessing Interface Variables


Interfaces can be used to declare a set of constants that can be used in
different classes. Interfaces do not contains methods; there is no need to worry
about implementing any methods. The constant values will be available to any class
that implements the interface.
STRINGS:

The strings represents a sequence of a character in java by using a character


array.
Example:
char chararray[ ] = new char[3];chararray[ ] = ‘H’;

chararray[ ] = ‘a’;
chararray[ ] = ‘i’;
In Java strings are class objects and implanted using two classes, namely
String and StringBuffer. A Java string is an instantiated object of the String class.
Strings may be declared and created as
String stringName;
stringName = new String(“string”);
Example:

String firstName;
firstName = new String (“Harshinni”);
Like arrays, it is possible to get the length of string using the lengthmethod
of the string class.
int m = [Link]( );
Java string can be concatenated using + operator.
Example:
String fullName = name1 + name2; // name1 and name2
containingstring constants

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

String city = “New” + “Delhi”;


[Link](firstName+”Sundar”);
String Arrays
We can also create and use arrays that contain strings. The statement String itemarray[ ] =
new String[2];// create string array with 3 string constants

We can assign the strings to the itemarray element by element using 3


different statements or using for loop.
String Methods
The String class defines a number of methods that allow us to accomplish a
variety of string manipulation tasks as shown in Table 3.4.1. String class creates
strings of fixed length.

Table 3.4.1 Commonly Used String Methods

Method Call Task performed


s2 =[Link]; Converts the string s1 to all lowercase s2
=[Link]; Converts the string s1 to all uppercase s2
=[Link](‘x’ , ‘y’); Replace all occurrences of x with y
s2 =[Link]( ); Remove white spaces at the beginning and end
of the string s1
[Link](s2) Return ‘true’ if s1 is equal to s2
[Link](s2) Return ‘true’ if s1 = s2, ignoring the case of
characters
[Link]( ) Gives the length of s1
[Link]( ) Gives nth character of s1
[Link](s2) Return negative if s1<s2, positive if s1>s2 or
zero if s1=s2
[Link](s2) Concatenates s1 and s2
[Link](n) Gives substring starting from nth character
[Link](n, m) Gives substring starting from nth character up
to mth [Link](p) Creates a string object of the parameter p
[Link]( ) Creates a string representation object p

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link](‘x’) Gives the position of the first occurrence of ‘x’


in the string s1
[Link](‘x’) Gives the position of ‘x’ that occurs after nth
position in string s1
[Link](Variable) Convert the parameter value to string
representation

Example
class strin
{
public static void main(String args[])
{
String s1,s2,s3; s1="computer";

s2=[Link]();
[Link]("convert lowercase to uppercase letters "+s2);
s1="COMPUTER";
s2=[Link]();
[Link]("convert uppercase to lowercase letters "+s2);s1="computer";
int length=[Link]();
[Link]("Length of string constant in s1 object is "+length);
s1="computer";
s2=" science"; s3=[Link](s2);
[Link]("concatenation of two strings is "+s3);char c=[Link](2);
[Link]("Extract character from s2 object is "+c);if ([Link](s2))
{
[Link]("two strins are equals");
}
else
{
[Link]("two strings are not equals");
}

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

}
}
O/P is:
C:\jdk1.4\bin>java strin
convert lowercase to uppercase letters COMPUTER convert uppercase to lowercase
letters computer Length of string constant in s1 object is 8 concatenation of two
strings iscomputer science Extract character from s2 object is c two strings are not
equals

StringBuffer Class
StringBuffer creates strings of flexible length that can be modified both
length and content. We can insert characters and substring in the middle of a string,
or append another string to the end. Table 3.4.2 lists some of the methods that are
used in string manipulations.
Table 3.4.2 Commonly Used StringBuffer Methods
Method Call Task performed
[Link](n, ’x’) Modifies the nth character to x [Link](s2)
Appends the string s2 to s1 at the end
[Link](n, s2) Inserts the string s2 at the position n of the
string [Link](n) Sets the length of the string s1 to n. If n <
[Link]() s1 is [Link] n>[Link] ( ) zeros are added tos1.
class strbuf
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer("computer"); StringBuffer s2=new
StringBuffer(" department");[Link](s2);
[Link](s1);[Link](3,'u'); [Link](s2);
[Link](9,"science ");[Link](s1);
}
}
O/P is: C:\jdk1.4\bin>java strbufcomputer department deuartment

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

UNIT – IV
Packages: Java API Packages – System Packages – Naming Conventions –Creating &
Accessing a Package – Adding-Class to a Package – Hiding Classes. Exception
Handling: Limitations of Error handling – Advantages of Exception Handling - Types of
Errors – Basics of Exception Handling – try blocks – throwing an exception – catching an
exception –Finally statement. Multithreading: Creating Threads – Life of a Thread –
Defining & Running-Thread – Thread Methods – Thread Priority – Synchronization –
Implementing Runnable interface – Thread Scheduling.

PACKAGES:

To use the classes and or interfaces from another program without physically
copying them into the program is done by Java package. Actually, packages are the group
of classes and interfaces. The grouping is done according to functionality. Packages are
containers for the classes.

Java package can be classified into two types are


 System packages or API (Application Program Interface) packages.
 User-Defined packages.
Benefits of packages:
 Packages are used to organize to classes into smaller units and make it easy to locate

and use the appropriate file.

 The classes contained in the packages of other programs can be easily reused.

 It is possible to create classes with the same name in different packages. Thus, it

avoids naming conflicts.

 Packages hide their classes from other programs and other packages.

 Packages are used to protect the classes, data and methods in a larger way than on a

class-to-class basis.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Java API Packages


Java API contains a large number of classes grouped into different packages according
to their functionality. The various API packages and their description are shown in the Table
4.3.1.

Table [Link] system packages

Package name Description

It contains the classes that support language. This package is the default package and they are
automatically imported. It includes classes of primitive data types, strings, threads and
exceptions, main functions.
This package consists of classes that are used forinput and output operations.
This package consists of utility classes such as vectors, random numbers, date etc.,
This package is useful to create GUI (Graphical User Interface) applications.
This package consists of classes for creating, implementing and executing applets.
[Link] This package contains classes for networking.

Using System Packages

The System packages are organized in a hierarchical manner as shown in fig

The main package in the Java is “java”. This “java” packages contains several packages.

Again it in turn contains packages and classes.

Example:

[Link].*;

Fig.4.3.1. Hierarchical Structure of [Link].*.

java

lang awt

Math Package containing lang package

. Package containing classes containing


String
.

Excepti
on

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Classes are stored in the package can be accessed in two ways.

 By specifying the full path of the required class.

This is done by using the package name containing the class and then appending the
class name to it using dot (.) operator.
Examples:
[Link] [Link]
 By using import keyword.

 This statement must appear at the top of the program, before any class declaration.
This is used to use a same class in number of places in the program or to use number of
classes contained in the package.

The general form is:


Import [Link];

Import package name.*;

Examples:
[Link];
[Link];

Naming Conventions

Packages can be named using the standard java naming rules. The rules may be followed
(not a compulsory) while naming the packages are

 The first letter of the packages name should be a lowercase letters. It is used to
distinguish a class name from the package name. Usually, class name begins with uppercase
letter.
Example:
[Link](a,b);

package name method nameclass name

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

 Every package name should be unique. In some case, giving the same name to
different packages is unavoidable. In this, case domain name is added with the package name.

Example:
[Link] [Link]

Creating Packages
The general form for creating user-defined package is package packagename; // package
declarationpublic class Classname // class definition
{
----------------- // body of the class

}
where
package , public & class - are the keywords
package name & class name - are the any valid user-defined package name &class name
The steps are used in the creation of a package are

 Declare the package at the beginning of a program by using the form


package packagename;
 Define the class that is to be put in the package and declare it public.

 Create a subdirectory under the main directory by using the DOScommand as


maindirectory > md subdirectory

Where
md- is a make directory (DOS command) used to create directory subdirectory-
is the name of the directory, which is same as package name.

 Save the program as the [Link] file in the subdirectory created.


 Compile the program by using javac. This creates [Link] file in the
subdirectory.

Accessing a Packages
The import statement is used to access a particular class in a package or all classes in a
[Link] general forms is
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

import package1 [.package2][.package3].Classname ;


or
import packagename.*;

where
import – is the keyword is used to import classes from package. package1,
package2, package3 & Classname- are the any valid user- defined
package name &
class name.

“ * “-All the classes contained in a particular package can be accessed


by
using“ * “in the import statement .

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Adding Class to a Package


It is very simple and easy to add a new class to an existing package. The following
steps are used for adding a new class to an existing package.
 Place the package statement before the class definition like
package existingpackagename;

 Define the new class and make it as public.


 Save the above program as the [Link] file in the subdirectory
created.
 Compile the program by using javac. This creates [Link] file in the
subdirectory.
Now, the package will contain new class also. The statement import
packagename.* will import all the classes.

Example

// package1 package package1;public class add


{
public void sum()
{
int a=10; int b=20;int c=a+b;
[Link]("Sum of two nos. is"+c);
}
}

//package2 package package2;public class sub


{
public void subtraction()
{
int a=10; int b=20;int c=a-b;
[Link]("Subtraction of two nos. is"+c);

}
}

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

//mainpackage import package1.*;import package2.*;class packmain


{
public static void main(String args[])
{
add obj1=new add();sub obj2=new sub();[Link](); [Link]();
}
}
O/P is:
Sum of two nos is:30 Subtraction of two nos is:-10

Hiding Classes
It is possible to hide some of classes from outside of the packages by declaring the
classes as “not public“. The classes declaring as “not public“ can be used only in the same
package, not possible to access the outside of the packages is called as Hiding classes.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Exceptions
An exception is a condition that is caused by a run-time error in the program. When the java
interpreter encounters an error such as dividing an integer by zero, it creates an exception object
and throws it. If the exception object is not caught and handled properly, the interpreter will
display an error message and will stop the program execution. If you want to the program to
continue with execution of the remaining code then we try to catch the exception object thrown by
the error condition and then display an appropriate message for taking corrective actions. This task
is known as exception handling. Some common exceptions listed out in the Table 4.3.3.a. The
following tasks are usedto handling the errors.
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective action (Handle the exception) The error handling code
basically consists of two segments.
 To detect errors and to throw exceptions
 To catch exception and to take appropriate actions.

Exceptions Type in Table 4.3.3.a

Exception Type Cause of Exception


ArithmeticException Caused by math errors such as division by zero
ArrayIndexOutOfBoundsException Caused by bad array indexes

ArrayStoreException Caused when a program tries to store the wrong


type of data in as array

FileNotFoundException Caused by an attempt to access a nonexistent


file
IOException Caused by general IO failures

NullPointerException Caused by referencing a null object


NumberFormatException Caused when a conversion between strings and
number fails.

OutOfMemoryException Caused when there’s not enough memory to


allocate a new object
SecurityException Caused when an applet tries to perform an

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

action not allowed by the browser’s security


setting
StackOverFlowException Caused when the system runs out of stack
space
StringIndexOutOfBoundsException Caused when a program attempts to access a
nonexistent character position in a string

Types Of Errors
Errors may be classified into two types.
 Compile-time errors

 Run-time errors
Compile-Time Errors:
All syntax errors will be detected and displayed by Java compiler is called as compile-time
errors. Most of the compile-time errors are due to typing mistakes. Sometimes, a single error may
be the source of multiple errors. For example, use of an undeclared variable in a number of places
will cause a series of errors of type “ undefined variable”. The some common compile-time errors
are
 Missing semicolons.
 Missing (or mismatch) of the brackets in classes and methods.
 Misspelling of identifiers and keywords.
 Missing double quotes in strings.
 Use of undeclared variables
 Incompatible types in assignment / initialization
 Bad references to objects
 Use of = in place of = =operator and etc.,

Whenever the compiler displays, these kinds of error, it will not create the .class file. It is therefore
compulsory to correct all the errors before we can successfully compile and run the program.

Run-Time Errors:
A program may compile successfully creating the .class file but may not run properly. Such
programs may produce wrong results due to wrong logic or stop the program execution due to
errors like
 Dividing an integer by zero.
 Accessing an element that is out of the bounds of an array.
 Trying to store a value into array of an incompatible class or type.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

 Trying to cast an instance of a class to one of its subclasses.


 Passing a parameter that is not valid range or value for a method.
 Trying to illegally change the state of a thread.
 Converting invalid string to a number.
 Accessing a character that is out of bounds of a string And etc.,

Syntax Of Exception Handling Code;


The basic concepts of exception handling are throwing an exception and

catching it as shown in Fig.4.5.1. Java uses a keyword try to preface a block of


code that is likely to cause an error condition and “ throw “an exception. A catch
block defined by the keyword catch “catches” the exception “thrown” by the try
block and handles it appropriately. The catch block is added immediately after
the try block. The general form is

Try
{
statement; // generates an exception
}
catch ( Exception-type e)
{
statement; // processes the exception

The try block can have one or more statements that could generate an
in the block are skipped and execution jumps to the catch block that is placed next to
the try block. The catch block can have one or more statements that are necessary to
process the exception.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Throwing Our Own Exceptions for Debugging


To throw our own exception by using the keyword throw. The generalform is

Throw new Throwable_subclass;

Example;

throw new ArithmeticException(); throw new NumberformatException(); import


[Link];

Example
class myexception extends Exception
{

myexception(String message) finally


{
[Link]("I am always here");
}}}
finally
{
[Link]("I am always here");
}}}
O/p is:
caught my ExceptionNumber is too small I am always here

O/p is:
caught my ExceptionNumber is too small I am always here

finally
{
[Link]("I am always here");
}}}
O/p is:
caught my ExceptionNumber is too small I am always here

finally
{
[Link]("I am always here");
}}}
O/p is:

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

caught my ExceptionNumber is too small I am always here


Catching an exception:

You associate exception handlers with a try block by providing one or more catch blocks
directly after the try block. No code can be between the end of the try block and the beginning
of the first catch block.

try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

Each catch block is an exception handler that handles the type of exception indicated by its
argument. The argument type, ExceptionType, declares the type of exception that the handler
can handle and must be the name of a class that inherits from the Throwable class. The
handler can refer to the exception with name.

The catch block contains code that is executed if and when the exception handler is invoked.
The runtime system invokes the exception handler when the handler is the first one in the call
stack whose Exception Type matches the type of the exception thrown. The system considers
it a match if the thrown object can legally be assigned to the exception handler's argument.

The following are two exception handlers for the write List method:

try {

} catch (IndexOutOfBoundsException e) {
[Link]("IndexOutOfBoundsException: " + [Link]());
} catch (IOException e) {
[Link]("Caught IOException: " + [Link]());
}

Exception handlers can do more than just print error messages or halt the program. They can
do error recovery, prompt the user to make a decision, or propagate the error up to a higher-
level handler using chained exceptions, as described in the Chained Exceptions section.

Finally statement:

Java finally block is a block used to execute important code such as closing the connection,
etc.

Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception
occurs or not.

The finally block follows the try-catch block.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Flowchart of finally block

o finally block in Java can be used to put "cleanup" code such as closing a file, closing connection,
etc.
o The important statements to be printed can be placed in the finally block.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

MULTITHREADED PROGRAMMING:
Introduction
A thread is small unit of program that is used to perform a particular task. Thus a process
can contain multiple threads. Each thread is used to perform a specific task, which is executed
simultaneously with other threads.

class ABC
{
-------------- Beginning

-------------- Single thread body of exception

} End

Fig. Single-threaded program


Every program has at least one thread. If a program contains only one thread, it is called
single threaded program as shown in Fig. 4.4.1. If a program has more than one thread, it is called
multithreaded program as shown in Fig. A Multithreaded program
Main Thread

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Advantages of Multithreading:
 Multithreading is used to write very efficient programs.
 Maximum use of CPU time ie., the idle time CPU is reduced.
 The time required to perform a context switch from one thread to anotheris less.
 Multithreading require less overheads.
 Multithreading reduces the complexity of large program.
 The resources required for a threads are less than the resources required bya process.
Some Java platform supports the concept of “time slicing”. In time slicing, every thread
receives a small portion of CPU time, which is called a “quantum”. After the time period is over,
even if the thread has not finished its execution, the thread is given no more time to continue and
next thread of equal priority takes the charge of the CPU time. This is the work of Java
[Link] Threads

Creating threads in Java is simple. Threads are implemented in the form of objects that
contain a method called run ( ). The general form of run ( ) method is
public void run ( )
{
--------------------
--------------------(statements for implementing thread)
--------------------
}
The run ( ) method contains the entire body of the thread an it will be invoked by an object
of the concerned thread.
A new thread can be created in two ways.
 By creating a thread class.
Create a class that extends Thread class and override its run ( ) method with the code
required by the thread.

 By converting a class to a thread.


Define a class that implements Runnable interface, that hasonly a run ( ) method .

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Life Cycle Of A Thread


The following states can be occurs during the life cycle of a thread. It
can move from one state to another state through a variety of methods as shown
in Fig. 4.4.1.
 Newborn state
 Runnable state
 Running state
 Blocked state
 Dead state
New thread
Newborn

start stop

Active thread Running Runnable stop Dead


killed
Yield
thread Killed thread

suspend resume
sleep notify stop
wait

Idle thread (Not Runnable) Blocked

Fig. State transition of a thread


Newborn state
A thread is in newborn state immediately after we create a thread object.
At this state, we can do only one of the following things with it. Scheduling of
newborn state as shown in Fig.4.4.2.
 To move the thread into running state using start ( ) method.
 To kill the thread using the stop( ) method.

16
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

Newborn

start stop

Runnable Dead state

Fig. Scheduling a newborn thread


Runnable state
The runnable state means that a thread is ready to run and is a waiting for
the control of the processor. That is, the thread has joined the queue of threads
that are waiting for execution. If one of the thread wants to relinquish control to
another thread of equal priority, then yield ( ) method is used.( see Fig 4.4.3)
yield

running thread runnable thread

Fig. 4.4.3 Relinquishing control using yield ( ) method


Running state
Running means the processor has given its time to the thread for its
execution. A running thread may relinquish its control on its own or other
higherpriority thread in the one of the following ways.
The thread will be blocked until further order by using suspend( ) method.
The blocked thread can be resumed by resume( ) method. This is
useful when we want to suspend a thread for some time due to certain reason,
butdo not want to kill it. (See Fig 4.4.4)
Suspended

g runnable suspendedresume

17
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

Fig. 4.4.4 Relinquishing control using suspend ( ) method

It has been made to sleep. We can put a thread to sleep for a specified
time period using the method sleep (time) where time is in milliseconds. The
thread will return to the runnable state when the specified time is elapsed. For
example, the statement sleep (1000), is block a thread for 1000 milliseconds.
(See Fig 4.4.5)

sleep(time)

Running runnable suspended


after( time)

Fig. 4.4.5 Relinquishing control using sleep ( ) method

The thread will be blocked until certain condition occurs by suing wait ( )
method. The notify ( ) method is used to schedule thread to run again. (See
Fig.4.4.6)
wait

g runnable waitingnotify
Fig. 4.4.6 Relinquishing control using wait ( ) method
Blocked state
A thread is in blocked state, if it is being prevented from the runnable and
running state. This happened when thread is suspended, sleeping, or waiting in
order to satisfy certain requirements. While a thread is in the blocked state, the
scheduler will simply skip over it and no CPU time is allotted, until a thread re-

18
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

enters the runnable and running state it will not perform any operation. A
blocked thread is considered as “not runnable” but not dead.

Dead state
A thread is dead when it finishes its execution (natural death) or is
stopped (killed) by another thread (premature death). A thread can be killed as
soon as it born, or while it is running, or even when it is blocked state.
Example
/*MULTITHREAD PROGRAM*/
import [Link].*;import [Link].*;
class fact extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
int f=1;
for(int j=1;j<=i;j++)
{
f=f*j;
}
[Link](i+" Factorial is "+f);if(i==7)
{
try
{
sleep(5000);
}
catch(Exception e)
{}
}

19
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

}
}
}
class prime extends Thread
{
public void run()
{
int flag=0;
for(int i=3;i<=20;i++)
{
for(int j=2;j<i;j++)
{
if(i%j==0)
{
[Link](i+" Not prime number ");flag=0;
break;
}
else
{
flag=1;
}
}
if(flag==1)
[Link](i+" Prime number");if(i==10)
{
stop();
}
}
}
}
class fib extends Thread

20
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

{
public void run()
{
int a=-1,b=1,c,k; for(k=1;k<=10;k++)
{
c=a+b;a=b; b=c;
[Link]("Fibnoacci no is "+c);if(k==4)
{
yield();
}
}
}
}
class multi
{
public static void main(String args[])
{
fact f=new fact(); prime p=new prime();fib fi=new fib(); [Link]();
[Link]();
[Link]();
}
}
O/P is :
1 Factorial is 1
2 Factorial is 2
3 Factorial is 6
4 Factorial is 24
5 Factorial is 120
6 Factorial is 720
7 Factorial is 5040
3 Prime number

21
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

4 Not prime number5 Prime number


6 Not prime number7 Prime number
8 Not prime number 9 Not prime number 10 Not prime numberFibonacci no is 0
Fibonacci no is 1 Fibonacci no is 1 Fibonacci no is 2 Fibonacci no is 3
Fibonacci no is 5 Fibonacci no is 8 Fibonacci no is 13 Fibonacci no is 21
Fibonacci no is 34
Factorial is 40320
Factorial is 362880
Factorial is 3628800
Using Thread MethodsThread Exceptions
The call to sleep ( ) method is enclosed in a try block and followed by
the a catch block. This is necessary because the sleep ( ) method throws an
exception, which should be caught. If we fail to catch the exception, program
willnot compile.
Thread exception are caused if the active thread calls method, which is
notrelated to its state.
For example,
 A sleeping thread cannot deal with the resume ( ) method because a
sleeping thread can not receive any instruction.
 If a dead state thread calls suspend ( ) or sleep ( ) method, then
threadexception can occur.
 If a blocked thread calls suspend ( ) method, than thread exception
canoccur.
The exception handler must be specified in catch statement
whenever calling a thread method that throws an exception. Some
of the exceptions caused by threads are
 ThreadDeath - killed thread
 InterruptedException - cannot handle it in the current
state
 IllegalArgumentException - by Illegal method argument
passing

Exception - any kind of exception The different forms of the catch

22
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

statements

Thread Priority
Each thread created has a priority attached to it. The scheduler allocates
time according to these priorities. The thread scheduler to decide when each
thread should be allowed to run uses thread priorities. A higher priority can
preempt the lower priority thread, thus taking the processor’s time. The priority
of the thread can be set by the method setPriority ( ). The general form is
[Link](int Number);
Where
ThreadObjectName - is the name of the thread object.
IntNumber - is an integer value (from 1 to 10) to
which the
thread’s priority is set.
The Thread class defines several priority constants areMIN_PRIORITY =
1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The default setting of a thread priority value is NORM_PRIORITY.

Synchronization
All the threads in a program share the same memory space. So it is
possible for two threads to access the same variable and methods in an object.
Problems may occur when two or more threads accessing the same data
concurrently. The Java enables us to overcome this problem using a technique is
called as synchronization.
The keyword synchronized is used in the code to enable synchronization.
The word ‘synchronized’ can be used along with a method or within a block.
synchronized void update ( )
{
-------------- // code here is synchronized

23
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

}
When declaring a method as synchronized, Java creates a “monitor” and
hands it over to the thread that calls the method first time. As long as the thread
contains the monitor, no other thread can enter the synchronized section of
code.
After the work is over, the thread will hand over the monitor to the next
thread that is ready to use the same resource.
To mark block of code as synchronized as shown below:
synchronized (lock object)
{
-------------- // code here is synchronized

}
When two or more threads are waiting to gain control of a resources,
due to some reasons, the condition on which waiting threads to gain control not
happened. This situation is known as deadlock.
For example, assume that the thread X must access MethodA before it
can release MethodB, but the thread Y cannot release MethodA until it gets
hold of MethodB. This is the problem to arises the dead lock.
Thread X
synchronized MethodB ( )
{

synchronized MethodA ( )
{
-------------- // code here is synchronized

}
}
Thread Y
synchronized MethodA
{

24
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

synchronized MethodB ( )
{
-------------- // code here is synchronized

}
}
Implementing The Runnable Interface
The Runnable interface declares the run ( ) method that is required for
implementing threads in our program. To do this, we must perform the
following steps:
 Declare the class as implementing Runnable interface.
 Implement the run ( ) method.
 Create a thread by defining an object.
 Call the thread’s start ( ) method to run thread.
Example
class xrun implements Runnable
{
public void run()
{
for(int i=1;i<=6; i++)
{
[Link]("\nThreadX:"+i);
}

[Link]("End of Threadx");
}
}
class runnabletest
{
public static void main(String args[])
{
xrun runobject=new xrun();

25
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

Thread threadx=new Thread(runobject);[Link]();


[Link]("End of main Thread");
}
}
O/P is:
C:\jdk1.4\bin>java runnabletestEnd of main Thread
ThreadX:1 ThreadX:2 ThreadX:3 ThreadX:4 ThreadX:5 ThreadX:6
End of Threadx

26
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

UNIT – V

I/O Streams: File – Streams – Advantages - The stream classes – Byte streams –
Character streams. Applets: Introduction – Applet Life cycle – Creating & Executing
an Applet –Applet tags in HTML – Parameter tag – Aligning the display - Graphics
Class: Drawing and filling lines – Rectangles – Polygon – Circles – Arcs – Line
Graphs – Drawing Bar charts AWT Components and Even Handlers: Abstract
window tool kit – Event Handlers – Event Listeners – AWT Controls and Event
Handling: Labels – Text Component – Action Event – Buttons – Check Boxes – Item
Event – Choice– Scrollbars – Layout Managers- Input Events – Menus.

MANAGING INPUT / OUTPUT FILES


Introduction
The variables and arrays are used for storing data inside the programs. This
approach yields the following problems.

 The data is lost either when variable goes out of scope or when
the program is terminated.
 It is difficult to handle large amount of data using variables and
arrays.
We can overcome these problems by storing data on secondary storage
devices such as floppy disks or hard disks. The data is stored in these devices
using the concept of files.

A file is a collection of related records. A record is composed of fields and


a field is a group of characters as shown in Fig.4.6.1.a. Storing and managing
data using files is called as file processing which includes tasks such as creating
files, updating files and manipulation of data.

Java supports many features for managing input and output of data using
files. Reading and writing of data in a file can be done at the level of bytes or
characters or fields. Java also provides capabilities to read and write class object
directly. The process of reading and writing objects is called object serialization.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

0 0 0 0 0 0 0 0

J o h n
Field(4 Characters)

John 1001 50.00


Record(3 Fields)

John 1001 50.00


File (3 Records)
Kala 1002 60.00

Name Field

Mani 1003 57.00

Marks
Field Roll No. Field
Fig. 4.6.1.a Data representation in Java files

Concepts Of Streams
In file processing, input refers to the flow of data into a program and
output means the flow of data out of a program. Input to a program may come
from key board, the mouse, the memory, the disk or another program and output
from a program may go to the screen, the printer, memory, the disk, or another
program (See Fig 4.6.2.a).

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Java uses the concept of streams to represent the ordered sequence of data.
A stream presents a uniform, easy-to-use, object-oriented interface between the
program and the input/output devices.

Sources Destinations
Screen

Keyboard

Mouse Printer

Java
Memory Memory
Program

Disk Disk

Network Network

Fig. 4.6.2.a Relationship of Java program with I/O devices


Java streams are classified into two basic types.
 Input stream extracts (i.e. reads) data from the source (file) and sends it
to the program.
 Output stream takes data from the program and sends (i.e. writes) it to
destination (file).
Fig. 4.6.2.b illustrates the use of input and output streams. In both the cases, the
program does not know the details of end points (i.e. source and destination).

Input stream Reads


Source Program

(i) Reading data into a program

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Writes Output stream


Program Destination

(ii) Writing data to a destination


Fig. 4.6.2.b Using input and output streams

Stream Classes
The [Link] package contains a large number of stream classes that provide
capabilities for processing all types of data. These classes may be categorized
into two groups based on the data type on which type operate.
 Byte stream classes that provide support for handling I/O operations on
bytes.
 Character stream classes that provide support for managing I/O
operations on characters.
Fig. 4.6.3.a shows how stream classes are grouped based on their functions.

Java
Stream Classes

Byte Stream Character


Classes Stream Classes

Output Stream Reader Writer


Input Stream Classes Classes Classes
Classes

Memory File Pipe Memory File Pipe

Fig.4.6.3.a Classification of Java Stream Classes


Byte Stream Classes
Java provides two kinds of byte stream classes: Input stream classes and
Output stream classes.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Input Stream Classes


Input stream classes that are used to read 8-bit bytes include super class
known as InputStream and a number of subclasses for supporting various input-
related functions. Fig 4.6.4.a shows the class hierarchy of input stream classes.
The InputStream class defines methods for performing input functions (See
Table 4.6.4.b) such as
 Reading bytes
 Closing streams.
 Marking positions in streams
 Skipping ahead in a stream
 Finding the number of bytes in a stream

Object

Input Stream

FileInputStream
SequenceInputStream

PipeInputStream ObjectInputStream

ByteArrayInputStream StringBufferInputStream

FilterInputStream

BufferedInputStream PushBackInputStream

DataInputStream

DataInput

Fig. 4.6.4.a Hierarchy of input stream classes

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

The class DataInputStream extends FilterInputStream and implements


the interface DataInput . Therefore, the DataInputStream class implements the
methods described in DataInput in addition to using the methods of
InputStream class. The DataInput interface contains the following methods:
 readShort( )
 readInt( )
 readLong( )
 readFloat( )
 readUTF( )
 readDouble( )
 readLine( )
 readChar( )
 readBoolean( )

Table 4.6.4.b InputStream Methods


Method Description
read( ) Reads a byte from the input stream
read(byte b[ ]) Reads an array of bytes into b
read(byte b[ ], int n, int m) Reads m bytes into b starting from nth byte
available( ) Gives number of bytes available in the input
skip( n ) Skips over n bytes from the input stream
reset( ) Goes back to the beginning of the stream
close( ) Closes the input stream

Output Stream Classes


Output stream classes are derived from the base class OutputStream as
shown in Fig 4.6.4.c. The OutputStream is an abstract class and therefore we
cannot instantiate it. The several subclasses of the Outputstream can be used for
performing the output [Link] 4.6.4.d gives a description of all the
methods defined by the OutputStream class.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

The OutputStream includes methods that are designed to perform the


following tasks:
 Writing bytes
 Closing streams
 Flushing streams

Object

OutputStream

FileOutputStream ObjectOutputStream

PipedOutputStream ByteArrayOutputStream

FilterOutputStream

BufferedOutputStream PushbackOutputStream

DataOutputStream

DataOutput

Fig.4.6.4.c Hierarchy of output stream classes

The class DataOutputStream, counterpart of DataInputStream,


implements the interface DataOutput. Therefore, the DataOutputStream

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

class implements the methods described in DataOutput in addition to


using the methods of OutputStream class. The DataOutput interface contains
the following methods:
 writeShort( )
 writeInt( )
 writeLong( )
 writeFloat( )
 writeUTF( )
 writeDouble( )
 writeLine( )
 writeChar( )
 writeBoolean( )

Table 4.6.4.d OutputStream Methods

Method Description
write( ) Writes a byte to the output stream
write(byte b[ ]) Writes all bytes in the array b to the output
stream
write(byte b[ ], int n, int m) Writes m bytes from array b starting from nth
byte
close( ) Closes the output stream
flush( ) Flushes the output stream

Character Stream Classes


Character streams can be used to read and write 16-bit Unicode characters. There
are two kinds of character stream classes: Reader stream classes and Writer
stream classes.
Reader Stream Classes
Reader stream classes are designed to read character from the files. The
Reader class is the base class for all other classes in this group as shown in Fig.
4.6.5.a. The Reader class contains methods that are identical to those

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

available in the InputStream class except is designed to handle


characters (See Table 4.6.4.b).

Object

Reader

BufferedReader StringReader

CharArrayReader PipeReader

InputstreamReader FilterReader

FileReader PushBackReader

Fig. 4.6.5.a Hierarchy of reader stream classes

Writer Stream Classes


The writer stream classes are designed to perform all output operations on
files. The Writer stream classes are designed to write characters. The Write class
is an abstract class, which acts as a base class for all the other writer stream
classes as shown in Fig 4.6.5.b. This base class contains methods that are
identical to those available in the OutputStream class except is designed to
handle characters (See Table 4.6.4.d).

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Object

Reader

Buffered Reader String Reader

CharArrayReader Pipe Reader

InputstreamReader Filter Reader

OutputStreamWriter

File Writer

Fig. 4.6.5.b Hierarchy of writer stream classes

Using Stream
All the classes are known as I/O classes, not all of them are used for
reading and writing operations only. Some perform operations such as buffering,
filtering, data conversion, counting and concatenation while carrying out I/O
tasks.
Other Useful I/O Classes
The [Link] package supports many other classes for performing certain
specialized functions. They include among others:
 Random Access File
 StreamTokenizer

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

The RandomAccessFile enables us to read and write bytes, text and Java
data types to any location in a file (when used with appropriate access
permissions). This class extends object class and implements DataInput and
DataOutput interfaces as shown in Fig.4.6.7.a. This forces the
RandomAccessFile to implement the methods described in both these
interfaces.
The class StreamTokenizer, a subclass of object can be used for breaking
up a stream of text from an input text file into meaningful pieces called tokens.
The behaviour of the StreamTokenizer class is similar to that of the
StringTokenizer (class of [Link] package) that breaks a string into its
component tokens.

Object
Interface Interface

DataInput DataOutput

RandomAccessFile

Fig. 4.6.7.a Implementation of the RandomAccessFile

Using The File Classes


The [Link] package includes a class known as the File class that provides
support for creating files and directories. The class includes several constructors
for instantiating the File objects. This class also contains several methods for
supporting the operations such as
 Creating a file
 Opening a file
 Closing a file
 Deleting a file
 Getting the name of a file
 Getting the size of a file
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

 Checking the existence of a file


 Renaming a file
 Checking whether the file is writable
 Checking whether the file is readable

Creation Of Files
To create and use a disk file, it is necessary to decide the following about
the file and its intended purpose:
 Suitable name for the file
 Data type to be stored
 Purpose (reading, writing, or updating)
 Method of creating the file
A filename is unique string of characters that helps identify a file on the
disk. The length of a filename and characters allowed are dependent on the OS on
which the Java program is executed. A filename may contain two parts, a primary
name and an optional period with extension.
Examples:
[Link] salary
[Link] [Link]
Inventory [Link]
Data type is important to decide the type of file stream classes to be used
for handling the data. We should decide whether the data to be handled is in the
form of characters, bytes or primitive type.
The purpose of using a file must also be decided before using it. For
example, we should know whether the file is created for reading only, or writing
only, or both the operations.
For using a file, it must be opened first. This is done by creating a file
stream and then linking it to the filename. A file stream can be defined using the
classes of Reader/Input Stream for reading data and Writer/Output Stream
for writing data. The common stream classes used for various I/O operation are
given in Table. 4.6.10.a.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Table 4.6.10.a Common Stream Classes used for I/O Operations


Source or
Destination Character Bytes
Read Write Read Write
Memory CharArrayReader CharArrayWriter ByteArrayInputStream
ByteArrayOutputStream
File FileReader FileWriter FileInputStream FileOutputStream
Pipe PipedReader PipedWriter PipedInputStream PipedOutputStream

Reading / Writing Characters


Subclasses of Reader and Writer implement streams that can handle
characters. The two subclasses used for handling characters in files are
 FileReader (for reading characters) and
 FileWriter (for writing characters).
Example
import [Link].*;
class wrcharacter
{
public static void main(String args[])
{
//write character
try
{
FileWriter fw=new FileWriter("[Link]");
int ch;
while((ch=[Link]())!=-1)
{
[Link](ch);
}
[Link]();

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

}
catch(IOException e)
{
[Link](e);
[Link](-1);
}
// Read character
int b;
try
{
FileReader fr=new FileReader("[Link]");
while((b=[Link]())!=-1)
{
[Link]((char)b);
}
[Link]();
}
catch(IOException e)
{
[Link](e);
[Link](-1);
}

}
}
C:\>java wrcharacters
ale m
^Z

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

salem

Reading / Writing Bytes


Two commonly used classes for handling bytes are
 FileInputStream Classes.
 FileOutputStream Classes.
How File Input Stream class is used for reading bytes from a file. The
program reads an existing file and displays its bytes on the screen. The following
program uses both FileInputStream and FileOutputStream classes to copy
files. We need to provide a source filename for reading and a target filename for
writing.
Example
import [Link].*;
class writebyte
{
public static void main(String args[])
{
byte citites[]={'D','E','L','H','I','\n','M','A','D','R','A','S','\n'};
//write operation
try
{
FileOutputStream fos=new FileOutputStream("[Link]");
[Link](citites);
[Link]();
}
catch(IOException e)
{

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link](e);
[Link](-1);
}
// Read operation
int b;
try
{
FileInputStream fis=new FileInputStream("[Link]");

while((b=[Link]())!=-1)
{
[Link]((char)b);
}
[Link]();
}
catch(IOException e)
{
[Link](e);
[Link](-1);
}
}
}
O/P is:
C:\>javac [Link]
C:\>java writebyte
DELHI
MADRAS

Handling Primitive Data Types


If we want to read/write the primitive data types such as integers and
doubles, we can use filter classes as wrappers on existing input and output

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

APPLET PROGRAMMING
Introduction
Applet are small Java programs that are primarily used in Internet
computing. They can be transported over the Internet from one computer to
another computer and run suing Applet Viewer or any Web Browser. It can
perform arithmetic operations, display graphics, play sounds, accept user input,
create animation, and play interactive games. Java applet when run, it can
produce graphics, sound and moving images.
Local applets
An applet developed locally and stored in a local system is known as local
applet. The local system does not require the Internet connection.
Remote applets
Remote applet is developed by some one else and stored on a remote
computer connected to the Internet. We can download the remote applet onto our
system via the Internet and run it as shown in Fig.5.3.2.

Local Applet Internet

Local Computer Local Computer Remote Remote


Computer (Client) Applet (Server)

Fig.5.3.1 Loading Local Applet Fig.5.3.2 Loading a Remote Applet


How Applets Differ From Applications
The applets and stand-alone applications, both are java program, but
applets have some difference from stand-alone application as given below.
 Applets do not use main( ) method for initiating the execution of
the program. Applets, when loaded, automatically call certain
methods of applet class to start and execute the applet program.
 Unlike stand-alone applications, applets cannot be run

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

independently. They are run from a web page using HTML tag.
 Applets cannot read from or write to the files in the local computer.
 Applets cannot communicate with other servers on the network.
 Applets cannot run any program the local computer.
 Applets are restricted from using libraries from other language such
as C or C++.

Preparing To Write Applets


Before, preparing to write applets program we will need to now
 When to use applet
 How an applets works
 What features an applet has and
 Where to start, when we first create our own applets.
Let us consider the situations when we need to use applets
1. When we need dynamic display of a web page. For example shows
daily changes of share prices of various companies.
2. When we require Flash outputs. For example, applets that produce
sounds, animations etc.,
3. When we want to create program and use it on the Internet for us by
others on their computers.
The following steps are used to develop and test the applets.
 Building an applet code (.java file)
 Creating an executable applet (.class file)
 Designing a Web page using HTML tags
 Preparing <APPLET> tag
 Incorporating <APPLET> tag into the Web page.
 Creating HTML file.
 Testing the applet code.

Building Applet Code


Applet program uses the services of two classes, namely, Applet and
Graphics class from the Java class library. The services of two classes are
 Applet class and
The Applet class, which is contained in the [Link] package provides
life and behavior to the applet through its methods such as init( ), start( ) and
paint( ). The Applet class maintains the lifecycle of an applet.
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

 Graphics class
The paint( ) method of the applet class, when it is called actually display
the results of the applet program on the screen. The output may be text, graphics,
or sound. The paint( ) method require graphics object as an argument is declared
by the Graphics class. The general form of paint( ) method is
public void paint (Graphics g)
This requires that the applet program import the [Link] that contains the
Graphics class.
The general form of building applet program is
import [Link].*;
import [Link].*;

public class appletclassname extends Applet


{

public void paint ( Graphics g)


{

------------------ // Applet operations code

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

}
The appletclassname is the main class for the applet. When the applet is
loaded, Java creates an instance of this class, and then a series of Applet class
methods are called on that instance to execute the program.

Applet Life Cycle


Every Java applet inherits a set of default behavior s from the Applet
class. The Applet class maintains the lifecycle of an applet as shown in Fig.5.3.
The applet states are
 Born or Initialization state
 Running state
 Idle state
 Dead or Destroyed state
Fig.5.3. Applet Life Cycle
Begin Born

(Load Applet) Initialization


Start()
stop ( )
Run Idle
Display start () Stopped
Destroy( )
Paint()
Dead
Destroyed
End

Born or Initialization State


Applet enters the initialization state when it is first loaded. This is
achieved by calling the init() method of Applet class. The applet is born. At
this stage, we may do the following, if required
 Create objects needed by the applet

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

 Set up initial values


 Load images or fonts
 Set up colors
The initialization occurs only once in the applet’s life cycle. To provide
any of the behaviors mentioned above, we must override the init( ) method.
public void init( )
{
----------------- (Action)

}
Running state
Applet enters the running state when the system calls the start( ) method
of applet class. This occurs automatically after the applet is initialized. Starting
can also occur if the applet is already in ‘stopped’ (idle) state. For example we
may leave the web page temporarily to another page and return back to the page.
This again starts the applet running. The start( ) method may be called more than
once. We may override the start( ) method to create a thread to control the
applet.
public void start( )
{
----------------- (Action)

Idle or Stopped state


An applet becomes idle when it is stopped from running. Stopping occurs
automatically when we leave the page containing the currently running
applet. We can also do so by calling the stop() method explicitly. If we
use a thread to run the applet, then we must use stop() method to terminate the
thread. We can achieve this by overriding the stop() method.
public void stop( )
{

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

----------------- (Action)

}
Dead or Destroyed state
An applet is said to be dead when it is removed from memory. This
occurs automatically by invoking the destroy() method when we quit the
browser. Destroying stage occurs only once in the applet’s lifecycle. If the applet
has created any resources, like threads, we may override the destroy() method to
clean up these resources.
public void destroy( )
{
----------------- (Action)

}
Display State
Applet moves to the display state whenever it has to perform some output
operations on the screen. This happened immediately after the applet enters into
the running state. The paint( ) method is called to display the output. We must
override paint( ) method if we want to be displayed on the screen.
public void paint ( Graphics g)
{
----------------- (Display statements)

Creating An Executable Applet


Executable applet is means that .class file of the applet, which is generated
by compiling the source program of the applet. Compiling applet program is
same as compiling stand- alone application. We use Java compiler ( javac ) to
compile the applet program. The following steps are required for compiling the
applet program.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

 Move to the directory containing the source code and type the following
command:
 javac [Link]
 The compiled output file called [Link] is placed in the same
directory as the source.
 If any error message is received, then we must check and correct the
errors, and compile the applet program again

Designing A Web Page


A Web page or HTML page or HTML document is made up of text and
HTML tags that can be interpreted (run) by a Web browser or applet viewer.
Web pages are stored using file extension .html, and it should be stored in the
same directory as compiled code of the applets.
A Web page is marked by an opening HTML tag <HTML> and a closing HTML
tag </HTML> and is divided into three sections are
 Comment section (optional)
 Head section (optional)
 Body section
Comment Section
Comment section contains comments about Web page. A comment line
begins with <! And end with a >. Web browser will ignore the text enclosed
between them. Comments are optional and can be included anywhere in the Web
page.
Head Section
The head section is defined with a starting <HEAD> tag and a closing
</HEAD> tag. Head section usually contains a title for web page. The text
enclosed in the tags <TITLE> and </TITLE> will appear in the title bar of the
Web browser when it displays the page. The head section is also optional. A
slash ( / ) in a tag indicates the end of that tag section.
Body section
Body section contains the entire information about the web page and its
behavior.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Applet Tag
We have included a pair of <APPLET….> and </APPLET> tags in the
body section of HTML tags. The <APPLET….> tag supplies the name of the
applet to be loaded and tells the browser how much space applet requires. The
ellipsis in the tag<APPLET..> indicates that it contains certain attributes that
must be specified. The minimum requirement of <APPLET….> tag specifies
three things.
 Name of the applet
 Width of the applet (in pixels)
 Height of the applet (in pixels)
The general form of APPLET tag is
<APPLET
CODE = [Link]
WIDTH = (in pixels)
HEIGHT = (in pixels)

>
</APPLET>
Adding Applet To Html File
Adding applet to a HTML document, we should follow the following steps:
 Insert an <APPLET>tag at an appropriate place in the web
page.
 Specify the name of the applet’s .class file.
 If the .class file not in the current directory, use the codebase
parameter to specify
o The relative path if file on the local system, or
o The URL of the directory containing the file, if it is on a
remote system.
 Specify the space required for display of the applet in terms of
width and height in pixels.
 Add any user-defined parameters using <PARAM>tags.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

 Add alternate HTML text to be displayed when a non-Java


browser is used.
 Close the applet declaration with the <APPLET> tag.

Running The Applet


To run an applet, it requires the following tools.
 Java-Enabled Web Browser (such as Internet Explorer or Hot
Java)
 Java appletviewer
Java-Enabled Web Browser
If we use a java-enabled Web browser for running the applet program, we
will be able to see the entire Web page containing the applet.
Java appletviewer
If we use a Java appletviewer for running the applet program, we will only
see the applet output. The appletviewer is available as a part of the Java
Development Kit. We can use it to run our applet as follows:
>appletviewer [Link]
The argument of the appletviewer is not the .java file or the .class file, but rather
.html file

More About Applet Tag


The general form of <APPLET> tag is
<APPLET
[CODEBASE =codebaseURL]
CODE = [Link]
[ALT = alternateText]
[NAME = applet_instance_name]
WIDTH = (in pixels)
HEIGHT = (in pixels)
[ALIGN =alignment]
[VSPACE =pixels]
[HSPACE =pixel]

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

>
[ <PARAM NAME = name1 VALUE = value1 >]
[ <PARAM NAME = name2 VALUE = value2 >]

[Text to be displayed in the absence of Java]


</APPLET>
The attributes shown inside [ ] indicate optional.

Passing Parameters to Applets


We can supply user-defined parameters to an applet using <PARAM…>
tags. Each <PARAM…> tag has a name attribute such as color, and value
attribute such as red. Inside the applet code, the applet can refer to that parameter
by name to find its value. For example, we can change the color of the text
displayed to red by an applet using <PARAM…> tag as follows:
<APPLET ….>
<PARAM NAME = “color” VALUE = “red”>
</APPLET>
To set up and handle parameters we need to do two things:
 Include appropriate <PARAM…>tags in the HTML document.
 Provide code in the applet to parse these parameters
The parameters are passed to an applet when it is loaded. We can define the
init ( ) method in the applet to get hold of the parameters defined in the
<PARAM> tags. This is done by using the getParameter( ) method, which takes
one string argument containing the value of that parameter.

Example
//paramapplet applet program
import [Link].*;
import [Link].*;
public class paramapplet extends Applet
{

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

String s;
public void init()
{
s=getParameter("str");
if(s==null)
s="Java";
s="Hello"+s;
}
public void paint(Graphics g)
{
[Link](s,20,200);
}
}
The html file for paramapplet applet program
<html>
<head>
<body>
<applet code=[Link] width=400 height=400>
<param name="str" value="applet">
</applet>
</body>
</html>
O/P is:

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Aligning The Display


We can align the output of the applet using the ALIGN attribute. This
attribute can have one of the nine values:
LEFT, RIGHT, TOP, TEXT TOP, MIDDLE, ABSMIDDLE, BASELINE,
BOTTOM, ABSBOTTOM
For Example
ALIGN = RIGHT - will display the output at the right margin of
the page

Displaying Numerical Values


In applets, we can display numerical values by first converting them into
strings and then using the drawstring() method of |Graphics class. The following
program illustrates how an applet handles numerical values.
Example
import [Link].*;
import [Link].*;
public class simpleapplet extends Applet
{
int a,b,c;
public void init()
{
a=10;
b=20;
}
public void start()
{
c=a+b;
}
public void paint(Graphics g)
{
String s="Sum :"+[Link](c);
[Link](s,200,200);

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

}
}

<html>
<body>
<applet code=[Link] width=300 height=400>
</applet>
</body>
</html>

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Getting Input From The User


Applets work in a graphical environment. Therefore, applets treat inputs as
text strings. we must first create an area of the screen in which user can type and
edit input items. we can do this by using the TextField class of the awt
[Link] following program demonstrates how these steps are implemented.
Example

import [Link].*;
import [Link].*;
import [Link].*;
public class fun1 extends Applet implements ActionListener
{
Label l1,l2,l3;
TextField t1,t2,t3;
Button b1;
public void init()
{
l1=new Label("enter a");
l2=new Label("enter b");
l3=new Label("result");
t1=new TextField(15);
t2=new TextField(15);
t3=new TextField(10);
b1=new Button("ADD");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
String s=[Link]();
int a,b,c;
float d;
a=[Link]([Link]());
b=[Link]([Link]());
if([Link]("ADD"))
{
c=a+b;
[Link]([Link](c));
}
}
}
<html>
<body>
<applet code="[Link]" width=400 height=400>
</applet>
</body>
</html>

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

GRAPHICS PROGRAMMING
Introduction
Java Applet has its own area of the screen known as canvas, where it
creates its display. The size of an applet’s space is decided by the attributes of the
<APPLET…> tag. We can write Java applets that draw lines, figures, images,
and text in different fonts and styles.
A Java applet draws graphical image inside its space using the coordinate
system as shown in Fig.4.5.2.a. Java, coordinate system has the origin (0,0) in the
upper-left corner. The positive x values are to the right, and positive y values are
to the bottom. The values of coordinates x and y are in pixels.
The Graphics Class
Java‘s Graphics class includes methods for drawing many different types
of shapes, from simple lines to polygons to text in a variety of fonts. To draw a
shape on the screen, we may call one of the methods available in the Graphics
class. Table shows the commonly used drawing methods available in the
Graphics class. All the drawing methods have arguments representing end points,
corners, or starting locations of a shape as values in the applet’s coordinate
system. To draw a shape, we only need to use the appropriate method with the
required arguments.
Table Drawing methods of the Graphics class
Method Description
clearRect ( ) Erases a rectangular area of the canvas.
copyArea ( ) Copies a rectangular area of the canvas to another
area.
drawArc ( ) Draws a hollow arc.
drawLine ( ) Draws a straight line.
drawOval ( ) Draws a hollow oval.
drawPolygon ( ) Draws a hollow polygon
drawRect ( ) Draws a hollow rectangle.
drawRoundRect ( ) Draws a hollow rectangle with rounded corner.
drawstring ( ) Displays a text string.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

fillArc ( ) Draws a filled arc.


fillOval ( ) Draws a filled oval.
fillPolygon ( ) Draws a filled polygon
fillRect ( ) Draws a filled rectangle.
fillRoundRect ( ) Draws a filled rectangle with rounded corners.
getColor ( ) Retrieves the current drawing color.
getFont ( ) Retrieves the currently used font.
getFontMetrics ( ) Retrieves information about the current font
setColor ( ) Set the drawing color.
setFont ( ) Set the font.

Lines And Rectangles


The drawLine ( ) method is used to draw a line, it takes two pair of
coordinates, (x1, y1) and (x2, y2) as arguments and draws a line between them.
The general form is
[Link](x1, y1, x2, y2);
Example:
[Link]( 10, 10, 50, 50);
The g is the Graphics Object passed to paint ( ) method.
The drawRect ( ) method is used to draw a rectangle, it takes four
arguments, the first two represent the x and y coordinates of the top left corner of
the rectangle, and remaining two represent width and height of the rectangle. The
general form is
[Link](x, y, width, height);
Example:
[Link](20, 60, 30 , 20);

( x, y) width height
top left corner

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Rectangle
The drawRect ( ) method draws only the outline of a box. We can draw a
solid box using the method fillRect ( ) method. This also takes four parameters,
the first two represent the x and y coordinates of the top left corner of the
rectangle, and remaining two represent width and height of the rectangle. The
general form is
[Link](x, y, width, height);
Example:
[Link](20, 60, 30 , 20);

( x, y ) width height
starting point

Filled Rectangle
We can also draw rounded edges rectangles, using the methods
drawRoundRect ( ) and fillRoundRect ( ). These two methods are same as
drawRect ( ) and fillRect ( ) methods except that they take extra two arguments
representing the width and height of the angle of [Link] general forms are
[Link](x, y, width, height , width of angle of corner,
height of angle of corner);
[Link](x, y, width, height, width of angle of corner,
height of angle of corner);
Example:
[Link](20, 60, 30 , 20, 10, 10);

Rounded Rectangle
[Link](20, 60, 30 , 20, 10, 10);

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Circles And Ellipses


The drawOval() method can be used to draw a circle or an ellipse. The
drawOval ( ) method takes four arguments, The first two represent the top left
corner of the imaginary rectangle and other two represent the width and height of
the oval itself. If the width and height are same, the oval becomes a circle. The
general form is
drawOval(x, y, width, height);
Example:
drawOval(20, 20, 160, 120);

(20, 20)

height (120)

width(160)

The drawOval ( ) method only draws outline of an oval. We can draws a


solid oval by using fillOval ( ) method. The fillOval ( ) method takes four
arguments. The first two represent the top left corner of the imaginary rectangle
and other two represent the width and height of the filled oval itself. If the width
and height are same, the filled oval becomes a filled circle.
The general form is
fillOval(x, y, width, height);
Example:
fillOval(20, 20, 160, 120);
(20, 20)

height (120)

width(160)
We can draw an object using a color object as follows.

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]([Link]);
After setting the color, all drawing operations will occur in that color.

Drawing Arcs
The drawArc ( ) method is used to draw arcs. The drawArc ( ) method
takes six arguments, the first four are the same as the arguments of drawOval ( )
method and last two represent the starting angle of the arc and the number of
degrees around the arc.
In drawing arcs, java actually formulates the arc as an oval and then draws
only a part of it as dictated by last two arguments. Java consider the 3 O’ clock
position as zero degree position and degree increase in anti-clockwise direction
as shown in Fig.4.5.5.a. So, to draw an arc from 12.00 O’ clock position to 6.00
O’ clock position, the starting angle would be 90 o, and the sweep angle would be
180o.
90 o

35 o
180 o

180 o 0o
-135 o

270 o
Fig.4.5.5.a Arc as a part of an oval Fig.4.5.5.b Drawing an ac in
clockwise

We can also draw an arc in backward direction by specifying the sweep


angle as negative. For example, the last angle is –135o and the starting angle is
35o, then the arc is drawn as shown in Fig.4.5.5.b We can use fillArc ( ) method
to fill the arc.
Example
Import [Link].*;
Import [Link].*;
Public class graph extends Applet

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

{
public void paint(Graphics g)
{
[Link](10,10,50,50);
[Link](10,60,40,30);
[Link](60,10,30,80);
[Link](20,110,60,30,5,5);
[Link](20,110,60,30,10,10);
[Link](20,20,200,120);
[Link]([Link]);
[Link](70,30,100,100);
[Link](60,125,80,40,180,180);
}
<html>
<body>
<applet code=[Link] width=400 height=600>
</applet>
</body>
</html>
O/P is:

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Drawing Polygons
Polygons are shapes with many sides. The drawPolygon ( ) method is
used to draw a polygon. This method takes three arguments:
 An array of integers containing x coordinates.
 An array of integers containing y coordinates.
 An integer for the total number of points.
It is obvious that x and y arrays should be of the equal size and we must repeat
the first point at the end of the array for closing the polygon.
We can also draw a filled polygon by using the fillPolygon ( ) method.
Second, way of calling the methods drawPolygon ( ) and fillPolygon ( ) is
to use a Polygon object. The Polygon class enables us treat the polygon as an
object. This approach involves the following steps.
 Defining x coordinate values as an array.
 Defining y coordinate values as an array.
 Defining the number of points n.
 Creating a Polygon object and initializing it with the above x, y
and n values.
 Calling the method drawPolygon ( ) or fillPolygon ( ) with the
Polygon object as argument.
The Polygon class is useful to add points to the Polygon.
We first create an empty polygon and then add points to it one another.
Finally call drawPolygon ( ) method using the poly object as an argument to
complete the process of drawing the polygon.
Example
import [Link].*;
import [Link].*;
public class poly extends Applet
{
int x1[]={20,120,220,20};
int y1[]={20,120,20,20};
int n1=4;
int x2[]={120,220,220,120};

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

int y2[]={120,20,220,120};
int n2=4;
public void paint(Graphics g)
{
[Link](x1,y1,n1);
[Link](x2,y2,n2);
}
}
<html>
<body>
<applet code=[Link] width=400 height=400>
</applet>
</body>
</html>
O/P is:

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Line Graphs
We can design applets to draw line graphs to illustrate graphically the
relationship between two variables.
Using Control Loops In Applet
We can use all control structures in an applet.
Drawing Bar Charts
Applets can be designed to display bar charts, which are commonly used
in comparative of data.
The method getParameter( ) is used to fetch the data values from the
HTML file. The getParameter( ) returns only string values and therefore we use
the wrapper class method parseInt to convert strings to integer values.
Example
import [Link].*;
import [Link].*;
public class barchart extends Applet
{
int n=0;
String label[];
int value[];
public void init()
{
try
{
n=[Link](getParameter("columns"));
label=new String[n];
value=new int[n];
label[0]=getParameter("label1");
label[1]=getParameter("label2");
label[2]=getParameter("label3");
label[3]=getParameter("label4");
value[0]=[Link](getParameter("c1"));
value[1]=[Link](getParameter("c2"));

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

value[2]=[Link](getParameter("c3"));
value[3]=[Link](getParameter("c4"));
}
catch(NumberFormatException e)
{}
}
public void paint(Graphics g)
{
for(int i=0;i<n;i++)
{
[Link]([Link]);
[Link](label[i],20,i*50+20);
[Link](50,i*50+10,value[i],40);
}
}
}

<html>
<body>
<applet code=[Link] width=500 height=500>
<param name="colums" value="4">
<param name="c1" value="110">
<param name="c2" value="150">
<param name="c3" value="100">
<param name="c4" value="170">
<param name="label1" value="91">
<param name="label2" value="92">
<param name="label3" value="93">
<param name="label4" value="94">
</applet>
</body>
</html>

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

O/P is:

AWT CONTROLS AND EVENT HANDLING:

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java.

Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).

The [Link] package provides classes for AWT API such as Text Field, Label, Text Area
Radio Button, Check Box, Choice, List etc.

The AWT tutorial will help the user to understand Java GUI programming in simple and easy
steps.

Java AWT Hierarchy

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

The hierarchy of Java AWT classes are given below.

Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java
AWT, there are classes for each component as shown in above diagram. In order to place
every component in a particular position on a screen, we need to add them to a container.

Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such
as Frame, Dialog and Panel.

It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components

Event and Listener

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

Steps to perform Event Handling

Following steps are required to perform event handling:

1. Register the component with the Listener

Registration Methods

For registering the component with the Listener, many classes provide the registration
methods. For example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Java Event Handling Code


We can put the event handling code into one of the following places:

1. Within class
2. Other class

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

3. Anonymous class

Java event handling by implementing ActionListener


import [Link].*;
import [Link].*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
[Link](60,50,170,20);
Button b=new Button("click me");
[Link](100,120,80,30);

//register listener
[Link](this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
[Link]("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the
above example that sets the position of the component it may be button, textfield etc.

Downloaded by Saro Saro (sarojini1341@[Link])

You might also like