You are on page 1of 100

1

Java Programming
Difference between Procedural and Object Oriented Programming
The different languages reflect the different styles of programming.
Procedural programming decomposes a program into various different functional
units, each of which can gather and manipulate data as needed.
Object-oriented programming, on the other hand, decomposes a program
into various different data-oriented units or other conceptual units; each unit
contains data and various operations that may be performed on that data.
Procedural programming forced developers to write highly interdependent code.
A minor change in any part of the code may end up with a bigger
modification of large pieces of code. This way of programming is not up to the
mark when the user interactivity is higher.Using OOP, a developer can break down
any real world item into a collection of objects. These individual objects can be
used separately and collectively to accomplish the requirements.
We can summarize the differences as follows:
Procedural Programming
top down design
create functions to do small tasks
communicate by parameters and return values
Object Oriented Programming
design and represent objects
determine relationships between objects
determine attributes each object has
determine behavior of each object will respond to
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

create objects and send messages to them to use or manipulate their


attributes
Encapsulation
The encapsulation is achieved by combining the methods and attribute into a
class.The class acts like a container encapsulating the properties. The users are
exposed mainly public methods.The idea behind is to hide how things work and
just exposing the requests a user can do
Introduction to JAVA
Java is a high level programming Language. It was introduced by SUN
MicroSystems in June 1995. It was officially released in November 1995. It was
developed by a team under James Gosling.
Its original name was OAK meant for consumer electronic devices and
later renamed to Java. Java has become the standard for Internet applications. It
provides interactive processing and easy use of graphics and animation on
the Internet. Since the Internet consists of different types of computers
and operating systems.
A common language needed to enable computers to run programs that run
on multiple plot forms. This need was fulfilled by Java, and it so on. Because the
language of choice for the Internet. Java is Object-Oriented language built on C
and C++. It derives its syntax from C and its Object-Oriented features are
influenced by C++.
Java can be used to create two types of programs. Those
are Applications and Applets. An application is a program that runs on the users
computers under the operating system. An Applet is a small window based
program that runs on HTML page using a java enabled web browser like internet
Explorer, Netscape Navigator or an Applet Viewer.
Java Features
1. Compiled and Interpreter:- Java has both compiled and interpreter feature
program of java is first compiled and then it is must to interpret it .first of all the
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

program of java is compiled then after compilation it creates bytes codes rather
than machine language. Then after bytes codes are converted into the machine
language is converted into the machine language with the help of the interpreter.
So for executing the java program first of all it is necessary to compile it then it
must be interpreter
2. Platform independent:- Java language is platform independent means program
of java is easily transferable because after compilation of java program bytes
code will be created then we have to just transfer the code of byte code to
another computer this is not necessary for computers having same operating
system in which the code of the java is created and executed after compilation
of the java program we easily convert the program of the java top the another
computer for execution
3. Object-oriented:- We know that is purely OOP language that is all the code of
the java language is written into the classes and objects so for this feature java
is most popular language because it also supports code reusability,
maintainability etc.
4. Robust and secure:- the code of java is robust and means of first checks the
reliability of the code before execution when we trying to convert the higher
data type into the lower then it checks the demotion of the code the it will warns
a user to not to do this so it is called as robust
5. Secure:- when we convert the code from one machine to another the first check
the code either it is effected by the virus or not or it checks the safety of the
code if code contains the virus then it will never executed that code on to the
machine.
6. Distributed:- java is distributed language means because the program of java is
compiled onto one machine can be easily transferred to machine and executes
them on another machine because facility of bytes codes so java is specially
designed for internet users which uses the remote computers for executing their
programs on local machine after transferring the programs from remote
computers or either from the internet.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

7. Simple small and familiar:- is a simple language because it contains many


features of other languages like C and C++ and java removes complexity
because it doesnt use pointers, storage classes and go to statements and java
doesnt support multiple inheritance.
8. Multithreaded and interactive:- java uses multithreaded techniques for
execution means like in other in structure languages code is divided into the
small parts like these code of java is divided into the smaller parts those are
executed by java in sequence and timing manner this is called as multithreaded
in this program of java is divided into the small parts those are executed by
compiler of java itself java is called as interactive because code of java supports
also cui and also GUI programs.
9. Dynamic and extensible code:- java has dynamic and extensible code means
with the help of oops java provides inheritance and with the help of inheritance
we reuse the code that is pre-defined and also uses all the built in functions of
java and classes.
10.Distributed:-Java is a distributed language which means that the program can
be design to run on computer networks. Java provides an extensive library of
classes for communicating, using TCP/IP protocols such as HTTP and FTP.
This makes creating network connections much easier than in C/C++. You can
read and write objects on the remote sites via URL with the same ease that
programmers are used to when read and write data from and to a file. This helps
the programmers at remote locations to work together on the same project.
11.Secure: Java was designed with security in mind. As Java is intended to be used
in networked/distributor environments so it implements several security
mechanisms to protect you against malicious code that might try to invade your
file system. For example: The absence of pointers in Java makes it impossible
for applications to gain access to memory locations without proper
authorization as memory allocation and referencing model is completely opaque
to the programmer and controlled entirely by the underlying run-time platform .
12.Architectural Neutral:- One of the key features of Java that makes it different
from other programming languages is architectural neutral (or platform
independent). This means that the programs written on one platform can run on
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

any other platform without having to rewrite or recompile them.In other words,
it follows 'Write-once-run-anywhere' approach. Java programs are compiled
into byte-code format which does not depend on any machine architecture but
can be easily translated into a specific machine by a Java Virtual Machine
(JVM) for that machine. This is a significant advantage when developing
applets or applications that are downloaded from the Internet and are needed to
run on different systems.
13.Portable:-The portability actually comes from architecture-neutrality. In C/C+
+, source code may run slightly differently on different hardware platforms
because of how these platforms implement arithmetic operations. In Java, it has
been simplified. Unlike C/C++, in Java the size of the primitive data types are
machine independent. For example, an int in Java is always a 32-bit integer, and
float is always a 32-bit IEEE 754 floating point number. These consistencies
make Java programs portable among different platforms such as Windows,
Unix and Mac .
14.Interpreted:- Unlike most of the programming languages which are either
complied or interpreted, Java is both complied and interpreted The Java
compiler translates a java source file to bytecodes and the Java interpreter
executes the translated byte codes directly on the system that implements the
Java Virtual Machine. These two steps of compilation and interpretation allow
extensive code checking and improved security.
15.High performance:- Java programs are compiled to portable intermediate form
known as bytecodes, rather than to native machine level instructions and JVM
executes Java bytecode on any machine on which it is installed. This
architecture means that Java programs are faster than program or scripts written
in purely interpreted languages but slower than C and C++ programs that
compiled to native machine languages. Although in the early releases of Java,
the interpretation of by bytecode resulted in slow performance but the advance
version of JVM uses the adaptive and Just in time (JIT) compilation technique
that improves performance by converting Java bytecodes to native machine
instructions on the fly.
BYTE CODE:
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

Bytecode is nothing but the intermediate representation of Java source code which
is produced by the Java compiler by compiling that source code. This byte code is
an machine independent code. It is not an completely a compiled code but it is an
intermediate code somewhere in the middle which is later interpreted and executed
by JVM. Bytecode is a machine code for JVM. But the machine code is platform
specific whereas bytecode is platform independent that is the main difference
between them. It is stored in .class file which is created after compiling the source
code. Most developers although have never seen byte code (nor have ever wanted
to see it!) One way to view the byte code is to compile your class and then open
the .class file in a hex editor and translate the bytecodes by referring to the virtual
machine specification. A much easier way is to utilize the command-line utility
javap. The Java SDK from Sun includes the javap disassembler, that will convert
the byte codes into human-readable mnemonics.

JVM:
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

A Java virtual machine (JVM), an implementation of the Java Virtual


Machine Specification, interprets compiled Java binary code (called bytecode) for a
computer's processor (or "hardware platform") so that it can perform a Java
program's instructions. Java was designed to allow application programs to be built
that could be run on any platform without having to be rewritten or recompiled by
the programmer for each separate platform. A Java virtual machine makes this
possible because it is aware of the specific instruction lengths and other
particularities of the platform.
The Java Virtual Machine Specification defines an abstract -- rather than a
real -- machine or processor. The Specification specifies an instruction set, a set
of registers, a stack, a "garbage heap," and a method area. Once a Java virtual
machine has been implemented for a given platform, any Java program (which,
after compilation, is called bytecode) can run on that platform. A Java virtual
machine can either interpret the bytecode one instruction at a time (mapping it to a
real processor instruction) or the bytecode can be compiled further for the real
processor using what is called a just-in-time compiler.

Java Tokens:A java Program is made up of Classes and Methods and in the Methods are
the Container of the various Statements And a Statement is made up of Variables,
Constants, operators etc.
Tokens are the various Java program elements which are identified by the
compiler. A token is the smallest element of a program that is meaningful to the
compiler. Tokens supported in Java include keywords, variables, constants, special
characters, operations etc.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

When you compile a program, the compiler scans the text in your source
code and extracts individual tokens. While tokenizing the source file, the compiler
recognizes and subsequently removes whitespaces (spaces, tabs, newline and form
feeds) and the text enclosed within comments. Now let us consider a program

//Print Hello
public class Hello
{
public static void main(String args[])
{
System.out.println(Hello Java);
}
}
The source code contains tokens such as public, class, Hello, {, public,
static, void, main, (, String, [], args, {, System, out, println, (, "Hello Java", }, }.
The resulting tokens are compiled into Java bytecodes that is capable of being run
from within an interpreted java environment. Token are useful for compiler to
detect errors. When tokens are not arranged in a particular sequence, the compiler
generates an error message.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

Tokens are the smallest unit of Program There is Five Types of Tokens
Reserve Word or Keywords
Identifier
Literals
Operators
Separators
Type Casting:
It is sometimes necessary to convert a data item of one type to another type.
For example: when it is necessary to perform some arithmetic using data items of
different types (so called mixed mode arithmetic). Under certain circumstances
Type conversion can be carried out automatically, in other cases it must be "forced"
manually (explicitly).
Automatic Conversion:
In Java type conversions are performed automatically when the type of the
expression on the right hand side of an assignment operation can be safely
promoted to the type of the variable on the left hand side of the assignment. Thus
we can safely assign: byte -> short -> int -> long -> float -> double.
For example:
//64 bit long integer
long myLongInteger;
//32 bit long integer
int myInteger;
myLongInteger=myInteger;
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

10

The extra storage associated with the long integer, in the above example, will
simply be padded with extra zeros.
Explicit Conversion (Casting):
The above will not work the other way round. For example we cannot
automatically convert a long to an int because the first requires more storage than
the second and consequently information may be lost. To force such a conversion
we must carry out an explicit conversion (assuming of course that the long integer
will fit into a standard integer). This is done using a process known as a type cast:
myInteger = (int) myLongInteger
This tells the compiler that the type of myLongInteger must be temporarily
changed to a int when the given assignment statement is processed. Thus, the cast
only lasts for the duration of the assignment. Java type casts have the following
form: (T) N where T is the name of a numeric type and N is a data item of another
numeric type. The result is of type T.
Difference between Type Conversion and Type Casting:
Type Conversion is that which converts the one data type into another for
example converting a int into float converting a float into double The Type
Conversion is that which automatically converts the one data type into another but
remember we can store a large data type into the other for ex we can t store a float
into int because a float is greater than int Type Conversion is Also Called as
Promotion of data Because we are Converting one Lower data type into higher data
type So this is Performed Automatically by java compiler.
new keyword
new is a keyword which is used when we are creating an object of class
for storing all the data like variables and member functions of class. There is
some memory space that is to be needed so that with the help of new keyword and
object is instantiated or simply an object reserves.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

11

Some memory or some new memory is allocated to class object for storing
data and member functions of class so every object must be created with the help
of new keyword so for allocating new memory area.
Identifiers
Identifier is a simple variable name which is defined as the value container.
The type of value stored by identifier is defined by the special java keyword is
termed as primitive data type.
In the given example there are some identifiers have been used
like byteident, shortident, intident, longident, charident, stringident, floatident,
doubleident. And there are some primitive data types of used identifiers have been
also used in the program like byte, short, int, long, float, double, char andString.
In addition to the rules that governs identifiers, Java programmers follow
certain style conventions to make up names for classes, methods, constants,
variables, interfaces and packages.
1. Class names in Java begins with a capital letter. Class names should be
descriptive names or noun phrases but not very long. If class name contains
multiple words then each subsequent word in the class name begins with a capital
letter. For
example:
Employee,
GradeBook,
CommissionEmployee,
ProcessExamResult etc.
2. Names of the fields that are not final and method's name should begin with a
lowercase letter. Method names should be verbs or verb phrases. However, if they
contain multiple words then each subsequent word in the name begins with a
capital letter. For example: firstName, salary, getName, getMaximum etc.
3. Names of the packages intended only for local use should have a first identifier
that begins with a lowercase letters.
4. Constant represents fixed values that cannot be altered. For example, PI is
constant with a fixed value 3.14159. Such constants should be written in
uppercase.
These conventions are followed so that programmers can distinguish
whether an identifier corresponds to a class name, variable, method, package in a
program. All the data type has its own capacity to keep the maximum value which
has been mentioned below:
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

12

Primitive Data Types


Keyword

Description

Size/Format

byte

Byte-length integer

8-bit two's complement

short

Short integer

16-bit two's complement

int

Integer

32-bit two's complement

long

Long integer

64-bit two's complement

Integers

Real numbers
float

Single-precision floating point

32-bit IEEE 754

double

Double-precision floating point

64-bit IEEE 754

char

A single character

16-bit Unicode character

boolean

A boolean value (true or false)

true or false

Other types

Java Operators
An operator is a symbol which helps the user to command the computer to
do a certain mathematical or logical manipulations. Operators are used
in Java language program to operate on data and variables. Java has a rich set of
operators which can be classified as
(1) Arithmetic Operators
(2) Relational Operators
(3) Logical Operators
(4) Assignment Operators
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

13

(5) Increments and Decrement Operators


(6) Conditional Operators
(7) Bitwise Operators
(8) Special Operators
(1) Arithmetic Operators: All the basic arithmetic operations can be carried out
in Java. All the operators have almost the same meaning as in other languages.
Both unary and binary operations are available in Java language. Unary operations
operate on a single operand, therefore the number 5 when operated by unary will
have the value 5.
Examples of arithmetic operators are:
x+y
x-y
-x + y
a*b+c
-a * b
Here a, b, c, x, y are known as operands. The modulus operator is a special
operator in Java language which evaluates the remainder of the operands after
division.
Integer Arithmetic: When an arithmetic operation is performed on two whole
numbers or integers than such an operation is called as integer arithmetic. It always
gives an integer as the result. Let x = 27 and y = 5 be 2 integer numbers.
Then the integer operation leads to the following results:
x + y = 32
x y = 22
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

14

x * y = 115
x%y=2
x/y=5
In integer division the fractional part is truncated
Floating Point Arithmetic: When an arithmetic operation is preformed on two
real numbers or fraction numbers such an operation is called floating point
arithmetic. The floating point results can be truncated according to the properties
requirement. The remainder operator is not applicable for floating point arithmetic
operands.
Let x = 14.0 and y = 4.0 then
x + y = 18.0
x y = 10.0
x * y = 56.0
x / y = 3.50
Mixed mode arithmetic: When one of the operands is real, other is an integer and
if the arithmetic operation is carried out on these 2 operands then it is called as
mixed mode arithmetic. If anyone operand is of real type then the result will
always be real thus 15/10.0 = 1.5.
(2) Relational Operators: Often it is required to compare the relationship between
operands and bring out a decision and program accordingly. Java supports the
following relational operators.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

15

It is required to compare the marks of 2 students, salary of 2 persons, we can


compare them using relational operators. A simple relational expression contains
only one relational operator and takes the following form:
exp1 relational operator exp2
Where exp1 and exp2 are expressions, which may be simple constants, variables or
combination of them. Given below is a list of examples of relational expressions
and evaluated values.
6.5 <= 25 TRUE
-65 > 0 FALSE
10 < 7 + 5 TRUE
Relational expressions are used in decision making statements of Java language
such as if, while and for statements to decide the course of action of a running
program.
(3) Logical Operators: Java has the following logical operators, they compare or
evaluate logical and relational expressions.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

16

Logical AND (&&) : This operator is used to evaluate 2 conditions or expressions


with relational operators simultaneously. If both the expressions to the left and to
the right of the logical operator is true then the whole compound expression is true.
a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole
expression is true only if both expressions are true i.e., if a is greater than b and x is
equal to 10.
Logical OR (||): The logical OR is used to combine 2 expressions or the condition
evaluates to true if any one of the 2 expressions is true.
a < m || a < n
The expression evaluates to true if any one of them is true or if both of them
are true. It evaluates to true if a is less than either m or n and when a is less than
both m and n.
Logical NOT (!): The logical not operator takes single expression and evaluates to
true if the expression is false and evaluates to false if the expression is true. In
other words it just reverses the value of the expression.
! (x >= y)
The NOT expression evaluates to true only if the value of x is neither greater
than nor equal to y.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

17

(4) Assignment Operators: The Assignment Operator evaluates an expression on


the right of the expression and substitutes it to the value or variable on the left of
the expression.
x=a+b
Here the value of a+b is evaluated and substituted to the variable x. In
addition, Java has a set of shorthand assignment operators of the form.
var oper = exp;
Here var is a variable, exp is an expression and oper is a Java binary
arithmetic operator. The operator oper = is known as shorthand assignment
operator.
x + = 1 is same as x = x + 1
The commonly used shorthand assignment operators are as follows:

Data Types
The Java programming language is strongly-typed, which means that all
variables must first be declared before they can be used. This involves stating the
variable's type and name, as you've already seen:
int gear = 1;
Doing so tells your program that a field named "gear" exists, holds
numerical data, and has an initial value of "1". A variable's data type determines
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

18

the values it may contain, plus the operations that may be performed on it. In
addition to int, the Java programming language supports seven other primitive data
types.
A primitive type is predefined by the language and is named by a reserved
keyword. Primitive values do not share state with other primitive values. The eight
primitive data types supported by the Java programming language are:
byte: The byte data type is an 8-bit signed two's complement integer. It has a
minimum value of -128 and a maximum value of 127 (inclusive).
short: The short data type is a 16-bit signed two's complement integer. It has a
minimum value of -32,768 and a maximum value of 32,767 (inclusive).
int: The int data type is a 32-bit signed two's complement integer. It has a
minimum value of -2,147,483,648 and a maximum value of 2,147,483,647
(inclusive).
long: The long data type is a 64-bit signed two's complement integer. It has a
minimum value of -9,223,372,036,854,775,808 and a maximum value of
9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range
of values wider than those provided by int.
float: The float data type is a single-precision 32-bit IEEE 754 floating point As
with the recommendations for byte and short, use a float (instead of double) if you
need to save memory in large arrays of floating point numbers. This data type
should never be used for precise values, such as currency.
double: The double data type is a double-precision 64-bit IEEE 754 floating point.
For decimal values, this data type is generally the default choice. As mentioned
above, this data type should never be used for precise values, such as currency.
boolean: The boolean data type has only two possible values: true and false. Use
this data type for simple flags that track true/false conditions. This data type
represents one bit of information, but its "size" isn't something that's precisely
defined.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

19

char: The char data type is a single 16-bit Unicode character. It has a minimum
value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
In addition to the eight primitive data types listed above, the Java programming
language also provides special support for character strings via the java.lang.String
class.
Automatic memory management
It also known as automatic garbage collection, is the practice of allowing the
language implementation to keep track of used and unused memory, freeing the
programmer from this burden.
In languages without automatic memory management, the programmer must
reserve memory when it is required and mark it as free once its contents no longer
have effect in the running program. For example, in the C programming language
(probably the most commonly used of those without automatic memory
management)
this
is
achieved
by
using
the
functions malloc, calloc,realloc, alloc and free.
On the other hand, languages (or implementations) with automatic memory
management automatically reserve memory when it is required for storing new
values and reclaim it (free it) when their contents can no longer affect future
computations
(1) Java automatically does the Garbage collecting and probably does a better job
than most developers on the down side.
(2) By auto Garbage collecting it takes away an opportunity for developers to
optimize garbage collecting and auto Garbage collecting can be seen as a
constraint not a benefit.

In the most part it is a benefit because it simplifies programming in Java and


is probably more efficient at garbage collecting than self regulated Garbage
collecting, unless people spent time researching the best way to garbage collect.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

20

Garbage collection concerns objects with dynamic extent (allocated with a


new statement in these languages). Java uses various techniques to automatically
discover when these objects are no longer referred to, and to reclaim them. In
contrast, C++ programmers manually specify where an object with dynamic extent
is to be reclaimed by coding a delete statement.
Arrays in Java
When there is a need to use many variables then we there is a big problem
because we will conflict with name of variables so that in this situation where we
wants to operate on many numbers then we can use array.
Arrays are set of elements having same data type or we can say that arrays
are collection of elements having same name and same data type but always
remember arrays are always
Start from its index value and the index of array is start from 0 to n-1.
Suppose we wants to access 5th element of array then we will use 4th element
because arrays are start from 0 and arrays are always stored in continuous memory
locations the number of elements and types of array are identified by subscript of
array elements. The various types of array those are provided by java as follows:1) single dimensional array:- These are mostly used when we wants to declare
number of elements single dimensional arrays are used for using many elements
and they are declared with single bracket like int a [] etc. The bracket will specify
the size of array elements means how many array elements are declared and used
for accessing or using a variable we have to specify the index value in the sub
script or in bracket of array variable.
The [] is used for dimensional or the sub-script of the array that is generally
used for declaring the elements of the array for accessing the element from the
array we can use the subscript of the array like this
a[3]=100
So there is only the single bracket then it is called as single dimensional array
The syntax for declaring array elements in java is as follows.
int a[]=new int[5]

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

21

Note the new keyword this is a special operator which is useful for creating
new memory which is continuous in nature and the new keyword is also creating
for memory for number of elements that is specified in single bracket.
2) two dimensional array:- the two dimensional array elements are used when we
wants to perform the operation in matrix forms the two dimensional arrays are used
for creating matrix and displaying array elements in the form of rows and columns
the total elements of arrays will be calculated by multiplying the elements of rows
and columns like int a[3][3]. That is 9 elements will be used by array these are
called as two dimensional because they use two brackets.
int a[3][3]
So this is the example of the two dimensional array in this first 3 represents
the total number of rows and the second elements represents the total number of
columns the total number of elements are judge by multiplying the numbers of
rows * number of columns in the array in the above array the total number of
elements is 9.
The two dimensional arrays are declared as follows:int a[][]=new int[3][3]
String:- Like an integer characters are also be in the array the array of characters
are called as the strings they are generally used for representing the strings in
java string is also array and also a class .we know that when collection of
characters are called as string in java for creating an string array you will use as
follows:String s[]=new String[10];
Here is the s is an array of type string means it can accept only 10 characters
but if you will use string as then:String s==new String(welcome to strings)
s is an object of class string and now you can use any method from string class the
various string methods those are reside in string class are :

toLowercase:- for converting a string into small letters or in small cases


toUppercase:- for converting a string into upper letters or in upper cases.
length:- for calculating the number of characters in a string.
trim:- for removing both left and right side spaces.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

22

charAt:- for finding aat the position.


indexOf:- for finding the position of a character in a string.
substring:- for extracting a string from a string.
replace:- for replacing a character in the string.
compareTo:- for comparing a string with another,
concat:- for joining two strings and making a single string.
Control Statements
The control statement are used to control the flow of execution of the program .
This execution order depends on the supplied data values and the conditional logic.
Java contains the following types of control statements:

Selection Statements
Repetition Statements
Branching Statements
Selection statements:
1. If Statement:
This is a control statement to execute a single statement or a block of code,
when the given condition is true and if it is false then it skips if block and rest code
of program is executed.
if(conditional_expression)
{
<statements>;
...;
...;
}
Example: If n%2 evaluates to 0 then the "if" block is executed. Here it evaluates to
0 so if block is executed. Hence "This is even number" is printed on the screen.
int n = 10;
if(n%2 = = 0)
{
System.out.println("This is even number");
}
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

23

2. If-else Statement:
The "if-else" statement is an extension of if statement that provides another
option when 'if' statement evaluates to "false" i.e. else block is executed
if "if" statement is false.
if(conditional_expression){
<statements>;
...;
...;
}
else{
<statements>;
....;
....;
}
Example: If n%2 doesn't evaluate to 0 then else block is executed. Here n%2
evaluates to 1 that is not equal to 0 so else block is executed. So "This is not even
number" is printed on the screen.
int n = 11;
if(n%2 = = 0)
{
System.out.println("This is even number");
}
else
{
System.out.println("This is not even number");
}
3. Switch Statement:
This is an easier implementation to the if-else statements. The
keyword "switch" is followed by an expression that should evaluates to byte, short,
char or int primitive data types only. In a switch block there can be one or more
labeled cases. The expression that creates labels for the case must be unique. The
switch expression is matched with each case label. Only the matched case is
executed, if no case matches then the default statement (if present) is executed.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

24

switch(control_expression)
{
case expression 1:
<statement>;
case expression 2:
<statement>;
...
...
case expression n:
<statement>;
default:
<statement>;
}//end switch
Example: Here expression "day" in switch statement evaluates to 5 which matches
with a case labeled "5" so code in case 5 is executed that results to
output "Friday" on the screen.
int day = 5;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thrusday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

25

break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid entry");
break;
}
Repetition Statements:
1. while loop statements:
This is a looping or repeating statement. It executes a block of code or statements
till the given condition are true. The expression must be evaluated to a Boolean
value. It continues testing the condition and executes the block of code. When the
expression results to false control comes out of loop.
while(expression)
{
<statement>;
...;
...;
}
Example: Here expression i<=10 is the condition which is checked before entering
into the loop statements. When i is greater than value 10 control comes out of loop
and next statement is executed. So here i contains value "1" which is less than
number "10" so control goes inside of the loop and prints current value of i and
increments value of i. Now again control comes back to the loop and condition is
checked. This procedure continues until i becomes greater than value "10". So this
loop prints values 1 to 10 on the screen.
int i = 1;
//print 1 to 10
while (i <= 10)
{
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

26

System.out.println("Num " + i);


i++;
}
2. do-while loop statements:
This is another looping statement that tests the given condition past so you can say
that the do-while looping statement is a past-test loop statement. First, do block
statements are executed then the condition given in while statement is checked. So
in this case, even the condition is false in the first attempt, do block of code is
executed at least once.
do{
<statement>;
...;
...;
}while (expression);
Example: Here first do block of code is executed and current value "1" is printed
then the condition i<=10 is checked. Here "1" is less than number "10" so the
control comes back to do block. This process continues till value of i becomes
greater than 10.
int i = 1;
do
{
System.out.println("Num: " + i);
i++;
}while(i <= 10);
3. for loop statements:
This is also a loop statement that provides a compact way to iterate over a range of
values. From a user point of view, this is reliable because it executes the statements
within this block repeatedly till the specified condition is true.
for (initialization; condition; increment or decrement)
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

27

{
<statement>;
...;
...;
}
initialization: The loop is started with the value specified.
condition: It evaluates to either 'true' or 'false'. If it is false then the loop is
terminated.
increment or decrement: After each iteration, value increments or decrements.
Here num is initialized to value "1", condition is checked whether num<=10.
If it is so then control goes into the loop and current value of num is printed. Now
num is incremented and checked again whether num<=10.If it is so then again it
enters into the loop. This process continues till num>10. It prints values 1 to10 on
the screen.
for (int num = 1; num <= 10; num++)
{
System.out.println("Num: " + num);
}
Branching Statements:
break statement:
The break statement is a branching statement that contains two forms: labeled
and unlabeled. The break statement is used for breaking the execution of a loop
(while, do-while and for). It also terminates the switch statements.
break; // breaks the innermost loop or switch statement.
break label; // breaks the outermost loop in a series of nested loops.
continue statement:
This is a branching statement that are used in the looping statements (while, dowhile and for) to skip the current iteration of the loop and resume the next
iteration.
continue;
return statement:
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

28

It is a special branching statement that transfers the control to the caller of


the method. This statement is used to return a value to the caller method and
terminates execution of method. This has two forms: one that returns a value and
the other cannot return. The returned value type must match the return type of
method.
return;
return values;
return; //This returns nothing. So this can be used when method is declared with
void return type.
return expression; //It returns the value evaluated from the expression.

public static void main(Strings args[])


static allows main() to be called without having to instantiate a particular instance
of class.
void does not return any value.
main() is the method where java application begins.
String args[] receives any command line arguments during runtime.
System is a predefined class that provides access to the system.
out is output stream connected to console.
println displays the output.
Java Variables
A variable is a place in memory where we can store a value. The Java
programming language defines the following kinds of variables :
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

29

Instance Variables (Non-Static Fields):Technically speaking, objects store


their individual states in "non-static fields", that is, fields declared without the
static keyword. Non-static fields are also known as instancevariables because their
values are unique to each instance of a class (to each object, in other words); the
currentSpeed of one bicycle is independent from the currentSpeed of another.

Class Variables (Static Fields): A class variable is any field declared with the
static modifier; this tells the compiler that there is exactly one copy of this variable
in existence, regardless of how many times the class has been instantiated. A field
defining the number of gears for a particular kind of bicycle could be marked as
static since conceptually the same number of gears will apply to all instances. The
code static int numGears = 6; would create such a static field. Additionally, the
keyword final could be added to indicate that the number of gears will never
change.

Local Variables: Similar to how an object stores its state in fields, a method
will often store its temporary state in local variables. The syntax for declaring a
local variable is similar to declaring a field (for example, int count = 0;). There is
no special keyword designating a variable as local; that determination comes
entirely from the location in which the variable is declared which is between the
opening and closing braces of a method. As such, local variables are only visible to
the methods in which they are declared; they are not accessible from the rest of the
class.
Difference between call by value and call by reference
Call by Value:
When values of built in types are passed as arguments to a function, it is known as
Call by value. The changes made to formal parameters in the called function are
not reflected in the actual arguments class.
Call by Reference:
In this approach, an object is passed as an argument, which is assigned to an object
reference are directly reflected to actual argument.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

30

Java Constructor
Initializing a variable is considered very helpful while making programs. We
can initialize variables of primitive types at the time of their declarations. For
example:
int a = 10;
In Object Oriented Programming language (OOPL) like Java, the need of
initialization of fields of a new object is even more common. We have already done
this using two approaches.
In the first approach, we used a dot operator to access and assign values to
the instance variables individually for each object. However, it can be a tedious job
to initialize the instance variables of all the objects individually. Moreover, it does
not promote data hiding.
r1.length = 5;
r2.length = 7;
where rl, r2 are objects of a Rectangle class.
In another approach, we made use of method setData() to assign values to
fields of each object individually. But it would have to be called explicitly for each
object. This would become inconvenient if the number of objects are very large.
rl.setData(5,6);//sets length and breadth of rl Rectangle object
r2.setData(7,8);
The above two approaches does not simulate the problem properly. A better
solution to the above problem is to initialize values to the object at the time of its
creation in the same way as we initialize values to a variable of primitive data
types. This is accomplished using a special method in Java known

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

31

as constructor that enables an object to initialize itself at the time of its creation
without the need to make separate call to the instance method.
A constructor is a special method that is called whenever an object is created
using the new keyword. It contains a block of statements that can be used to
initialize instance variables of an object before the reference to this object is
returned by new. A constructor does look and feel a lot like a method but it is
different from a method generally in two ways.
A constructor always has the same name as the class whose instance
members they initialize. The constructor does not have a return type, nor even
void. It is because the constructor is automatically called by the compiler whenever
an object of a class is created.
The syntax for constructor is as follows.
ConstructorName([parameterList])
{
//Constructor Body
}
Here, the ConstructorName is same as the class name it belongs to. The
parameterList is the list of optional zero or more parameter(s) that is specified after
the classname in parentheses. Each parameter specification, if any, consists of a
type and a name which are separated from each other by commas.
Now let us consider a program
// use of Constructor
class Rectangle
{
int length;
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

32

int breath;
Rectangle()
{
length = 5;
breath = 6;
}
int area()
{
int rectArea = length * breath;
return rectArea;
}
}
class Constructordemo
{
public static void main(String args[])
{
Rectangle firstRect = new Rectangle();
System.out.println(Area of Rectangle = + firstrect.area());
}
}
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

33

Rectangle firstRect = new Rectangle();


which is executed, the new operator creates a new but uninitialized object of the
class. Then the constructor (Rectangle () is called and the statements in its body
are executed. As a result, the instance variables length and breadth of object
firstRect will be initialized to integer literals 5 and 6 respectively.
Then the address of the allocated Rectangle object is returned and assigned to the
reference variable firstRect. This method of initializing instance variable(s) of an
object(s) using constructor is very simple and concise as there is no need to
explicitly call the method for each object separately.
There are three types of Constructor as follows:1) Default Constructor:- Default Constructor is also called as Empty Constructor
which has no arguments and is automatically called when we creates the object of
class but remember name of Constructor is same as name of class.
2) Parameterized Constructor:- This is another constructor which has some
Arguments and same name as class name but it uses some Arguments So For this
We have to create object of Class by passing some Arguments at the time of
creating object with the name of class.
3) Copy Constructor:- This is also Another type of Constructor. InConstructor object
of another Constructor is passed As name Suggests you Copy means Copy values
of another Class object This is used for Copying the values of class object into an
another object of class So For Calling Copy Constructor We have to pass the name
of object whose values we wants to Copying .
Destructor:
1. It is a member function whose name is same as the class. But preceeded by a ~
(tilde) symbol.
2. It has no return type.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

34

3. It cannot have parameters.


4. It is implicitly called when object is no longer required.
5. It is used to release the memory and close files and database conversions.
(No Destructor concept in java)
Polymorphism
It gives us the ultimate flexibility in extensibility. The ability to define more than
one function with the same name is called Polymorphism. In Java and C++, there
are two type of polymorphism:
Compile time polymorphism (overloading)
Runtime polymorphism (overriding)
When you override methods, JVM determines the proper methods to call at the
programs run time, not at the compile time. Overriding occurs when a class
method has the same name and signature as a method in parent class.
Overloading occurs when several methods have same names with
Overloading is determined at the compile time.
Different method signature and different number or type of parameters.
Same method signature but different number of parameters.
Same method signature and same number of parameters but of different type
Example of overloading
int add(int a,int b)
float add(float a,int b)
float add(int a ,float b)
void add(float a)
int add(int a)
void add(int a)

//error conflict with the method int add(int a)

Example: Overloading
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

35

class BookDetails
{
String title;
String publisher;
float price;
setBook(String title)
{}
setBook(String title, String publisher)
{}
setBook(String title, String publisher,float price)
{}
}
Example: Overriding
class BookDetails
{
String title;
setBook(String title)
{}
}
class ScienceBook extends BookDetails
{
setBook(String title)
{}
//overriding
setBook(String title, String publisher,float price)
{} //overloading
}
Inheritance
It is a compile-time mechanism in Java that allows you to extend a class
(called the base class or superclass) with another class (called the derived
class or subclass). In Java, inheritance is used for two purposes:
Single Inheritance
Single inheritance is damn easy to understand. When a class extends another
one class only then we call it a single inheritance. The below flow diagram shows
that class B extends only one class which is A. Here A is a parent class of B and B
would be a child class of A.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

36

Example:
class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
Multiple Inheritance
Multiple Inheritance refers to the concept of one class extending (Or
inherits) more than one base class. The inheritance we learnt earlier had the
concept of one base class or parent. The problem with multiple inheritance is that
the derived class will have to manage the dependency on two base classes.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

37

Note 1: Multiple Inheritance is very rarely used in software projects. Using


Multiple inheritance often leads to problems in the hierarchy. This results in
unwanted complexity when further extending the class.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not support
Multiple inheritance. Multiple Inheritance is supported in C++.
Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one
can inherit from a derived class, thereby making this derived class the base class
for the new class. As you can see in below flow diagram C is subclass or child
class of B and B is a child class of A.

Example:

class X
{
public void methodX()
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

38

{
System.out.println("Class X method");
}
}
class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}
Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below
example class B,C and D inherits the same class A. A is parent class (or base
class) of B,C & D

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

39

Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a combination
of Single and Multiple inheritances. A typical flow diagram would look like below.
A hybrid inheritance can be achieved in the java in a same way as
multiple inheritance can be. By using interfaces you can have multiple as well
as hybrid inheritance in Java

super keyword
The super is java keyword. As the name suggest super is used to access the
members of the super class. It is used for two purposes in java. The first use of
keyword super is to access the hidden data variables of the super class hidden by
the sub class.
Suppose class A is the super class that has two instance variables as int a and
float b. class B is the subclass that also contains its own data members named a and
b. then we can access the super class (class A) variables a and b inside the subclass
class B just by calling the following command.
super.member;
Here member can either be an instance variable or a method. This form of super is
most useful to handle situations where the local members of a subclass hide the
members of a super class having the same name. The following example clarifies
all the confusions.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

40

class A{
int a;
float b;
void Show()
{
System.out.println("b in super class: " + b);
}
}
class B extends A{
int a;
float b;
B( int p, float q){
a = p;
super.b = q;
}
void Show(){
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
public static void main(String[] args){
B subobj = new B(1, 5);
subobj.Show();
}
}
Use of super to call super class constructor: The second use of the keyword
super in java is to call super class constructor in the subclass. This functionality
can be achieved just by using the following command.
super(param-list);
Here parameter list is the list of the parameter requires by the constructor in the
super class. super must be the first statement executed inside a super class
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

41

constructor. If we want to call the default constructor then we pass the empty
parameter list. The following program illustrates the use of the super keyword to
call a super class constructor.
c=r;
class B extends A{
int d;
B(int l, int m, int n, int o){
super(l,m,n);
d=o;
}
void Show(){
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
public static void main(String args[]){
B b = new B(4,3,8,7);
b.Show();
}
}
Keyword this
Pointer this is used when a method has to refer to an object that has
invoked it. 'this' pointer can be used inside any method to refer to
the current object. This means that this is always used as a reference to the object
on which the method was invoked. We can use this anywhere as reference to an
object of the current class type is permitted. Since, it is illegal in Java to declare
two local variables with the same name inside the same or enclosing scopes; we
can have local variables, which include formal parameters to methods, which may
overlap with the names of the class instance variables. However, when a local
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

42

variable has the same name as an instance variable, the local variable hides the
instance variable.
For example, here is another version of Employee( ), which uses emp_id and
emp_salary for parameter names and then uses this to access the instance variables
by the same name:
Employee(double emp_id, double emp_salary)
{
this.emp_id = emp_id;
this.emp_salary =.emp_salary;
}
The use of this in such a context can sometimes be confusing, and some
programmers are careful not to use local variables and formal parameter names
that hide instance variables. But other programmers believe that it is a good
convention to use the same names for clarity, and use this to overcome the instance
variable hiding. It is a matter of taste which approach you adopt. Although this is
of no significant value in the examples just shown, it is very useful in certain
situations.

Access Modifiers
Access modifiers specify who can access them. There are four access
modifiers used in java. They are public, private, protected, no modifier (declaring
without an access modifier).
Using no modifier is also sometimes referred as package-private or
default or friendly access. Usage of these access modifiers is restricted to two
levels. The two levels are class level access modifiers and member level access
modifiers.
I) Class level access modifiers (java classes only)
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

43

Only two access modifiers is allowed, public and no modifier


If a class is public, then it CAN be accessed from ANYWHERE.
If a class has no modifier, then it CAN ONLY be accessed from same package.
II) Member level access modifiers (java variables and java methods)
All the four public, private, protected and no modifier is allowed.

public and no modifier the same way as used in class level.


private members CAN ONLY access.
protected CAN be accessed from same package and a subclass existing in
any package can access.
For better understanding, member level access is formulated as a table:

Access Modifiers

Same Class Same Package

Subclass Other packages

public

protected

no access modifier

private

First row {public Y Y Y Y} should be interpreted as:

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

44

Y A member declared with public access modifier CAN be accessed by the


members of the same class.
Y A member declared with public access modifier CAN be accessed by the
members of the same package.
Y A member declared with public access modifier CAN be accessed by the
members of the subclass.
Y A member declared as public CAN be accessed from Other packages.
Second row {protected Y Y Y N} should be interpreted as:
Y A member declared with protected access modifier CAN be accessed by the
members of the same class.
Y A member declared with protected access modifier CAN be accessed by the
members of the same package.
Y A member declared with protected access modifier CAN be accessed by the
members of the subclass.
N A member declared with protected access modifier CANNOT be accessed by
the members of the Other package.
Difference between final, finally and finalize().

final constant declaration.

finally The finally block always executes when the try block exits, except
System.exit(0) call. This ensures that the finally block is executed even if an
unexpected exception occurs. But finally is useful for more than just exception
handling it allows the programmer to avoid having cleanup code accidentally
bypassed by a return, continue, or break. Putting cleanup code in a finally block is
always a good practice, even when no exceptions are anticipated.

finalize() method helps in garbage collection. A method that is invoked before


an object is discarded by the garbage collector, allowing it to clean up its state.
Should not be used to release non-memory resources like file handles, sockets,
database connections etc because Java has only a finite number of these resources
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

45

and you do not know when the garbage collection is going to kick in to release
these non-memory resources through the finalize() method.
Vectors:We know that Arrays are very useful when there is a need to use number of
variables But There is a problem with Array they use only single data type or The
Elements of array are always same type for avoiding this problem vectors are used.
These are also collection of elements those are object data type for using vectors
we have to import java.util package these are also called as dynamic array of object
data type.
But always remember vectors doesnt support primitives data types like int, float,
char etc. for creating a vector, vector class will be used which is reside in javas
utility package

Various Methods those are used with vectors:1.addElement():- For Inserting an element into Vector
2.elementAt():- Gives the name of Char at position
3.size():- Give us Size of Number of Elements in Vector
4.copyInto():- For Copying All Elements into an Array
5.insertElementAt(ele,n):- For Inserting an Element ele into the nth Position
Command Line Arguments:These are parameters that are supplied to the application program at the time
of invoking it for execution. We can write Java programs that can receive and use
the arguments provided in the command line.
e.g. public static void main (String args[]). args is declared as an array of
strings and arguments provided in the command line are passed to the array args as
its elements.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

46

A Java application can accept any number of arguments from the command
line. This allows the user to specify configuration information when the application
is launched.
The user enters command-line arguments when invoking the application and
specifies them after the name of the class to be run. For example, suppose a Java
application called Sort.java sorts lines in a file. To sort the data in a file named
friends.txt, a user would enter:
java Sort friends.txt
When an application is launched, the runtime system passes the commandline arguments to the application's main method via an array of Strings. In the
previous example, the command-line arguments passed to the Sort application in
an array that contains a single String: "friends.txt".
The Echo example displays each of its command-line arguments on a line
by itself
public class Echo {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}

The following example shows how a user might run Echo. User input is in italics.
java Echo Drink Hot Java
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

47

Drink
Hot
Java
Note that the application displays each word Drink, Hot, and Java on a
line by itself. This is because the space character separates command-line
arguments.
To have Drink, Hot, and Java interpreted as a single argument, the user
would join them by enclosing them within quotation marks.
Static members
We know in Class data members and Members Functions are Instantiated,
When Object of Class is Created New Memory is Allocated by Each Object .So for
Avoiding this New Memory Each Time Creation, We Uses Static Data then data
will be Common to all and the static data is used without creating an object of class
Static data is used without creating an object Instead with name of class.
The Members those are declared as Static are Known as Static Members are
associated with the class itself rather than individual objects Main Advantage of
Static variables is java creates only one Copy of Static data Members in Memory
Like Data Members Methods May also be Static and they Called without object of
class.
Function overloading (Compile Time Polymorphism)
This in Java is when you have the several methods with same name and
different parameters and compiler has to decide how to select which method has to
run based on the arguments hence the name Compile time polymorphism or
method overloading.
Overloaded methods may or may not have different return types. When java
encounters a call to an overloaded method, it simply executes the version of the
method whose parameters match the arguments used in the call.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

48

However, this match need not always be exact. In some cases javas
automatic type conversions can play a role in overload resolution. Java will employ
its automatic type conversion only if no exact match is found.
The important points to note:
A difference in return type only is not sufficient to constitute an overload
and is illegal. You should restrict your use of overloaded method names to
situations where the methods really are performing the same basic function with
different data.
The language treats methods with overloaded names as totally different
methods and as such they can have different return types. However, since
overloaded methods perform the same job with different data sets, they should
produce same return type normally. There is one particular condition, however,
under which it is sensible to define different return types. This is the situation
where the return type is derived from the argument type and is exactly parallel with
the arithmetic operators.
Overloaded methods may call one another simply by providing a normal
method call with an appropriately formed argument list.
Wrapper Classes:We know that vectors cant handle primitives data types like int, float ,char,
long so that primitives data type may be converted into object data types by using
wrapper classes those are contained in java.lang packages the various wrapper
classes are :1) Integer
2) Float
3) Character
These are used when a list contains elements those are string in nature and
we wants to convert them into primitives data type then we have to use wrapper
class wrapper classes will first convert the String into the object data type either it
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

49

may be int, float ,char etc and after that we will be able to convert the object data
type into primitives data type many times we were using wrapper class like
integer.parseInt(123) this is also a wrapper class (Integer) for converting a String
into int data type.
Difference between Interface and Abstract Class
Main difference is methods of a Java interface are implicitly abstract and cannot
have implementations. A Java abstract class can have instance methods that
implement a default behavior.
Variables declared in a Java interface is by default final. An abstract class may
contain non-final variables.
Members of a Java interface are public by default. A Java abstract class can have
the usual flavors of class members like private, protected, etc.
Java interface should be implemented using keyword implements; A Java
abstract class should be extended using keyword extends.
An interface can extend another Java interface only, an abstract class can extend
another Java class and implement multiple Java interfaces.
A Java class can implement multiple interfaces but it can extend only one abstract
class.
Interface is absolutely abstract and cannot be instantiated; A Java abstract class
also cannot be instantiated, but can be invoked if a main() exists.
In comparison with java abstract classes, java interfaces are slow as it requires
extra indirection.
Difference between Abstraction and Encapsulation
Abstraction focuses on the outside view of an object (i.e. the interface)
Encapsulation (information hiding) prevents clients from seeing its inside view,
where the behavior of the abstraction is implemented.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

50

Abstraction solves the problem in the design side while Encapsulation is the
Implementation.
Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about
grouping up your abstraction to suit the developer needs.
Dynamic Binding
In java, base class reference can be assigned objects of sub class when
methods of sub class object are called through base classs reference.The mapping /
binding of function calls to respective function takes place after running the
program, at least possible moment. This kind of binding is known as latebinding
or dynamic binding or runtime polymorphism.
class A
{
public void display()
{}
}
class B extends A
{
public void display()
{}
}
class C extends A
{
public void display()
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

51

{}
}
class DispatchDemo
{
psvm (String args[])

{
A ob1= new A();
B ob2 = new B();
C ob3 = new C();
A r;
r=ob1;
r.display();
r=ob2;
r.display();
r=ob3;
r.display();
}
}
In the above programs, the statement r.display( ), calls the display() method
and based on the object. That has been assigned to base class reference. i.e. r. But
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

52

the mapping / binding as to which method is to be invoked is done only at run


time.
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and
type signature as a method in its superclass, then the method in the subclass is said
to override the method in the superclass.
When an overridden method is called from within a subclass, it will always
refer to the version of that method defined by the subclass. The version in the
superclass will be hidden. If you wish to access the superclass version of an
overridden method, you can do so by using super.
In order for any particular method to override another correctly:
The return type, method name, type and order of arguments must be identical to
those of a method in a parent class.
The accessibility must not be more restrictive than original method.
The method must not throw checked exceptions of classes that are not
possible for the original method.
Rules for method overriding:
The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in
the original overridden method in the superclass.
The access level cannot be more restrictive than the overridden method's access
level. For example: if the superclass method is declared public then the
overridding method in the sub class cannot be either private or protected.
Instance methods can be overridden only if they are inherited by the subclass.
A method declared final cannot be overridden.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

53

A method declared static cannot be overridden but can be re-declared.


If a method cannot be inherited, then it cannot be overridden.
A subclass within the same package as the instance's superclass can override
any superclass method that is not declared private or final.
A subclass in a different package can only override the non-final methods
declared public or protected.
An overriding method can throw any uncheck exceptions, regardless of whether
the overridden method throws exceptions or not. However the overriding
method should not throw checked exceptions that are new or broader than the
ones declared by the overridden method. The overriding method can throw
narrower or fewer exceptions than the overridden method.
Constructors cannot be overridden.
Method Overloading
Polymorphism in java can be implemented by using method overloading &
method over riding. Method overloading is a process of defining many methods
with the same name. But parameter must be different. A method acts upon different
sets of parameters. But, basic operation is same.
Advantages:
When many methods are performing same operations, it would be easy to call
same method with different types of arguments.
We can override many methods and remember them for the same operation.
Packages
The programmer can easily find them, by knowing their position with their
set of task. The common types of classes and interfaces are placed in the same
package. The type name (class or interface) must not conflict with other package
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

54

type name, because at the same time if both packages are in use, compiler must not
confuse.
There must not be any restriction to access any type from another type
within the same package. But assign the restricted access from types outside the
package.
Defining a Package
Now as we know, a package is a collection of classes and interfaces. A
package does not contain the source code of any type of Java file. Each Java source
code file is a collection of one or more classes, or one or more interfaces with their
members. After compilation, a separate class file is created for individual class or
interface, either these are part of one Java file or stored in individual file. That
class file (byte code) is placed in a particular related package using a package
declaration.
package<fully qualified package name>;
The package declaration statement must be the first statement of the source
file, and at least one package declaration must be in a source file. The package
name is stored in the byte code (class file). The dot (.) notation is used to
distinctively spot (identify) the package name in the package hierarchy. One
naming convention for a package is that, package name is written in all lowercase.
It will escape the confliction with classes and interfaces name.
package mypkg;
Here, mypkg is the package name. Moreover a file belonging to same
package can include the same package name.You can also create a hierarchy of
packages, i.e. package within a package called subpackage for further classification
and categorization of classes and interfaces.
package mypkg.mypkg2.mypkg3;
Here, mypkg2 is a subpackage in package mypkg, mypkg3 is a subpackage
in subpackage mypkg2. If there is no package declaration in a source file, then the
compiled file is stored in the default package (unnamed package), and that is the
current working directory.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

55

In the above package hierarchy class A is identified by the name


pckl.pck2.pck3.A .This is called the fully qualified type name of the class (type). A
fully qualified type name (name includes class or interface name) is comprises of
fully qualified package name. According to above hierarchy pck1.pck2.pck3 is the
fully qualified package name.
Packaging up Classes
Now, you must have a model or a blue print of package in your mind. Let's
take one example how to create package with keeping in mind all the concepts that
we have discussed in last sections.
package pck1;
class Student
{
private int rollno;
private String name;
private String address;
public Student(int rno, String sname, String sadd)
{
rollno = rno;
name = sname;
address = sadd;
}
public void showDetails()
{
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

56

System.out.println("Roll No :: " + rollno);


System.out.println("Name :: " + name);
System.out.println("Address :: " + address);
}
}
public class DemoPackage
{
publ~c static void main(String ar[])
{
Student st[]=new Student[2];
st[0] = new Student (1001,"Alice", "New York");
st[1] = new Student(1002,"BOb","Washington");
st[0].showDetails();
st[1].showDetails();
}
}
There are two ways to create package directory as follows:

1. Create the folder or directory at your choice location with the same name as
package name.
2. Compile the file with following syntax.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

57

javac -d <target location of package> sourceFile.java

The above syntax will create the package given in the sourceFile at
the <target location of pacakge> if it is not yet created. If package already exist
then only the .class (byte code file) will be stored to the package given
in sourceFile.

Steps to compile the given example code:

Compile the code with the command on the command prompt.


javac -d DemoPackage.java
The command will create the package at the current location with the name pck1,
and contains the file DemoPackage.class and Student.class
To run write the command given below
java pckl.DemoPackage
Note: The DemoPackate.class is now stored in pck1 package. So that we've to
use fully qualified type name to run or access it.
Output:
Roll No :: 1001
Name :: Alice
Address :: New York
Roll No :: 1002
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

58

Name :: Bob
Address :: Washington
If you put multiple types in a single source file, only one can be public, and
it must have the same name as the source file. For example, you can define public
class Circle in the file Circle.java, define public interface Draggable in the file
Draggable.java, define public enum Day in the file Day.java, and so forth.
You can include non-public types in the same file as a public type (this is
strongly discouraged, unless the non-public types are small and closely related to
the public type), but only the public type will be accessible from outside of the
package. All the top-level, non-public types will be package private .
Difference between Application program and Applet program
Java is a general-purpose, object-oriented programming language. We can develop
two types of Java programs:
Stand-alone Applications: Programs written in Java to carry out certain tasks on a
stand-alone local computer. Executing stand-alone java programs involves two
steps
o Compiling through javac compiler.
o Executing the byte code using java interpreter.
Web Applets: Programs that are developed for Internet based applications. An
applet located on a distant computer (Server) can be downloaded via Internet and
executed on a local computer (Client) using a java capable browser.
From the users point of view, Java applications can be compared to compiled C
programs since they are started from a command line just like any compiled
program would be started. However, there is a major difference: Java applications,
as well as applets, are interpreted. Applications are started on the command-line by
calling the Java Interpreter with the name of the application as an argument.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

59

Applets, in contrary to applications, are small programs which can be included


in web pages and run inside the user's browser. Alternatively, applets can be run in
the applet viewer that comes with the JDK, which has advantages for debugging.
Types of Errors
Many Times a Program has to face some errors An Error is an Situation
when a Compiler either doesnt Execute statements or either Compiler will
Produce Wrong Result .Various types of Errors are there like : Syntax Error or Compile Time Error:- The Compile Time Error or Syntax are
denoted by compiler at the time of compilation The Compile Time Errors include
Missing Semicolon, missing parenthesis , used undefined variable etc These are all
Compile Time Errors
Run Time Error:- Run Time Errors are Caught by Interpreter or at the time of
Execution when we Execute out Program the Error is Encountered Run Time Error
includes operations those are not possible but a user trying to do them .At that
Situation error may occurred Like Divide a Number by zero, Accessing Element of
Array Which Doesnt Exist Trying to Open a File that doesnt Exists. All these are
Examples of Run Time Errors.
Logical Error:- These types of Error doesnt halt or Stops the Execution of Java
Program but they produce wrong Results But there is no any syntax missing or
either any Operation which is not possible but his type of Error is occurred when
these is some mistake in logic of user Like he wants to Multiply two Numbers and
he puts Addition Mark instead of Multiplication then it is called as Logical Error.
Exception Handling
Exception is a condition which is responsible for occurrence of error like
divide by zero is an condition that never be possible so we can call it an exception
which halts or stops the execution of program in java there is an exception class
which is responsible for producing an error message when an error has occurred.
When an exception has occurred then compiler will never reach to the code
that is placed after the block which contains an error. So that there is special
mechanism given by java for handling exceptions when as exception has occurred
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

60

then the compiler will generate an exception code to an exception class and with
the help of exception object. So if we wants to execute statements then we have to
handle exception forhandling exceptions java provides us special mechanism
which is called as exception handling mechanism java provide following methods
for handling exceptions those are occurred in a program
Exception handlers:Java provides us various exception handlers for handling exceptions the
various types of exception handlers are:
1) try:- Code which we have doubt that it could creates an exception is placed in
the try block the try block contains that code which contains any invalid operations
or the code that may generates an error
2) catch:- Every try block must have an at least one try block when an exception
has occurred in the try block then the error code is just passed to the catch block
which will handle the particular exception and gives appropriate message to the
A try block may have multiple catch blocks but one try block may contains
at least one catch block because in the user code there is the possibility of
occurring of two or more errors and a user code can contains code which have
multiple operations like a user contains the code which contains division of array
elements then it is possible of occurring array index out of bound exception and
either it may generate arithmetic exception so there is the possibility of occurrence
of multiple catch blocks of one try block
3) finally:- This is the third most popular exception handler which is used for
performing the code that may cause exceptions or not means finally block must be
executed either the exception may occurred or not or the code that contains
important code that must be executed in any situation either an exception occurred
or not it executed its code it contains code like de-allocation of memory, closing
files etc.
4) throws: - When we are throwing any exception in a method and not handling it,
then we need to use throws keyword in method signature to let caller program
know the exceptions that might be thrown by the method. The caller method might
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

61

handle these exceptions or propagate it to its caller method using throws keyword.
We can provide multiple exceptions in the throws clause and it can be used
with main() method also.
5) throw:- Java s exception handlers provides the facility for the user to creating
his own exceptions if a user wants to create his own exception then ha may use
throw keyword for creating his own error and with respective error message
Causes of exception
A java exception can be thrown only in the following three scenarios:
(1) An abnormal execution condition was synchronously detected by the java
virtual machine.
when evaluation of an expression violates the normal semantics (example:
an integer divide by zero)
an error occurs in loading or linking part of the program
when limitation on a resource is exceeded (example: using too
much memory)
(2) A throw statement was executed.
(3) An asynchronous exception occurred.
stop() of class thread was invoked an internal error has occurred in the java virtual
machine.
Types of exception classes
There are many exceptions those may be occurred when there is an error in
code of java every error may cause an exception that is specific and compiler will
understand it clearly when an exception has occurred then there is specific
exception class that will generate the error message to the user there are many
exception classes that gives the message to the user .the various types of exception
classes are as follows:Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

62

1) ArithmeticException:- this exception will occur when you are performing


wrong arithmetic operations like you are dividing a number by zero when you are
dividing a number by zero then compile gives us an error message that will be
generated by arithmetic class
2) ArrayIndexOutOfBoundsException: - this exception will occur when you are
accessing the element of an array that is doesnt exists like accessing 6 th element
out of 5 elements
3) NullPointerAssignment:- occur when performing the operations on null string
4) InvalidTypeCasting:- when you are converting a data type into type into the
invalid data type
Multithreading
The Java language and its run-time system was designed keeping in mind
about multithreading. The run-time system depend upon multithreading. Java
provides asynchronous thread environment, this helps to increase the utilization
of CPU.
Multithreading is best in all cases in contrast with single-thread model.
Single-thread system uses an approach of event loop with polling. According to
this approach a single thread in the system runs in an infinite loop. Polling the
mechanism, that selects a single event from the event queue to choose what to do
next. As the event is selected, then event loop forwards the control to the
corresponding required event handler. Nothing else can be happened, until the
event handler returns. Because of this CPU time is wasted. Here, only one part of
the complete program is dominating the whole system, and preventing the system
to execute or start any other process. In single-thread model one thread blocks all
other threads until its execution completes. On other waiting or idle thread can start
and acquire the resource which is not in use by the current thread. This causes the
wastage of resources.
Life Cycle of a Thread:

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

63

New Born State


The following statement creates a new thread but does not start it thereby
leaving the thread in the state labeled "New Thread" in the diagram.
Thread myThread = new MyThreadClass();
When a thread is in the "New Thread" state, it is merely an empty Thread
object. No system resources have been allocated for it yet. Thus when a thread is in
this state, you can only start the thread or stop it; calling any other method
besides start() or stop() when a thread is in this state makes no sense and causes
an IllegalThreadStateException.
Now consider these two lines of code:
Thread myThread = new MyThreadClass();
myThread.start();
Runnable State
The start() method creates the system resources necessary to run the thread,
schedules the thread to run, and calls the thread's run() method. At this point the
thread is in the "Runnable" state. This state is called "Runnable" rather than
"Running" because the thread may not actually be running when it is in this state.
Many computers have a single processor making it impossible to run all
"Runnable" threads at the same time. So, the Java runtime system must implement
a scheduling scheme that shares the processor between all "Runnable". However,
for most purposes you can think of the "Runnable" state as simply "Running".
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

64

When a thread is running--it's "Runnable" and is the current thread--the


instructions in its run() are executing sequentially.
Blocked State (Not Runnable)
A thread enters the "Not Runnable" state when one of these four events occur:
someone calls its suspend() method
someone calls its sleep() method
the thread uses its wait() method to wait on a condition variable
For example, the bold line in this code snippet
Thread myThread = new MyThreadClass();
myThread.start();
try {
myThread.sleep(10000);
} catch (InterruptedException e){
}
puts myThread to sleep for 10 seconds (10,000 milliseconds). During those 10
seconds, even if the processor became available myThread would not run. After the
10 seconds are up, myThread becomes "Runnable" again and now if the processor
became available myThread would run.
For each of the "entrances" into the "Not Runnable" state listed above, there
is a specific and distinct escape route that returns the thread to the "Runnable"
state. An escape route only works for its corresponding "entrance". For example, if
a thread has been put to sleep, then the specified number of milliseconds must
elapse before the thread becomes "Runnable" again. Calling resume() on a sleeping
thread has no effect.
The following indicates the escape route for every entrance into the "Not
Runnable" state.
If a thread has been put to sleep, then the specified number of milliseconds must
elapse.
If a thread has been suspended, then someone must call its resume() method.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

65

If a thread is waiting on a condition variable, whatever object owns the variable


must relinquish it by calling either notify() or notifyAll().
If a thread is blocked on I/O, then the specified I/O command must complete.
Dead State
A thread can die in two ways: either from natural causes, or by being killed
(stopped). A thread dies naturally when its run() method exits normally. For
example, the while loop in this method is a finite loop--it will iterate 100 times and
then exit.
public void run() {
int i = 0;
while (i < 100) {
i++;
System.out.println("i = " + i);
}
}
A thread with this run() method will die naturally after the loop and
the run() method completes. You can also kill a thread at any time by calling
its stop() method. This code snippet
Thread myThread = new MyThreadClass();
myThread.start();
try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException e){
}
myThread.stop();
creates and starts myThread then puts the current thread to sleep for 10 seconds.
When the current thread wakes up, the bold line in the code segment
kills myThread.
The stop() method throws a ThreadDeath object at the thread to kill it. Thus
when a thread is killed in this manner it dies asynchronously. The thread will die
when it actually receives the ThreadDeath exception.
Thread Synchronization:
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

66

When two or more threads wants to access a shared resource, then it must ensure
that the resource will be used by only one thread at an instant of time. The
mechanism of this process is called synchronization. Synchronization is the
concept of the monitor or semaphore. Monitor works as mutex and restrict to one
thread to own a monitor at a given time. As the thread acquires the lock, all the
threads that want to acquire the monitor will be suspended. As the first thread exits
from the monitor, one thread will acquire monitor from the waiting list of threads.
Synchronization of code can be in two ways, but both use synchronized keyword.
1. Using synchronized method
2. Using synchronized statement
public class SynchronizedMethod extends Object
{
private static int c = 1;
private static void print (String msg)
{
String threadName = Thread.currentThread().getName();
System.out.println(threadName + ": " + msg);
}
public static synchronized int getCount()
{
int i = c;
c++;
return i;
}
public static void main(String[] args)
{
try
{
Runnable runnable = new Runnable() { public void run() {
System.out.println("count=" + getCount());
}
};
Thread thread1 = new Thread(runnable, "Threadl");
thread1.start();
Thread.sleep(500);
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

67

Thread thread2 = new Thread(runnable, "Thread2");


thread2.start();
Thread.sleep(500);
Thread thread3 = new Thread(runnable, "Thread3");
thread3.start();
Thread.sleep(500);
Thread thread4 = new Thread(runnable, "Thread4");
thread4.start();
}
catch(Exception x )
{
}
}
}
Thread Priorities
Priority allow the scheduler to take the decision when the thread should be
allowed to run, and in which order. The higher priority threads get more CPU time
than lower priority threads. A lower priority thread can be pre-empted by higher
priority thread. The threads having equal priority get equal CPU time.
To set a thread's priority, use the setPriority() method, which belongs
to Thread class. Prototypes is as
final void setPriority(int priorityValue)
Here, priorityValue give the new priority for the calling thread. The value
of priorityValue must be within the range MIN_PRIORITY and MAX_PRIORITY.
Values of these constants are 1 and 10, respectively. A thread default priority is
NORM_PRIORITY, which is currently 5. These priorities constants are defined as
final variables within Thread.
You can get current priority value of the thread by calling the getPriority( ) method
of Thread,shown here.
final int getPriority( )
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

68

Example:
public class Main
{
public void setPrioritiesOnThreads()
{
Thread thread1 = new Thread(new TestThread(1));

Thread thread2 = new Thread(new TestThread(2));


thread1.start();
thread2.start();
try
{
thread1.join ();
thread2.join ();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
System.out.println("Done.");
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

69

}
public static void main(String[] args)
{
new Main().setPrioritiesOnThreads();
}
class TestThread implements Runnable
{
int id;
public TestThread(int id)
{
this.id = id;
}
public void run()
{
for (int i = 1; i <= 10; i++)
{
System.out.println("Thread" + id + ": " + i);
}
}
}
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

70

Applet
Applets are small Java programs that are embedded in Web pages. They can
be transported over the Internet from one computer (web server) to another (client
computers). They transform the web into rich media and support the delivery of
applications via the Internet. It is also a special Java program that can be embedded
in HTML documents. A Java applet is a Java program written in a special format to
have a graphical user interface. The graphical user interface is also called a GUI ,
and it allows a user to interact with a program by clicking the mouse, typing
information into boxes, and performing other familiar actions. With a Java applet,
GUIs are easy to create even if you've never run into such GUI before.
Life Cycle of an Applet
Various states, an applet, undergoes between its object creation and object
removal (when the job is over) is known as life cycle. Each state is represented by
a method. There exist 5 states represented by 5 methods. That is, in its life of
execution, the applet exists (lives) in one of these 5 states.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

71

These methods are known as "callback methods" as they are called


automatically by the browser whenever required for the smooth execution of the
applet. Programmer just writes the methods with some code but never calls.
Following are the methods.
1.
2.
3.
4.
5.

init() method
start() method
paint() method
stop() method
destroy() method
These methods are known as life cycle methods. These methods are defined
in java.applet.Applet class except paint() method. The paint() method is defined
in java.awt.Component class, an indirect super class of Applet.

Browser Responsibilities
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

72

The life cycle methods are called as callback methods as they are called
implicitly by the browser for the smooth execution of the applet. Browser should
provide an environment known as container for the execution of the applet.
Following are the responsibilities of the browser.
1. It should call the callback methods at appropriate times for the smooth execution of
the applet.
2. It is responsible to maintain the life cycle of the applet.
3. It should have the capability to communicate between applets, applet to JavaScript
and HTML, applet to browser etc.

Description of Life Cycle methods


Even though, the methods are called automatically by the browser, the
programmer should know well when they are called and what he can do with the
methods. Following is the schematic representation of the methods.

Brief Description of Life Cycle Methods


Following is the brief description of the above methods.
1. init(): The applet's voyage starts here. In this method, the applet object is created
by the browser. Because this method is called before all the other methods,
programmer can utilize this method to instantiate objects, initialize variables,
setting background and foreground colors in GUI etc.; the place of a constructor in
an application. It is equivalent to born state of a thread.
2. start(): In init() method, even through applet object is created, it is in inactive state.
An inactive applet is not eligible for microprocessor time even though the
microprocessor is idle. To make the applet active, the init() method calls start()
method. In start() method, applet becomes active and thereby eligible for processor
time.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

73

3. paint(): This method takes a java.awt.Graphics object as parameter. This class


includes many methods of drawing necessary to draw on the applet window. This
is the place where the programmer can write his code of what he expects from
applet like animation etc. This is equivalent to runnable state of thread.
4. stop(): In this method the applet becomes temporarily inactive. An applet can come
any number of times into this method in its life cycle and can go back to the active
state (paint() method) whenever would like. It is the best place to have cleanup
code. It is equivalent to the blocked state of the thread.
5. destroy(): This method is called just before an applet object is garbage collected.
This is the end of the life cycle of applet. It is the best place to have cleanup code.
It is equivalent to the dead state of the thread.

HTML for Applet


We cannot open an applet directly in a browser, even though, the browser is
meant to execute an applet. For every applet, a HTML file is to be written in which
we give the name and address etc. of the applet.
Following is the example code for embedding applet in a HTML file.
1 <applet code ="LifeTest.class" width ="250" height ="200">
2 </applet>
The <applet> tag
comes
with
many
attributes
of
which code, width and height are important. The other, optional, we discuss later.
The code attribute includes the name of the applet, width and height attributes give
the size of applet window in the browser, in pixels.
Applet Execution Styles
There exist two styles of running the HTML file embedding the applet.
As usual using a browser
Using appletviewer
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

74

When you do not have a browser to test or run the applets, the JDK gives a
tool, appletviewer.

AWT Controls

Labels
Push buttons
Check boxes
Choice lists
Lists
Scroll bars
Text editing
These controls are subclasses of Component.
Adding and Removing Controls
To include a control in a window, you must add it to the window. To do this,
you must first create an instance of the desired control and then add it to a window
by calling add( ), which is defined by Container. The add( ) method has several
forms.
Comp onent add(Component compObj)
Here, compObj is an instance of the control that you want to add. A reference to
compObj is returned. Once a control has been added, it will automatically be
visible whenever its parent window is displayed. Sometimes you will want to
remove a control from a window when the control is no longer needed. To do this,
call remove( ). This method is also defined by Container. It has this general form:
void remove(Component obj)
Here, obj is a reference to the control you want to remove. You can remove all
controls by calling removeAll( ).
Responding to Controls
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

75

Except for labels, which are passive controls, all controls generate events when
they are accessed by the user. For example, when the user clicks on a push button,
an event is sent that identifies the push button. In general, your program simply
implements the appropriate interface and then registers an event listener for each
control that you need to monitor. Once a listener has been installed, events are
automatically sent to it.
Labels
The easiest control to use is a label. A label is an object of type Label, and it
contains a string, which it displays. Labels are passive controls that do not support
any interaction with the user.
Label defines the following constructors:
Label( )
creates a blank label.
Label(String str) creates a label that contains the string specified by str.
This string is left-justified.
Label(String str, int how) creates a label that contains the string specified by
str using the alignment specified by how. The value of how must be one of these
three constants: Label.LEFT, Label.RIGHT, or Label.CENTER.
You can set or change the text in a label by using the setText( ) method. You can
obtain the current label by calling getText().
These methods are shown here:
void setText(String str)
String getText( )
For setText( ), str specifies the new label. For getText( ), the current label is
returned.
You can set the alignment of the string within the label by calling setAlignment( ).
To obtain the current alignment, call getAlignment( ).
The methods are as follows:
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

76

void setAlignment(int how)


int getAlignment( )
Using Buttons
The most widely used control is the push button. A push button is a component that
contains a label and that generates an event when it is pressed. Push buttons are
objects of type Button. Button defines these two constructors:
Button( )
Button(String str)
The first version creates an empty button.
The second creates a button that contains str as a label.
After a button has been created, you can set its label by calling setLabel( ). You can
retrieve its label by calling getLabel( ).
These methods are as follows:
void setLabel(String str)
String getLabel( )
Here, str becomes the new label for the button.
Handling Buttons
Each time a button is pressed, an action event is generated. This is sent to
any listeners that previously registered an interest in receiving action event
notifications from that component. Each listener implements the ActionListener
interface. That interface defines the actionPerformed() method, which is called
when an event occurs. An ActionEvent object is supplied as the argument to this
method. It contains both a reference to the button that generated the event and a
reference to the string that is the label of the button.
Example:
Here is an example that creates three buttons labeled Yes, No, and
Undecided. Each time one is pressed, a message is displayed that reports which
button has been pressed. In this version, the label of the button is used to determine
which button has been pressed. The label is obtained by calling the
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

77

getActionCommand(
actionPerformed( ).

method

on

the

ActionEvent

object

passed

to

Check Boxes
A check box is a control that is used to turn an option on or off. It consists of
a small box that can either contain a check mark or not. There is a label associated
with each check box that describes what option the box represents. You change the
state of a check box by clicking on it. Check boxes can be used individually or as
part of a group. Check boxes are objects of the Checkbox class.
Checkbox supports these constructors:

Checkbox( )
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup cbGroup)
Checkbox(String str, CheckboxGroup cbGroup, boolean on)
The first form creates a check box whose label is initially blank. The state of the
check box is unchecked.
The second form creates a check box whose label is specified by str. The state of
the check box is unchecked.
The third form allows you to set the initial state of the check box. If on is true, the
checkbox is initially checked otherwise, it is cleared.
The fourth and fifth forms create a check box whose label is specified by str and
whose group is specified by cbGroup. If this check box is not part of a group, then
cbGroup must be null. (Check box groups are described soon in this article) The
value of on determines the initial state of the check box.
To retrieve the current state of a check box, call getState( ). To set its state, call
setState(). You can obtain the current label associated with a check box by calling
getLabel( ). To set the label, call setLabel( ).
These methods are as follows:
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

78

boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)
Here, if on is true, the box is checked. If it is false, the box is cleared. The string
passed in str becomes the new label associated with the invoking check box.

Handling Check Boxes


Each time a check box is selected or deselected, an item event is generated.
This is sent to any listeners that previously registered an interest in receiving item
event notifications from that component. Each listener implements the
ItemListener interface. That interface defines the itemStateChanged( ) method. An
ItemEvent object is supplied as the argument to this method. It contains
information about the event (for example, whether it was a selection or
deselection).
CheckboxGroup
It is possible to create a set of mutually exclusive check boxes in which one
and only one check box in the group can be checked at any one time. These check
boxes are often called radio buttons, because they act like the station selector on a
car radioonly one station can be selected at any one time. To create a set of
mutually exclusive check boxes, you must first define the group to which they will
belong and then specify that group when you construct the check boxes. Check box
groups are objects of type CheckboxGroup. Only the default constructor is defined,
which creates an empty group. You can determine which check box in a group is
currently selected by calling getSelectedCheckbox( ). You can set a check box by
calling setSelectedCheckbox( ).
These methods are as follows:
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox which)

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

79

Here, the argument which means that checkbox that you want to be selected? The
previously selected check box will be turned off.
Choice Controls
The Choice class is used to create a pop-up list of items from which the user may
choose. Thus, a Choice control is a form of menu. When inactive, a Choice
component takes up only enough space to show the currently selected item. When
the user clicks on it, the whole list of choices pops up, and a new selection can be
made. Each item in the list is a string that appears as a left-justified label in the
order it is added to the Choice object. Choice only defines the default constructor,
which creates an empty list.
To add a selection to the list, call add( ). It has this general form:
void add(String name)
Here, name is the name of the item being added. Items are added to the list in the
order in which calls to add( ) occur. To determine which item is currently selected,
you may call either getSelectedItem( ) or getSelectedIndex( ).
These methods are shown here:
String getSelectedItem( )
int getSelectedIndex( )
The getSelectedItem( ) method returns a string containing the name of the item.
getSelectedIndex( ) returns the index of the item. The first item is at index 0. By
default, the first item added to the list is selected. To obtain the number of items in
the list, call getItemCount( ). You can set the currently selected item using the
select( ) method with either a zero-based integer index or a string that will match a
name in the list.
These methods are shown here:
int getItemCount( )
void select(int index)
void select(String name)

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

80

Given an index, you can obtain the name associated with the item at that index by
calling getItem( ), which has this general form:
String getItem(int index)
Here, index specifies the index of the desired item.
Handling Choice Lists
Each time a choice is selected, an item event is generated. This is sent to any
listeners that previously registered an interest in receiving item event notifications
from that component. Each listener implements the ItemListener interface. That
interface defines the itemStateChanged( ) method. An ItemEvent object is supplied
as the argument to this method.
Lists
The List class provides a compact, multiple-choice, scrolling selection list.
Unlike the Choice object, which shows only the single selected item in the menu, a
List object can be constructed to show any number of choices in the visible
window. It can also be created to allow multiple selections.
List provides these constructors:
List( )
List(int numRows)
List(int numRows, boolean multipleSelect)
The first version creates a List control that allows only one item to be selected at
any one time.
In the second form, the value of numRows specifies the number of entries in the
list that will always be visible (others can be scrolled into view as needed).
In the third form, if multipleSelect is true, then the user may select two or more
items at a time. If it is false, then only one item may be selected.
To add a selection to the list, call add( ). It has the following two forms:
void add(String name)
void add(String name, int index)
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

81

Here, name is the name of the item added to the list.


The first form adds items to the end of the list.
The second form adds the item at the index specified by index. Indexing begins at
zero. You can specify 1 to add the item to the end of the list.
For lists that allow only single selection, you can determine which item is currently
selected by calling either getSelectedItem( ) or getSelectedIndex( ).
These methods are shown here:
String getSelectedItem( )
int getSelectedIndex( )
The getSelectedItem( ) method returns a string containing the name of the item.
If more than one item is selected or if no selection has yet been made, null is
returned. getSelectedIndex( ) returns the index of the item. The first item is at
index 0. If more than one item is selected, or if no selection has yet been made, 1
is returned. For lists that allow multiple selection, you must use either
getSelectedItems( ) or getSelectedIndexes( ), shown here, to determine the current
selections:
String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )
getSelectedItems( ) returns an array containing the names of the currently selected
items. getSelectedIndexes( ) returns an array containing the indexes of the
currently selected items.
To obtain the number of items in the list, call getItemCount( ). You can set the
currently selected item by using the select( ) method with a zero-based integer
index.
These methods are shown here:
int getItemCount( )
void select(int index)
Given an index, you can obtain the name associated with the item at that index by
calling getItem( ), which has this general form:
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

82

String getItem(int index)


Here, index specifies the index of the desired item.
Handling Lists
To process list events, you will need to implement the ActionListener
interface. Each time a List item is double-clicked, an ActionEvent object is
generated. Its getActionCommand( ) method can be used to retrieve the name of
the newly selected item. Also, each time an item is selected or deselected with a
single click, an ItemEvent object is generated. Its getStateChange( ) method can be
used to determine whether a selection or deselection triggered this event.
getItemSelectable( ) returns a reference to the object that triggered this event.
TextField
The TextField class implements a single-line text-entry area, usually called
an edit control. Text fields allow the user to enter strings and to edit the text using
the arrow keys, cut and paste keys, and mouse selections.
TextField is a subclass of TextComponent.
TextField defines the following constructors:
TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
The first version creates a default text field.
The second form creates a text field that is numChars characters wide.
The third form initializes the text field with the string contained in str.
The fourth form initializes a text field and sets its width.
TextField (and its superclass TextComponent) provides several methods that allow
you to utilize a text field. To obtain the string currently contained in the text field,
call getText( ). To set the text , call setText( ).
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

83

These methods are as follows:


String getText( )
void setText(String str)
Here, str is the new string.
The user can select a portion of the text in a text field. Also, you can select a
portion of text under program control by using select( ). A program can obtain the
currently selected text by calling getSelectedText( ).
These methods are shown here:
String getSelectedText( )
void select(int startIndex, int endIndex)
getSelectedText( ) returns the selected text. The select( ) method selects the
characters beginning at startIndex and ending at endIndex1.
You can control whether the contents of a text field may be modified by the user by
calling setEditable( ). You can determine editability by calling isEditable( ).
These methods are shown here:
boolean isEditable( )
void setEditable(boolean canEdit)
isEditable( ) returns true if the text may be changed and false if not. In
setEditable( ), if canEdit is true, the text may be changed. If it is false, the text
cannot be altered.
There may be times when you will want the user to enter text that is not displayed,
such as a password. You can disable the echoing of the characters as they are typed
by calling setEchoChar( ). This method specifies a single character that the
TextField will display when characters are entered (thus, the actual characters
typed will not be shown). You can check a text field to see if it is in this mode with
the echoCharIsSet( ) method. You can retrieve the echo character by calling the
getEchoChar( ) method.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

84

These methods are as follows:


void setEchoChar(char ch)
boolean echoCharIsSet( )
char getEchoChar( )
Here, ch specifies the character to be echoed.
Handling a TextField
Since text fields perform their own editing functions, your program
generally will not respond to individual key events that occur within a text field.
However, you may want to respond when the user presses ENTER. When this
occurs, an action event is generated.
TextArea
Sometimes a single line of text input is not enough for a given task. To
handle these situations, the AWT includes a simple multiline editor called
TextArea.
Following are the constructors for TextArea:
TextArea( )
TextArea(int numLines, int numChars)
TextArea(String str)
TextArea(String str, int numLines, int numChars)
TextArea(String str, int numLines, int numChars, int sBars)
Here, numLines specifies the height, in lines, of the text area, and numChars
specifies its width, in characters. Initial text can be specified by str.
Frame class
A Frame is a top-level window with a title and a border. The size of the frame
includes any area designated for the border. The dimensions of the border area may
be obtained using the getInsets method. Since the border area is included in the
overall size of the frame, the border effectively obscures a portion of the frame,
constraining the area available for rendering and/or displaying subcomponents to
the rectangle which has an upper-left corner location of (insets.left, insets.top), and
Prof. Regitha Baiju
Dept. of Computer Science, S H College,

Thevara

85

has a size of width - (insets.left + insets.right) by height - (insets.top +


insets.bottom).
A frame, implemented as an instance of the JFrame class, is a window that has
decorations such as a border, a title, and supports button components that close or
iconify the window. Applications with a GUI usually include at least one frame.
Applets sometimes use frames, as well.
To make a window that is dependent on another window disappearing
when the other window is iconified, for example use a dialog instead of frame.
To make a window that appears within another window, use an internal frame.

Layout Managers
Java technology uses Layout Managers to define the location and size of
Graphical User Interface components. Java technology does not encourage
programmers to use absolute location and size of components. Java technology
instead places components based on specified Layout Manager. A Layout Manager
implements a layout policy that defines constraints between components in a
container.
Types of Layout Managers
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

86

Java technology provides the following Layout Managers, each of which


implements the LayoutManager interface.
FlowLayout
GridLayout
BorderLayout
GridBagLayout
The FlowLayout is the default Layout Manager for Panel, and hence the Applet
class. The BorderLayout is the default Layout Manager for Window class and its
subclasses (Frame and Dialog).
Setting Layout Managers
The following method defined in the Container class can be used for setting layout
managers.
void setLayout(LayoutManager mgr);
So for example to set FlowLayout as the Layout Manager for a container C, the
following can be used
C.setLayout(new FlowLayout());
The add method defined in the Container class can be used for adding components
to a container. The following are the prototypes of the add method
Component add(Component comp);
Component add(Component comp, int index);
void add(Component comp, Object constraints, int index);
void add(Component comp, Object constraint);
The order in which components are added to a container effects the placement of
components. Also a component added to a container can itself be a container that
holds other components.
FlowLayout Manager
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

87

FlowLayout places component in rows from left to right. Components towards the
end of row are written on next row, if there is not enough space in the current row.
The FlowLayout honors the specified size of a component. The size of a
component never changes regardless of size of container. The following
constructors of FlowLayout are provided by AWT
FlowLayout();
FlowLayout(int alignment);
FlowLayout(int alignment, int hor_gap, int ver_gap);
Alignment can take values of constants - LEFT, CENTER and RIGHT. The default
alignment for the components in a row is center. Default horizontal and vertical
gaps are 5 pixels.
GridLayout Manager
A GridLayout Manager places the components in a rectangular grid. Each
component's position is identified by a column and row. All the cells in the grid
have same size and width. Each component is stretched to the cell size. So a
GridLayout ignores the Component's preferred size.
The GridLayout class provides the following constructors.
GridLayout();
GridLayout(int rows, int columns);
GridLayout(int rows, int columns, int hor_gap, int ver_gap);
This creates a row*col grid layout with the specified horizontal and vertical
gaps. In the constructor, either rows or cols can be zero, but not both. The first
constructor is equivalent to one row with any number of components. The default
gap between components is zero pixels.
BorderLayout Manager
A BorderLayout Manager divides the window into five regions - North, East, West,
South and Center. A component can be explicitly added to one of the regions using
the add() method of the Container class. Any space left over by the component in
North, East, South and West is occupied by the component in Center. Only the last
component added to a region is shown, and not all regions need to be occupied by
Prof. Regitha Baiju
Dept. of Computer Science, S H College,

Thevara

88

a component. So a container that uses BorderLayout may have up-to 5


components.
The BorderLayout class defines the following constructors
BorderLayout();
BorderLayout(int hor_gap, int ver_gap);
As illustrated below, components can be added to the container using add() method
defined in the Container class.
Component add(Component comp);
void add(Component comp, Object constraints);
Here constraints can be NORTH, SOUTH, EAST, WEST and CENTER. These
constants correspond to strings "North", "South", East", "West", and "Center"
respectively. They describe the region where the component should be placed. The
default region is CENTER.
CardLayout
The CardLayout is a useful layout when you want to hide and show components in
groups. It's very useful for being able to fit in a large number of components in a
small space if you don't need to see all of the them at the same time. The best way
to think of it is like a tabbed program. You press a tab to show it's contents and
only one tab can be displayed at a time. This can be achieved with
the CardLayout by using JPanels as containers for the group of components you
want to switch between.
CardLayout cards = new CardLayout();
JPanel cardPanel = new JPanel();
cardPanel.setLayout(cards);
Event Handling
Event
Java applications can create user interfaces, allowing users to carry out
application tasks. Within these user interfaces, the Java code must be able to
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

89

respond to user interaction, tailoring processing to whichever actions the user


takes. Java events are key to this technique, as they provide programs with the
means to detect such user interaction.
In Java, events are handled in terms of event sources and event listeners. An
event source is an object that produces an event, and an event listener is an object
that wants to be informed when an event occurs.
For example, a button is an event source, and an animation object might be an
event listener.

In AWT components, we came to know every component


(except Panel and Label) generates events when interacted by the user like clicking
over a button or pressing enter key in a text field etc. Listeners handle the events.
Let us know the style (or design pattern) Java follows to handle the events.
The event handling involves three types of classes.
1. Event Sources
2. Event classes
3. Event Listeners
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

90

1. Event Sources
Event sources are components, subclasses of java.awt.Component, capable
to generate events. The event source can be a button, TextField or a Frame etc.
2. Event classes
Almost every event source generates an event and is named by some Java
class. For example, the event generated by button is known as ActionEvent and
that of Checkbox is known as ItemEvent. All the events are listed
in java.awt.event package. Following list gives a few components and their
corresponding listeners.
Component

Event it generates

Button, TextField, List, Menu

ActionEvent

Frame

WindowEvent

Checkbox, Choice, List

ItemEvent

Scrollbar

AdjustmentEvent

Mouse (hardware)

MouseEvent

Keyboard (hardware)

KeyEvent

The
events
generated
by
hardware
components
(like MouseEvent and KeyEvent) are known as low-level events and the events
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

91

generated by software components (like Button, List) are known as semantic


events.
3. Event Listeners
The events generated by the GUI components are handled by a special group
of interfaces known as "listeners". Note, Listener is an interface. Every
component has its own listener, say, AdjustmentListener handles the events
of scrollbar. Some listeners handle the events of multiple components. For
example, ActionListener handles the events of Button, TextField, List and Menus.
Listeners are from java.awt.event package.
What happens internally at a button click?
We know the events are handled by listeners and ActionListener handles the
events of a button. Observe the following skeleton code.
public class ButtonDemo extends Frame implements ActionListener
{
public ButtonDemo()
{
Button btn = new Button("OK");
btn.addActionListener(this);
add(btn);
}
public void actionPerformed(ActionEvent e)
{

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

92

String str = e.getActionCommand();


}
}
The above program contains a small part of event handling code of a big
program, and is used here just for the explanation of internal event handling
mechanism of Java.
A button object btn is created for which events are yet to be linked. For this,
the first step is implementing ActionListener to the class ButtonDemo. In the
second step, we link or register the button btn with the ActionListener. For
this addActionListener() method of Button class is used. The parameter "this"
refers the ActionListener.
btn.addActionListener(this);
With the above statement, btn is linked with the ActionListener.
1. When the button btn is clicked, the button generates
called ActionEvent. It is the nature of the button taken care by JVM.

an

event

2. This ActionEvent reaches the ActionListener because we registered the button


with ActionListener earlier.
3. Now, the question is, what ActionListener does with the ActionEvent object it
received?
The ActionListener simply calls actionPerformed() method and passes the
ActionEvent object to the parameter as follows.
public void actionPerformed(ActionEvent e)
The parameter for the above method comes from ActionListener.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

93

4. Finally the ActionEvent object generated by the button btn reaches the e object
of ActionEvent. All this is done by JVM implicitly. For this reason, the
getActionCommand() method of ActionEvent class knows the label of the
button btn.
String str = e.getActionCommand();
The e represents an object of ActionEvent and the value for the e is coming
from button btn. str is nothing but the label of the button OK.
Graphics
The Java 2D API is powerful and complex. However, the vast majority of uses
for the Java 2D API utilize a small subset of its capabilities encapsulated in
the java.awt.Graphics class.
Most methods of the Graphics class can be divided into two basic groups:
Draw and fill methods, enabling you to render basic shapes, text, and images
Attributes setting methods, which affect how that drawing and filling
appears
Methods such as setFont and setColor define how draw and fill methods render.
This figure illustrates how these methods relate to graphic objects:

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

94

Coordinate Axes:
When working with graphics, a coordinate system is essential for locating
object. You probably remember your mathematical coordinate axes system
which utilizes an x-axis and a y-axis. The axes for Java graphics, however, are
somewhat different.
(0,0)

WindowThe coordinate system for the Java graphing window


positions (0,0) in the upper left hand corner. The grid
is then numbered in a positive direction on the x-axis
(horizontally to the right) and in a positive direction on
the y-axis (vertically going down).
We will now be using the methods contained within
the Graphics Classin the package java.awt.

Basic Graphing Methods:

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

95

g.drawLine(35,
45,
75,
95);
drawLine(int x1, int y1, int x2, int y2)
Line
Used to draw a straight line from point
(x1,y1) to (x2,y2).

Rectangle

g.drawRect(35,
45,
25,
35);
drawRect(int x, int y, int width, int
length)
Used to draw a rectangle with the upper
left corner at (x,y) and with the
specified width and length.

g.drawRoundRect(35,45,25,35,10,10)
;
drawRoundRect(int x, int y, int width,
Round Edge int length, int arcWidth, int arcHeight)
Rectangle
Used to draw a rounded edged
rectangle. The amount of rounding is
controlled by arcWidth and arcHeight.
g.drawOval(25,
35,
25,
35);
g.drawOval(25, 35, 25, 25); circle
drawOval(int x, int y, int width, int
Oval / Circle length)
Used to draw an oval inside an
imaginary rectangle whose upper left
corner is at (x,y). To draw a circle keep
the width and length the same.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

96

g.drawArc(35, 45, 75, 95, 0, 90);


drawArc(int x, int y, int width, int
length, int startAngle, int arcAngle)

Arc

Used to draw an arc inside an


imaginary rectangle whose upper left
corner is at (x,y). The arc is drawn
from the startAngle to startAngle +
arcAngle and is measured in degrees.
A startAngle of 0 points horizontally
to the right (like the unit circle in
math). Positive is a counterclockwise
rotation starting at 0.
int [ ] x = {20, 35, 50, 65, 80, 95};
int [ ] y = {60, 105, 105, 110, 95, 95};
g.drawPolygon(x,
y,
6);
drawPolygon(int x[ ], int y[ ], int n)

Polygon

Used to draw a polygon created by n


line segments. The command will
close the polygon. (x-coordinates go in
one array with accompanying ycoordinates in the other)
g.drawString("Java is cool!", 40, 70);
drawString(String str, int x, int y);

String
(text)

Draws a string starting at the point


indicated by (x,y). Be sure you leave
enough room from the top of the screen
for the size of the font.

Streams in Java
An I/O Stream represents an input source or an output destination. A stream
can represent many different kinds of sources and destinations, including disk files,
devices, other programs, and memory arrays.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

97

Streams support many different kinds of data, including simple bytes,


primitive data types, localized characters, and objects. Some streams simply pass
on data; others manipulate and transform the data in useful ways.
No matter how they work internally, all streams present the same simple
model to programs that use them: A stream is a sequence of data. A program uses
an input stream to read data from a source, one item at a time:

Reading information into a program.


A program uses an output stream to write data to a destination, one item at time:

Writing information from a program.

Byte streams read bytes that fall under ASCII range and character streams
read Unicode characters that include characters of many international languages.
Being latest, introduced with JDK 1.1, the character streams are advantageous over
byte streams like the inclusion of newLine() method (that is not deprecated) with
BufferedReader. BufferedWriter includes a overloaded write() method that can
write a whole string or a part of a string; but the writeBytes() method of
DataOutputStream is not overloaded and writes a whole line (but not
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

98

part).Sometimes, byte streams are more efficient to read binary data like the files
containing images and sound.
To bridge or link byte streams with character streams, there comes two
classes InputStreamReader and OutputStreamWriter. Many byte streams (not all)
have equivalent classes in character streams like FileInputStream equivalent
FileReader and FileOutputStream equivalent to FileWriter etc.

Character streams Reader and Writer


The character streams are capable to read 16-bit characters (byte streams
read 8-bit characters). Character streams are capable to translate implicitly 8-bit
data to 16-bit data or vice versa. The two super-most classes from which all
character streams are derived are Reader and Writer. Following hierarchies can
be referred for the list of all character streams.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

99

Buffered Reader

The Java.io.BufferedReader class reads text from a character-input stream,


buffering characters so as to provide for the efficient reading of characters, arrays,
and lines.Following are the important points about BufferedReader:

The buffer size may be specified, or the default size may be used.
Each read request made of a Reader causes a corresponding read request to
be made of the underlying character or byte stream.
Class declaration:
public class BufferedReaderextends Reader
Class constructors
BufferedReader(Reader in)
This creates a buffering character-input stream that uses a default-sized input
buffer.
BufferedReader(Reader in, int sz)
This creates a buffering character-input stream that uses an input buffer of the
specified size.
BufferedWriter
The Java.io.BufferedWriter class writes text to a character-output stream,
buffering characters so as to provide for the efficient writing of single characters,
arrays, and strings.Following are the important points about BufferedWriter:
The buffer size may be specified, or the default size may be used.
A Writer sends its output immediately to the underlying character or byte
stream.
Class declaration:
public class BufferedWriterextends Writer
Class constructors:
BufferedWriter(Writer out)
This creates a buffered character-output stream that uses a default-sized output
buffer.
Prof. Regitha Baiju
Dept. of Computer Science, S H College,
Thevara

100

BufferedWriter(Writer out, int sz)


This creates a new buffered character-output stream that uses an output buffer
of the given size.

Prof. Regitha Baiju


Dept. of Computer Science, S H College,
Thevara

You might also like