Professional Documents
Culture Documents
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
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.
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
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.
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.
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
Description
Size/Format
byte
Byte-length integer
short
Short integer
int
Integer
long
Long integer
Integers
Real numbers
float
double
char
A single character
boolean
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
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.
15
16
17
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.
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.
20
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 :
22
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
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
29
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.
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
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
34
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
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
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
Access Modifiers
public
protected
no access modifier
private
44
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.
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.
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
53
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
56
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
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.
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.
59
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
63
64
65
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
68
Example:
public class Main
{
public void setPrioritiesOnThreads()
{
Thread thread1 = new Thread(new TestThread(1));
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.
71
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.
73
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
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.
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)
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
82
83
84
Thevara
85
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
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
89
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
ActionEvent
Frame
WindowEvent
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
92
an
event
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:
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)
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.
96
Arc
Polygon
String
(text)
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.
97
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.
99
Buffered Reader
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