Java Complete Notes
Java Complete Notes
M. YASEEN PASHA
ASST.PROF
J2SE CORE JAVA MATERIAL 2022
James Gosling is a famous Canadian software developer who has been with Sun
Microsystems since 1984 and is considered as father of Java programming language.
Gosling did the original design of Java and implemented its original compiler and virtual
machine.
Since the Internet consists of different types of computers and operating systems. A
common lang. 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 user’s 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.
YASEEN’S Page 2
J2SE CORE JAVA MATERIAL 2022
1. Introduction to Java
History of Java:
In 1990, Sun Micro Systems Inc. (US) was conceived a project to develop software for
consumer electronic devices that could be controlled by a remote. This project was called
Stealth Project but later its name was changed to Green Project.
In January 1991, Project Manager James Gosling and his team members Patrick
Naughton, Mike Sheridan, Chris Wrath, and Ed Frank met to discuss about this project.
Gosling thought C and C++ would be used to develop the project. But the problem he
faced with them is that they were system dependent languages. The trouble with C and
C++ (and most other languages) is that they are designed to be compiled for a specific
target and could not be used on various processors, which the electronic devices might
use.
James Gosling with his team started developing a new language, which was completely
system independent. This language was initially called OAK. Since this name was
registered by some other company, later it was changed to Java.
James Gosling and his team members were consuming a lot of coffee while developing
this language. Good quality of coffee was supplied from a place called “Java Island’.
Hence they fixed the name of the language as Java. The symbol for Java language is cup
and saucer.
Sun formally announced Java at Sun World conference in 1995. On January 23rd 1996,
JDK1.0 version was released.
Features of Java (Java buzz words):
Simple: Learning and practicing java is easy because of resemblance with c and C++.
Object Oriented Programming Language: Unlike C++, Java is purely OOP.
Distributed: Java is designed for use on network; it has an extensive library which works
in agreement with TCP/IP.
Secure: Java is designed for use on Internet. Java enables the construction of virus-free,
tamper free systems.
Robust (Strong/ Powerful): Java programs will not crash because of its exception
handling and its memory management features.
Interpreted: Java programs are compiled to generate the byte code. This byte code can
be downloaded and interpreted by the interpreter. .class file will have byte code
instructions and JVM which contains an interpreter will execute the byte code.
Portable: Java does not have implementation dependent aspects and it yields or gives
same result on any machine.
Architectural Neutral Language: Java byte code is not machine dependent, it can run
on any machine with any processor and with any OS.
High Performance: Along with interpreter there will be JIT (Just In Time) compiler
which enhances the speed of execution.
Multithreaded: Executing different parts of program simultaneously is called
multithreading. This is an essential feature to design server side programs.
YASEEN’S Page 3
J2SE CORE JAVA MATERIAL 2022
Dynamic: We can develop programs in Java which dynamically change on Internet (e.g.:
Applets).
Right-click on My Computer
Choose Properties
Select the Advanced tab
Click the Environment Variables button at the bottom
In system variables tab, select path (system variable) and click on edit button
A window with variable name path and its value will be displayed.
Don’t disturb the default path value that is appearing and just append (add) to that path at
the end:
D:\ProgramFiles\Java\jdk1.6.0\bin;
Finally press OK button.
YASEEN’S Page 4
J2SE CORE JAVA MATERIAL 2022
YASEEN’S Page 5
J2SE CORE JAVA MATERIAL 2022
Javac : Javac is the java compiler that translates the source code to byte codes. That is, it
converts the source file. Namely the .java file to .class file.
Java : The java interpreter which runs applets and Applications by reading and interpreting the
byte code files. That is, it executes the .class file.
Javadoc : Javadoc is the utility used to produce documentation for the classes from the source
code files.
JDB: JDB is a debugging tool.
The way these tools are applied to build and run application programs is as follows.
The source code file is created using a text editor and saved with a .java (with Extension).
The source code is compiled using the java compiler javac. Which translates source code to byte
codes. The compiled code is executed using the java interpreter java.Which runs applications and
applets by reading the byte codes. Byte codes are instructions that are generated for a virtual
machine. A virtual machine is a program that processes these generalized instructions to machine
specific code.
The lifetime of a JVM
The runtime instance of the java virtual machine has a clear mission in life. To run one java
application. When a java application starts a run time instance is ban when the application
completes the instance dies. If you start three java applications at the same time on the same
computer using the same can create and implementation. You will get three JVM instances. Each
java application runs inside its own java virtual machine. A java virtual machine instance starts
running its solitary application by invoking the main() method of some initial class. The main()
method must be public, static, return void and accept one parameter: a string array. Any class
with such a main() method can be used as the starting point for a java application.
Java Runtime Environment
JRE consists of the java virtual machine. The java plot form core classes and supporting files. It
is the run time part of the java Development Kit. No compiler, no debugger, no tools. The JRE is
the smallest set of executables and files that constitute the standard java plot form.JRE consists
of the JVM interacting with hardware on one side and the JVM and the prg on the other. The
java runtime environment runs code compiled for the JVM by:
Coding the .class files
Performed by the ‘class loader’. The class loader performs security checks here if the .classes are
required across the network.
Verifying bytecode.
Performed by the ‘bytecode verifier’. The bytecode verifier verifies the format of the code object
type conversions and checks for the violation of access rights.
Executing the code
Performed by the runtime interpreter. The interpreter executes the bytecode and makes calls to
the underlying hard. The following Figure illustrates the above steps in sequence.
YASEEN’S Page 6
J2SE CORE JAVA MATERIAL 2022
JIT
In the java programming language and environment a Just – In – Time (JIT) compiler is a
program that runs java bytecode ( a program that contains instructions that must be interpreted)
into instructions that can be sent directly to the processor.(machine code or native code).
After you have written a java program the source code is compiled to byte code by JVM. When a
JIT is present the JVM does something different. After reading in the .class file for interpreter
locations, it hands the .class file to the JIT. The JIT will take the byte code and compiled them
into native code for the machine that you are running on. It is faster to grab the bytecodes
compiled them and run the resulting executable with JIT than with just interpreter them. The JIT
is an integral part of the JVM. So you nicer notice its there, except your, java runs faster. Some
environments allow you to choose whether or not to JIT code. Java is dynamic language. So you
are not allowed to “Statistically” compile all the .class files into machine code until they are
actually called. Thus the JIT is really “just in time”. Since it compiles methods on a methods
called. If you call the same method more than once, the JIT code can really pay off as you do not
have to re-JIT the method and can simply reexecute the native code.
YASEEN’S Page 7
J2SE CORE JAVA MATERIAL 2022
2. Programming Structure
Comments: Comments are description about the aim and features of the program. Comments
increase readability of a program. Three types of comments are there in Java:
Single line comments: These comments start with //
e.g.: // this is comment line
Multi line comments: These comments start with /* and end with */
e.g.: /* this is comment line*/
Java documentation comments: These comments start with /** and end with */
These comments are useful to create a HTML file called API (application programming
Interface)document. This file contains description of all the features of software.
Structure of the Java Program:
As all other programming languages, Java also has a structure.
The first line of the C/C++ program contains include statement. For example, <stdio.h> is
the header file that contains functions, like printf (), scanf () etc. So if we want to use any
of these functions, we should include this header file in C/ C++ program.
Similarly in Java first we need to import the required packages. By default java.lang.* is
imported. Java has several such packages in its library. A package is a kind of directory
that contains a group of related classes and interfaces. A class or interface contains
methods.
Since Java is purely an Object Oriented Programming language, we cannot write a Java
program without having at least one class or object. So, it is mandatory to write a class in
Java program. We should use class keyword for this purpose and then write class name.
In C/C++, program starts executing from main method similarly in Java, program starts
executing from main method. The return type of main method is void because program
starts executing from main method and it returns nothing.
Sample Program:
//A Simple Java Program
import java.lang.System;
import java.lang.String;
class Sample
{
public static void main(String args[])
{
System.out.print ("Hello world");
}
}
Since Java is purely an Object Oriented Programming language, without creating an
object to a class it is not possible to access methods and members of a class. But main
YASEEN’S Page 8
J2SE CORE JAVA MATERIAL 2022
method is also a method inside a class, since program execution starts from main method
we need to call main method without creating an object.
Static methods are the methods, which can be called and executed without creating
objects.Since we want to call main () method without using an object, we should declare
main () method as static. JVM calls main () method using its Classname.main () at the
time of running the program.
JVM is a program written by Java Soft people (Java development team) and main () is the
method written by us. Since, main () method should be available to the JVM, it should be
declared as public. If we don’t declare main () method as public, then it doesn’t make
itself available to JVM and JVM cannot execute it.
JVM always looks for main () method with String type array as parameter otherwise JVM
cannot recognize the main () method, so we must provide String type array as parameter
to main () method.
A class code starts with a {and ends with a}. A class or an object contains variables and
methods (functions). We can create any number of variables and methods inside the
class.
This is our first program, so we had written only one method called main ().
Our aim of writing this program is just to display a string “Hello world”. In Java, print ()
method is used to display something on the monitor.
A method should be called by using objectname.methodname (). So, to call print ()
method,
create an object to PrintStream class then call objectname.print () method.
An alternative is given to create an object to PrintStream Class i.e. System.out. Here,
System
is the class name and out is a static variable in System class. out is called a field in System class.
When we call this field a PrintStream class object will be created internally. So, we can call
print() method as: System.out.print (“Hello world”);
println () is also a method belonging to PrintStream class. It throws the cursor to the next
line
after displaying the result.
In the above Sample program System and String are the classes present in java.lang
package.
YASEEN’S Page 9
J2SE CORE JAVA MATERIAL 2022
Escape Sequence: Java supports all escape sequence which is supported by C/ C++. A character
preceded by a backslash (\) is an escape sequence and has special meaning to the compiler.
When an escape sequence is encountered in a print statement, the compiler interprets it
accordingly.
Escape Sequence Description
The prompt shows current directory. To compile Sample.java source file, change current
directory to the directory where Sample.java file is located. For example, if source directory
is JQR on the D drive, type the following commands at the prompt and press Enter:
YASEEN’S Page 11
J2SE CORE JAVA MATERIAL 2022
The Java Virtual Machine: Java Virtual Machine (JVM) is the heart of entire Java program
execution process. First of all, the .java program is converted into a .class file consisting of byte
code instructions by the java compiler at the time of compilation. Remember, this java compiler
is outside the JVM. This .class file is given to the JVM. Following figure shows the architecture
of Java Virtual Machine.
YASEEN’S Page 12
J2SE CORE JAVA MATERIAL 2022
In JVM, there is a module (or program) called class loader sub system, which performs the
following instructions:
First of all, it loads the .class file into memory.
Then it verifies whether all byte code instructions are proper or not. If it finds any
instruction
suspicious, the execution is rejected immediately.
If the byte instructions are proper, then it allocates necessary memory to execute the
program. This memory is divided into 5 parts, called run time data areas, which contain
the data and results while running the program. These areas are as follows:
Method area: Method area is the memory block, which stores the class code, code of the
variables and code of the methods in the Java program. (Method means functions written
in a class).
Heap: This is the area where objects are created. Whenever JVM loads a class, method
and heap areas are immediately created in it.
Java Stacks: Method code is stored on Method area. But while running a method, it
needs some more memory to store the data and results. This memory is allotted on Java
Stacks. So, Java Stacks are memory area where Java methods are executed. While
executing methods, a separate frame will be created in the Java Stack, where the method
is executed. JVM uses a separate thread (or process) to execute each method.
PC (Program Counter) registers: These are the registers (memory areas), which
contain memory address of the instructions of the methods. If there are 3 methods, 3 PC
registers will be used to track the instruction of the methods.
Native Method Stacks: Java methods are executed on Java Stacks. Similarly, native
YASEEN’S Page 13
J2SE CORE JAVA MATERIAL 2022
methods (for example C/C++ functions) are executed on Native method stacks. To execute
the native methods, generally native method libraries (for example C/C++ header files) are
required. These header files are located and connected to JVM by a program, called Native
method interface.
Execution Engine contains interpreter and JIT compiler which translates the byte code
instructions into machine language which are executed by the microprocessor. Hot spot
(loops/iterations) is the area in .class file i.e. executed by JIT compiler. JVM will identify the Hot
spots in the .class files and it will give it to JIT compiler where the normal instructions and
statements of Java program are executed by the Java interpreter.
Float Data Types: These data types handle floating point numbers.
YASEEN’S Page 14
J2SE CORE JAVA MATERIAL 2022
Character Data Type: This data type represents a single character. char data type in java
uses two bytes of memory also called Unicode system. Unicode is a specification to include
alphabets of all international languages into the character set of java.
Boolean Data Type: can handle truth values either true or false
e.g.:- boolean response = true;
Operators: An operator is a symbol that performs an operation. An operator acts on
variables
called operands.
Arithmetic operators: These operators are used to perform fundamental operations like
addition, subtraction, multiplication etc.
Assignment operator: This operator (=) is used to store some value into a variable.
Unary operators: As the name indicates unary operator’s act only on one operand.
Bitwise operators: These operators act on individual bits (0 and 1) of the operands. They
act only on integer data types, i.e. byte, short, long and int.
YASEEN’S Page 16
J2SE CORE JAVA MATERIAL 2022
YASEEN’S Page 17
J2SE CORE JAVA MATERIAL 2022
4.Control Statements
Control statements are the statements which alter the flow of execution and provide better
control to the programmer on the flow of execution. In Java control statements are categorized
into selection control statements, iteration control statements and jump control statements.
Java’s Selection Statements: Java supports two selection statements: if and switch.
These
statements allow us to control the flow of program execution based on condition.
if Statement: if statement performs a task depending on whether a condition is true or
false.
Syntax: if (condition)
statement1;
else
statement2;
Here, each statement may be a single statement or a compound statement enclosed in curly
braces (that is, a block). The condition is any expression that returns a boolean value. The else
clause is optional.
}
Output:
Switch Statement: When there are several options and we have to choose only one
option from the available ones, we can use switch statement.
Syntax: switch (expression)
{ case value1: //statement sequence
break;
case value2: //statement sequence
break;
………….…..
case valueN: //statement sequence
break;
default: //default statement sequence
}
Here, depending on the value of the expression, a particular corresponding case will be executed.
Program 2: Write a program for using the switch statement to execute a particular task
depending on color value.
//To display a color name depending on color value
class ColorDemo
{ public static void main(String args[])
{ char color = ‘r’;
switch (color)
{ case ‘r’: System.out.println (“red”); break;
case ‘g’: System.out.println (“green”); break;
case ‘b’: System.out.println (“blue”); break;
case ‘y’: System.out.println (“yellow”); break;
case ‘w’: System.out.println (“white”); break;
default: System.out.println (“No Color Selected”);
}
}
}
Output:
YASEEN’S Page 19
J2SE CORE JAVA MATERIAL 2022
Java’s Iteration Statements: Java’s iteration statements are for, while and do-while.
These
statements are used to repeat same set of instructions specified number of times called
loops.
A loop repeatedly executes the same set of instructions until a termination condition is
met.
while Loop: while loop repeats a group of statements as long as condition is true. Once
the condition is false, the loop is terminated. In while loop, the condition is tested first; if
it is true, then only the statements are executed. while loop is called as entry control
loop.
Syntax: while (condition)
{
statements;
}
YASEEN’S Page 20
J2SE CORE JAVA MATERIAL 2022
for Loop: The for loop is also same as do…while or while loop, but it is more compact
syntactically. The for loop executes a group of statements as long as a condition is true.
Syntax: for (expression1; expression2; expression3)
{ statements;
}
Here, expression1 is used to initialize the variables, expression2 is used for condition checking
and expression3 is used for increment or decrement variable value.
Program 5: Write a program to generate numbers from 1 to 20.
//Program to generate numbers from 1 to 20.
class Natural
YASEEN’S Page 21
J2SE CORE JAVA MATERIAL 2022
Java’s Jump Statements: Java supports three jump statements: break, continue and
return.
These statements transfer control to another part of the program.
break:
break can be used inside a loop to come out of it.
break can be used inside the switch block to come out of the switch block.
break can be used in nested blocks to go to the end of a block. Nested blocks
represent a block written within another block.
Syntax: break; (or) break label;//here label represents the name of the block.
YASEEN’S Page 22
J2SE CORE JAVA MATERIAL 2022
}
System.out.println (“This is after second block”);
}
}
}
Output:
continue: This statement is useful to continue the next repetition of a loop/ iteration.
When continue is executed, subsequent statements inside the loop are not executed.
Syntax: continue;
Program 7: Write a program to generate numbers from 1 to 20.
//Program to generate numbers from 1 to 20.
class Natural
{ public static void main (String args[])
{ int i=1;
while (true)
{ System.out.print (i + “\t”);
i++;
if (i <= 20 )
continue;
else
break;
}
}
}
Output:
return statement:
return statement is useful to terminate a method and come back to the calling method.
YASEEN’S Page 23
J2SE CORE JAVA MATERIAL 2022
Note: goto statement is not available in java, because it leads to confusion and forms infinite
loops.
YASEEN’S Page 24
J2SE CORE JAVA MATERIAL 2022
monitor. System.out is used to display normal messages and results whereas System.err
is
used to display error messages.
To accept data from the keyboard:
Connect the keyboard to an input stream object. Here, we can use InputStreamReader
that
can read data from the keyboard.
InputSteamReader obj = new InputStreamReader (System.in);
Connect InputStreamReader to BufferReader, which is another input type of stream. We
are
using BufferedReader as it has got methods to read data properly, coming from the
stream.
BufferedReader br = new BufferedReader (obj);
The above two steps can be combined and rewritten in a single statement as:
BufferedReader br = new BufferedReader (new InputStreamReader
(System.in));
Now, we can read the data coming from the keyboard using read () and readLine ()
methods
available in BufferedReader class.
YASEEN’S Page 25
J2SE CORE JAVA MATERIAL 2022
ch, we should convert it into char type by writing (char) before the method. int data type
is
converted into char data type, converting one data type into another data type is called type
casting.
We can accept a float value from the keyboard with the help of the following statement:
float n = Float.parseFloat (br.readLine() );
We are accepting a float value in the form of a string using br.readLine () and then
passing
the string to Float.parseFloat () to convert it into float. parseFloat () is a static method in
Float class.
We can accept a double value from the keyboard with the help of the following
statement:
YASEEN’S Page 26
J2SE CORE JAVA MATERIAL 2022
YASEEN’S Page 27
J2SE CORE JAVA MATERIAL 2022
In the above program after accepting gender of the student, br.skip (2) is used. The reason is that
we used read () method to accept the gender value and then readLine () is used to accept the
name. When we type M for gender and press enter, then it releases a \n code. So at gender
column, we are giving two characters M and \n. But, read () method takes only the first character
and rejects the next character, i.e. \n, which is trapped by the next readLine () method and name
will accept \n. For this purpose, we can use skip () method of BufferedReader, which helps in
skipping a specified number of characters. Suppose we take \n as two characters; now to skip
them, we can write br.skip (2);
Arrays: An array represents a group of elements of same data type. Arrays are generally
categorized into two types:
Single Dimensional arrays (or 1 Dimensional arrays)
Multi-Dimensional arrays (or 2 Dimensional arrays, 3 Dimensional arrays, …)
Single Dimensional Arrays: A one dimensional array or single dimensional array represents a
row or a column of elements. For example, the marks obtained by a student in 5 different
subjects can be represented by a 1D array.
We can declare a one dimensional array and directly store elements at the time of its
declaration, as:
int marks[] = {50, 60, 55, 67, 70};
We can create a 1D array by declaring the array first and then allocate memory for it by
using new operator, as: int marks[]; //declare marks array
marks = new int[5]; //allot memory for storing 5 elements
These two statements also can be written as: int marks [] = new int [5];
Program 1: Write a program to accept elements into an array and display the same.
// program to accept elements into an array and display the same.
import java.io.*;
class ArrayDemo1
{ public static void main (String args[]) throws IOException
{ //Create a BufferedReader class object (br)
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
YASEEN’S Page 28
J2SE CORE JAVA MATERIAL 2022
Output:
YASEEN’S Page 29
J2SE CORE JAVA MATERIAL 2022
int marks[] [] = {{50, 60, 55, 67, 70},{62, 65, 70, 70, 81}, {72, 66, 77, 80, 69} };
We can create a two dimensional array by declaring the array first and then we can allot
memory for it by using new operator as:
int marks[ ] [ ]; //declare marks array
marks = new int[3][5]; //allot memory for storing 15 elements.
These two statements also can be written as: int marks [ ][ ] = new int[3][5];
Program 2: Write a program to take a 2D array and display its elements in the form of a matrix.
//Displaying a 2D array as a matrix
class Matrix
{ public static void main(String args[])
{ //take a 2D array
int x[ ][ ] = {{1, 2, 3}, {4, 5, 6} };
// display the array elements
for (int i = 0 ; i < 2 ; i++)
{ System.out.println ();
for (int j = 0 ; j < 3 ; j++)
System.out.print(x[i][j] + “\t”);
}
}
}
Output:
Three Dimensional arrays (3D arrays): We can consider a three dimensional array as a
combination of several two dimensional arrays. To represent a three dimensional array,
we
should use three pairs of square braces [ ] [ ] after the array name.
We can declare a three dimensional array and directly store elements at the time of its
declaration, as:
YASEEN’S Page 30
J2SE CORE JAVA MATERIAL 2022
int arr[ ] [ ] [ ] = {{{50, 51, 52},{60, 61, 62}}, {{70, 71, 72}, {80, 81, 82}}};
We can create a three dimensional array by declaring the array first and then we can allot
memory for it by using new operator as:
int arr[ ] [ ] = new int[2][2][3]; //allot memory for storing 15 elements.
arrayname.length: If we want to know the size of any array, we can use the property ‘length’ of
an array. In case of 2D, 3D length property gives the number of rows of the array.
Strings: A String represents group of characters. Strings are represented as String objects in
java.
Creating Strings:
· We can declare a String variable and directly store a String literal using assignment operator.
String str = "Hello";
· We can create String object using new operator with some data.
String s1 = new String ("Java");
· We can create a String by using character array also.
char arr[] = { 'p','r','o',’g’,’r’,’a’,’m’};
· We can create a String by passing array name to it, as:
String s2 = new String (arr);
· We can create a String by passing array name and specifying which characters we need:
String s3 = new String (str, 2, 3);
Here starting from 2nd character a total of 3 characters are copied into String s3.
YASEEN’S Page 31
J2SE CORE JAVA MATERIAL 2022
YASEEN’S Page 32
J2SE CORE JAVA MATERIAL 2022
We can divide objects broadly as mutable and immutable objects. Mutable objects are those
objects whose contents can be modified. Immutable objects are those objects, once created can
not be modified. String objects are immutable. The methods that directly manipulate data of the
object are not available in String class.
StringBuffer: StringBuffer objects are mutable, so they can be modified. The methods that
YASEEN’S Page 33
J2SE CORE JAVA MATERIAL 2022
YASEEN’S Page 34
J2SE CORE JAVA MATERIAL 2022
7. Introduction to OOPs
Languages like Pascal, C, FORTRAN, and COBOL are called procedure oriented programming
languages. Since in these languages, a programmer uses procedures or functions to perform a
task. When the programmer wants to write a program, he will first divide the task into separate
sub tasks, each of which is expressed as functions/ procedures. This approach is called procedure
oriented approach.
The languages like C++ and Java use classes and object in their programs and are called
Object Oriented Programming languages. The main task is divided into several modules and
these are represented as classes. Each class can perform some tasks for which several methods
are written in a class. This approach is called Object Oriented approach.
YASEEN’S Page 35
J2SE CORE JAVA MATERIAL 2022
1. Main program is divided into small parts 1. Main program is divided into small object
depending on the functions. depending on the problem.
2. The Different parts of the program 2. Functions of object linked with object using
connect with each other by parameter message passing.
passing & using operating system.
3. Every function contains different data. 3. Data & functions of each individual object
act
like a single unit.
4. Functions get more importance than data 4. Data gets more importance than functions in
in program. program.
5. Most of the functions use global data. 5. Each object controls its own data.
6. Same data may be transfer from one 6. Data does not possible transfer from one
function to another object to another.
7. There is no perfect way for data hiding. 7. Data hiding possible in OOP which prevent
illegal access of function from outside of it.
This
is one of the best advantages of OOP also.
8. Functions communicate with other 8. One object link with other using the message
functions maintaining as usual rules. passing.
9. More data or functions cannot be added 9. More data or functions can be added with
with program if necessary. For this purpose program if necessary. For this purpose full
full program need to be change. program need not to be change.
10. To add new data in program user should 10. Message passing ensure the permission of
be ensure that function allows it. accessing member of an object from other
object.
11. Top down process is followed for 11. Bottom up process is followed for program
program design. design.
12. Example: Pascal, Fortran 12. Example: C++, Java.
YASEEN’S Page 36
J2SE CORE JAVA MATERIAL 2022
Features of OOP:
Class: In object-oriented programming, a class is a programming language construct that
is
used as a blueprint to create objects. This blueprint includes attributes and methods that
the
created objects all share. Usually, a class represents a person, place, or thing - it is an
abstraction of a concept within a computer program. Fundamentally, it encapsulates the
state
and behavior of that which it conceptually represents. It encapsulates state through data
placeholders called member variables; it encapsulates behavior through reusable code
called
methods.
General form of a class: class class_name
{
Properties (variables);
Actions (methods);
}
e.g.: class Student
{ //properties -- variables
int rollNo;
String name;
//methods -- actions
void display ()
{
System.out.println ("Student Roll Number is: " + rollNo);
System.out.println ("Student Name is: " + name);
}
}
Note: Variables inside a class are called as instance variables. Variables inside a method are
called as method variables.
Object: An Object is a real time entity. An object is an instance of a class. Instance
means
physically happening. An object will have some properties and it can perform some
actions.
Object contains variables and methods. The objects which exhibit similar properties and
actions are grouped under one class. “To give a real world analogy, a house is
constructed
according to a specification. Here, the specification is a blueprint that represents a class,
and
the constructed house represents the object”.
To access the properties and methods of a class, we must declare a variable of that class
YASEEN’S Page 37
J2SE CORE JAVA MATERIAL 2022
type. This variable does not define an object. Instead, it is simply a variable that can refer
to an object.
We must acquire an actual, physical copy of the object and assign it to that variable. We
can do this using new operator. The new operator dynamically allocates memory for an
object and returns a reference to it. This reference is, more or less, the address in
memory
of the object allocated by new. This reference is then stored in the variable. Thus, in
Java,
all class objects must be dynamically allocated.
General form of an Object:
Class_name variable_name; // declare reference to object
variable_name = new Class_name ( ); // allocate an object
e.g.: Student s; // s is reference variable
s = new Student (); // allocate an object to reference variable s
The above two steps can be combined and rewritten in a single statement as:
Student s = new Student ();
Now we can access the properties and methods of a class by using object with dot
operator as:
s.rollNo, s.name, s.display ()
Encapsulation: Wrapping up of data (variables) and methods into single unit is called
Encapsulation. Class is an example for encapsulation. Encapsulation can be described as
a
protective barrier that prevents the code and data being randomly accessed by other code
defined outside the class. Encapsulation is the technique of making the fields in a class
private and providing access to the fields via methods. If a field is declared private, it
cannot
be accessed by anyone outside the class.
e.g.: class Student
{
private int rollNo;
private String name;
//methods -- actions
void display ()
{
System.out.println ("Student Roll Number is: " + rollNo);
System.out.println ("Student Name is: " + name);
}
}
YASEEN’S Page 38
J2SE CORE JAVA MATERIAL 2022
Abstraction: Providing the essential features without its inner details is called
abstraction
(or) hiding internal implementation is called Abstraction. We can enhance the internal
implementation without effecting outside world. Abstraction provides security. A class
contains lot of data and the user does not need the entire data. The advantage of
abstraction
is that every user will get his own view of the data according to his requirements and will
not
get confused with unnecessary data. A bank clerk should see the customer details like
account number, name and balance amount in the account. He should not be entitled to
see
the sensitive data like the staff salaries, profit or loss of the bank etc. So such data can be
abstracted from the clerks view.
e.g.: class Bank
{ private int accno;
private String name;
private float balance;
private float profit;
private float loan;
void display_to_clerk ()
{
System.out.println ("Accno = " + accno);
System.out.println ("Name = " + name);
System.out.println ("Balance = " + balance);
}
}
In the preceding class, inspite of several data items, the display_to_clerk () method is able
to access and display only the accno, name and balance values. It cannot access profit and
loan of the customer. This means the profit and loan data is hidden from the view of the
bank clerk.
Inheritance: Acquiring the properties from one class to another class is called
inheritance
(or) producing new class from already existing class is called inheritance. Reusability of
code
is main advantage of inheritance. In Java inheritance is achieved by using extends
keyword.
The properties with access specifier private cannot be inherited.
e.g.: class Parent
{
String parentName;
String familyName;
}
YASEEN’S Page 39
J2SE CORE JAVA MATERIAL 2022
Polymorphism: The word polymorphism came from two Greek words ‘poly’ means
‘many’
and ‘morphos’ means ‘forms’. Thus, polymorphism represents the ability to assume
several
different forms. The ability to define more than one function with the same name is
called
Polymorphism
e.g.: 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)
Message Passing: Calling a method in a class is called message passing. We can call
methods of a class by using object with dot operator as:
object_name.method_name ();
e.g.: s.display (); ob.add (2, 5); ob.printMyName ();
Program 1: Write a program to display details of student using class and object.
//Program to display the details of a student using class and object
class Student
{ int rollNo; //properties -- variables
String name;
void display () //method -- action
{ System.out.println ("Student Roll Number is: " + rollNo);
System.out.println ("Student Name is: " + name);
}
}
class StudentDemo
{ public static void main(String args[])
{
YASEEN’S Page 40
J2SE CORE JAVA MATERIAL 2022
When the programmer does not initialize the instance variables, java compiler will write code
and initializes the variables with default values.
YASEEN’S Page 41
J2SE CORE JAVA MATERIAL 2022
class Student
{ int rollNo = 101;
String name = “Surya“;
void display ()
{ System.out.println ("Student Roll Number is: " + rollNo);
System.out.print ("Student Name is: " + name);
}
}
class StudentDemo
{ public static void main(String args[])
{ Student s1 = new Student ();
System.out.println ("First Student Details : " );
s1.display ();
Student s2 = new Student ();
System.out.println ("Second Student Details : " );
s2.display ();
}
}
Output:
Type 2: We can initialize one class instance variables in another class using reference
variable.
s.rollNo = 101;
s.name = “Kiran”;
Program 3: Let us rewrite the Program 1.
//Program to display the details of a student using class and object
class Student
{ int rollNo;
String name;
void display ()
{
System.out.println ("Student Roll Number is: " + rollNo);
System.out.print ("Student Name is: " + name);
}
}
YASEEN’S Page 42
J2SE CORE JAVA MATERIAL 2022
class StudentDemo
{ public static void main(String args[])
{ Student s1 = new Student ();
System.out.println ("First Student Details : " );
s1.rollNo = 101;
s1.name = "Suresh";
s1.display ();
Student s2 = new Student ();
System.out.println ("Second Student Details : " );
s2.rollNo = 102;
s2.name = "Ramesh";
s2.display ();
}
}
Output:
In this type of initialization the properties (variables in the class) are not available, if they are
declared as private.
Access Specifiers: An access specifier is a key word that represents how to access a member
of a class. There are four access specifiers in java.
private: private members of a class are not available outside the class.
public: public members of a class are available anywhere outside the class.
protected: protected members are available outside the class.
default: if no access specifier is used then default specifier is used by java compiler.
Default members are available outside the class.
Type 3: We can initialize instance variables using a constructor.
Constructor:
A constructor is similar to a method that initializes the instance variables of a class.
A constructor name and classname must be same.
A constructor may have or may not have parameters. Parameters are local variables to
receive data.
A constructor without any parameters is called default constructor.
YASEEN’S Page 43
J2SE CORE JAVA MATERIAL 2022
YASEEN’S Page 44
J2SE CORE JAVA MATERIAL 2022
class StudentDemo
{ public static void main(String args[])
{ Student s1 = new Student ();
System.out.println ("s1 object contains: ");
s1.display ();
Student s2 = new Student ();
System.out.println ("s2 object contains: ");
s2.display ();
}
}
Output:
Output:
The keyword ‘this’: There will be situations where a method wants to refer to the object
which invoked it. To perform this we use ‘this’ keyword. There are no restrictions to use
‘this’ keyword we can use this inside any method for referring the current object. This
keyword is always a reference to the object on which the method was invoked. We can
use ‘this’ keyword wherever a reference to an object of the current class type is
permitted. ‘this’ is a key word that refers to present class object. It refers to
Present class instance variables
Present class methods.
Present class constructor.
Program 6: Write a program to use ‘this’ to refer the current class parameterized constructor
and current class instance variable.
//this demo
class Person
{
String name;
Person ( )
{ this (“Ravi Sekhar”); // calling present class parameterized constructor
this.display ( ); // calling present class method
}
Person (String name)
{ this.name = name; // assigning present class variable with parameter “name”
}
void display( )
{ System.out.println ("Person Name is = " + name);
}
YASEEN’S Page 46
J2SE CORE JAVA MATERIAL 2022
}
class ThisDemo
{ public static void main(String args[])
{
Person p = new Person ( );
}
}
Output:
Garbage Collection: Generally memory is allocated to objects by using ‘new’ operator and
deleting an allocated memory is uncommon. This deletion of memory is supported by delete
operator in C++ but this deletion of allocated memory works automatically in Java. This
automatic deletion of already allocated but unused memory is called as garbage collection. This
operation of garbage collection is accomplished by a method named “gc ()”. This method is used
for garbage collection.
The finalize( ) Method: It is possible to define a method that will be called just before an
object's final destruction by the garbage collector. This method is called finalize( ) method. To
add a finalizer to a class, simply define the finalize( ) method. The Java runtime calls that
method whenever it is about to recycle an object of that class. Inside the finalize( ) method
specify those actions that must be performed before an object is destroyed. The finalize( )
method has this general form:
protected void finalize( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize ( ) by code defined
outside its class. This means that you cannot know when.or even if.finalize ( ) will be executed.
For example, if your program ends before garbage collection occurs, finalize ( ) will not execute.
8. Methods & Inner Class
Methods: A method represents a group of statements to perform a task. A method contains two
parts: method header (or) method prototype is first part. This part contains method name, method
parameters and method returntype.
return_type methodname (param1, param2, ……)
e.g.: double sum (double d1, double d2), void sum (), float power (float x, int n), etc.
The second part contains method body. This part represents the logic to perform the task in the
YASEEN’S Page 47
J2SE CORE JAVA MATERIAL 2022
Note: Instance methods can read and act upon static variables also.
Static Methods:
Static methods can read and act upon static variables.
Static methods cannot read and act upon instance variables.
YASEEN’S Page 48
J2SE CORE JAVA MATERIAL 2022
Static variable is a variable whose single copy is shared by all the objects.
Static methods are declared using keyword static.
Static methods can be called using objectname.methodname (or) classname.methodname.
From any object, if static variable is modified it affects all the objects. Static variables are
stored on method area.
YASEEN’S Page 49
J2SE CORE JAVA MATERIAL 2022
Inner Class: A class with in another class is called Inner class. When the programmer wants to
restrict the access of entire code of a class, creates an inner class as a private class. The way to
access the inner class is through its outer class only.
Inner class is a safety mechanism.
Inner class is hidden in outer class from other classes.
Only inner class can be private.
An object to Inner class can be created only in its outer class.
An object to Inner class cannot be created in any other class.
Outer class object and Inner class objects are created in separate memory locations.
Outer class members are available to Inner class object.
Inner class object will have an additional invisible field called ‘this$0’ that stores a
reference
of outer class object.
Inner class members are referenced as: this.member;
Outer class members are referred as: Outerclass.this.member;
YASEEN’S Page 50
J2SE CORE JAVA MATERIAL 2022
Program 3: Write a program to access private members of a class using inner class.
// inner class demo
class Bank
{ private double bal, rate;
Bank (double b, double r)
{ bal=b;
rate = r;
}
void display ( )
{ Interest in=new Interest ();
in.calculateInterest ( );
System.out.println ("New Balance : " + bal);
}
private class Interest
{ void calculateInterest ( )
{ System.out.println ("Balance = "+ bal);
double interest=bal* rate/100;
System.out.println ("interest = "+interest);
bal+=interest;
}
}
}
class InnerDemo
{ public static void main (String args[])
{ Bank account = new Bank (20000, 5);
account.display ();
}
}
Output:
YASEEN’S Page 51
J2SE CORE JAVA MATERIAL 2022
9. Inheritance
Inheritance: Creating new class from existing class such that the features of existing class are
available to the new class is called inheritance. Already existing class is called super class &
produced class is called sub class. Using inheritance while creating sub classes a programmer
can reuse the super class code without rewriting it.
Syntax: class subclass_name extends superclass_name
e.g.: class Child extends Parent
Program 1: Write a program to create a Person class which contains general details of a person
and create a sub class Employ which contains company details of a person. Reuse the general
details of the person in its sub class.
// Inheritance Example
class Person
{ String name;
String permanentAddress;
int age;
void set_PermanentDetails (String name, String permanentAddress, int age)
{ this.name = name;
this.permanentAddress = permanentAddress;
this.age = age;
}
void get_PermanentDetails ()
{ System.out.println ("Name : " + name);
System.out.println ("Permanent Address : " + permanentAddress);
System.out.println ("Age :" + age);
}
}
class Employ extends Person
{ int id;
String companyName;
String companyAddress;
Employ (int id, String name, String permanentAddress, int age,
String companyName, String companyAddress)
{ this.id = id;
set_PermanentDetails (name, permanentAddress, age);
this.companyName = companyName;
this.companyAddress = companyAddress;
}
YASEEN’S Page 52
J2SE CORE JAVA MATERIAL 2022
void get_EmployDetails ()
{ System.out.println ("Employ Id : " + id);
get_PermanentDetails ();
System.out.println ("Company Name : "+ companyName);
System.out.println ("Company Address : "+companyAddress);
}
}
class InherDemo
{ public static void main (String args [])
{ Employ e1 = new Employ (101, "Suresh Kumar", "18-Madhura Nagar-Tirupati",
29, "Centris Software- Chennai", "20-RVS Nagar");
e1.get_EmployDetails ();
}
}
Output:
Program 2: Write a program to illustrate the order of calling of default constructor in super and
sub class.
// Default constructors in super and sub class
class One
{ One ( ) //super class default constructor
{
System.out.println ("Super class default constructor called");
}
}
class Two extends One
{ Two ( ) //sub class default constructor
{
System.out.println ("Sub class default constructor called");
}
}
class Const
{ public static void main (String args[])
{ Two t=new Two ( ); //create sub class object
YASEEN’S Page 53
J2SE CORE JAVA MATERIAL 2022
}
}
Output:
YASEEN’S Page 54
J2SE CORE JAVA MATERIAL 2022
{
super(a); // (or) x=a;
y=b;
}
void show( )
{ super.show ();
System.out.println ("y = "+y);
System.out.println (“ super x = “ + super.x);
}
}
class SuperUse
{
public static void main(String args[])
{ B ob = new B (10, 24);
ob.show ( );
}
}
Output:
10. Polymorphism
Polymorphism came from the two Greek words ‘poly’ means many and morphos means forms.
If the same method has ability to take more than one form to perform several tasks then it is
called polymorphism. It is of two types: Dynamic polymorphism and Static polymorphism.
Dynamic Polymorphism: The polymorphism exhibited at run time is called dynamic
polymorphism. In this dynamic polymorphism a method call is linked with method body
at
the time of execution by JVM. Java compiler does not know which method is called at
the
time of compilation. This is also known as dynamic binding or run time polymorphism.
Method overloading and method overriding are examples of Dynamic Polymorphism in
Java.
YASEEN’S Page 55
J2SE CORE JAVA MATERIAL 2022
Method Overloading: Writing two or more methods with the same name, but with a
difference in the method signatures is called method over loading. Method signature
represents the method name along with the method parameters. In method over loading
JVM understands which method is called depending upon the difference in the method
signature. The difference may be due to the following:
There is a difference in the no. of parameters.
void add (int a,int b)
void add (int a,int b,int c)
There is a difference in the data types of parameters.
void add (int a,float b)
void add (double a,double b)
There is a difference in the sequence of parameters.
void swap (int a,char b)
void swap (char a,int b)
Program 1: Write a program to create a class which contains two methods with the same
name but with different signatures.
// overloading of methods --------- Dynamic polymorphism
class Sample
{ void add(int a,int b)
{
System.out.println ("sum of two="+ (a+b));
}
void add(int a,int b,int c)
{
System.out.println ("sum of three="+ (a+b+c));
}
}
class OverLoad
{ public static void main(String[] args)
{ Sample s=new Sample ( );
s.add (20, 25);
s.add (20, 25, 30);
}
}
Output:
YASEEN’S Page 56
J2SE CORE JAVA MATERIAL 2022
Method Overriding: Writing two or more methods in super & sub classes with same
name
and same signatures is called method overriding. In method overriding JVM executes a
method depending on the type of the object.
Program 2: Write a program that contains a super and sub class which contains a method
with same name and same method signature, behavior of the method is dynamically decided.
//overriding of methods --------------- Dynamic polymorphism
class Animal
{ void move()
{
System.out.println ("Animals can move");
}
}
class Dog extends Animal
{ void move()
{
System.out.println ("Dogs can walk and run");
}
}
public class OverRide
{ public static void main(String args[])
{ Animal a = new Animal (); // Animal reference and object
Animal b = new Dog (); // Animal reference but Dog object
a.move (); // runs the method in Animal class
b.move (); //Runs the method in Dog class
}
}
Output:
Achieving method overloading & method overriding using instance methods is an example of
dynamic polymorphism.
Static Polymorphism: The polymorphism exhibited at compile time is called Static
polymorphism. Here the compiler knows which method is called at the compilation. This
is
also called compile time polymorphism or static binding. Achieving method overloading
&
method overriding using private, static and final methods is an example of Static
YASEEN’S Page 57
J2SE CORE JAVA MATERIAL 2022
Polymorphism.
Program 3: Write a program to illustrate static polymorphism.
//Static Polymorphism
class Animal
{ static void move ()
{ System.out.println ("Animals can move");
}
}
class Dog extends Animal
{ static void move ()
{ System.out.println ("Dogs can walk and run");
}
}
public class StaticPoly
{ public static void main(String args[])
{ Animal.move ();
Dog.move ();
}
}
Output:
YASEEN’S Page 58
J2SE CORE JAVA MATERIAL 2022
YASEEN’S Page 59
J2SE CORE JAVA MATERIAL 2022
/* If super class reference is used to refer to sub class object then super class methods are
available, sub class methods are not available unless they override super class methods */
One ob3 = (One) new Two(); // Generalization
ob3.show1();
/* It is not possible to access any methods if we use subclass object to refer to super class
as above */
Two ob4 = (Two) new One();
ob4.show1();
ob4.show2();
// Specialization
One ob5 = (One) new Two();
Two ob6 = (Two) ob5;
ob6.show1();
ob6.show2();
}
}
Note: Using casting it is not possible to convert a primitive data type into a referenced data type
and vice-versa. For this we are using Wrapper classes.
YASEEN’S Page 60
J2SE CORE JAVA MATERIAL 2022
YASEEN’S Page 61
J2SE CORE JAVA MATERIAL 2022
YASEEN’S Page 62
J2SE CORE JAVA MATERIAL 2022
12. Interface
A programmer uses an abstract class when there are some common features shared by all the
objects. A programmer writes an interface when all the features have different implementations
for different objects. Interfaces are written when the programmer wants to leave the
implementation to third party vendors. An interface is a specification of method prototypes. All
the methods in an interface are abstract methods.
· An interface is a specification of method prototypes.
· An interface contains zero or more abstract methods.
· All the methods of interface are public, abstract by default.
· An interface may contain variables which are by default public static final.
· Once an interface is written any third party vendor can implement it.
· All the methods of the interface should be implemented in its implementation classes.
· If any one of the method is not implemented, then that implementation class should be
declared as abstract.
· We cannot create an object to an interface.
· We can create a reference variable to an interface.
· An interface cannot implement another interface.
· An interface can extend another interface.
· A class can implement multiple interfaces.
Program 1: Write an example program for interface
interface Shape
{ void area ();
void volume ();
double pi = 3.14;
}
class Circle implements Shape
{ double r;
Circle (double radius)
{ r = radius;
}
public void area ()
{ System.out.println ("Area of a circle is : " + pi*r*r );
}
public void volume ()
{ System.out.println ("Volume of a circle is : " + 2*pi*r);
}
}
class Rectangle implements Shape
{ double l,b;
Rectangle (double length, double breadth)
{ l = length;
YASEEN’S Page 63
J2SE CORE JAVA MATERIAL 2022
b = breadth;
}
public void area ()
{ System.out.println ("Area of a Rectangle is : " + l*b );
}
public void volume ()
{ System.out.println ("Volume of a Rectangle is : " + 2*(l+b));
}
}
class InterfaceDemo
{ public static void main (String args[])
{ Circle ob1 = new Circle (10.2);
ob1.area ();
ob1.volume ();
Rectangle ob2 = new Rectangle (12.6, 23.55);
ob2.area ();
ob2.volume ();
}
}
Output:
Types of inheritance:
Single Inheritance: Producing subclass from a single super class is called single
inheritance.
YASEEN’S Page 64
J2SE CORE JAVA MATERIAL 2022
Multiple Inheritance: Producing subclass from more than one super class is called
Multiple
Inheritance.
Java does not support multiple inheritance. But multiple inheritance can be achieved by using
interfaces.
Program 2: Write a program to illustrate how to achieve multiple inheritance using multiple
interfaces.
//interface Demo
interface Father
{ double PROPERTY = 10000;
double HEIGHT = 5.6;
}
interface Mother
{ double PROPERTY = 30000;
double HEIGHT = 5.4;
}
class MyClass implements Father, Mother
{ void show()
{ System.out.println("Total property is :" +(Father.PROPERTY+Mother.PROPERTY));
System.out.println ("Average height is :" + (Father.HEIGHT + Mother.HEIGHT)/2 );
}
}
class InterfaceDemo
{ public static void main(String args[])
{ MyClass ob1 = new MyClass();
ob1.show();
}
YASEEN’S Page 65
J2SE CORE JAVA MATERIAL 2022
Output:
13. Packages
A package is a container of classes and interfaces. A package represents a directory that contains
related group of classes and interfaces. For example, when we write statemens like:
import java.io.*;
Here we are importing classes of java.io package. Here, java is a directory name and io is another
sub directory within it. The ‘*’ represents all the classes and interfaces of that io sub directory.
We can create our own packages called user-defined packages or extend the available packages.
User-defined packages can also be imported into other classes and used exactly in the same way
as the Built-in packages. Packages provide reusability.
General form for creating a package:
package packagename;
e.g.: package pack;
· The first statement in the program must be package statement while creating a package.
· While creating a package except instance variables, declare all the members and the class
itself as public then only the public members are available outside the package to other
programs.
Program 1: Write a program to create a package pack with Addition class.
//creating a package
package pack;
public class Addition
{ private double d1,d2;
public Addition(double a,double b)
{ d1 = a;
d2 = b;
}
public void sum()
YASEEN’S Page 66
J2SE CORE JAVA MATERIAL 2022
The –d option tells the Java compiler to create a separate directory and place the .class file in that
directory (package). The (.) dot after –d indicates that the package should be created in the
current directory. So, out package pack with Addition class is ready.
Program 2: Write a program to use the Addition class of package pack.
//Using the package pack
import pack.Addition;
class Use
{ public static void main(String args[])
{ Addition ob1 = new Addition(10,20);
ob1.sum();
}
}
Output:
Program 3: Write a program to add one more class Subtraction to the same package pack.
//Adding one more class to package pack:
package pack;
public class Subtraction
{ private double d1,d2;
public Subtraction(double a, double b)
{ d1 = a;
d2 = b;
}
YASEEN’S Page 67
J2SE CORE JAVA MATERIAL 2022
Program 4: Write a program to access all the classes in the package pack.
//To import all the classes and interfaces in a class using import pack.*;
import pack.*;
class Use
{ public static void main(String args[])
{ Addition ob1 = new Addition(10.5,20.6);
ob1.sum();
Subtraction ob2 = new Subtraction(30.2,40.11);
ob2.difference();
}
}
In this case, please be sure that any of the Addition.java and Subtraction.java programs will not
exist in the current directory. Delete them from the current directory as they cause confusion for
the Java compiler. The compiler looks for byte code in Addition.java and Subtraction.java files
and there it gets no byte code and hence it flags some errors.
Output:
If the package pack is available in different directory, in that case the compiler should be given
information regarding the package location by mentioning the directory name of the package in
the classpath. The CLASSPATH is an environment variable that tells the Java compiler where to
look for class files to import. If our package exists in e:\sub then we need to set class path as
follows:
YASEEN’S Page 68
J2SE CORE JAVA MATERIAL 2022
We are setting the classpath to e:\sub directory and current directory (.) and
%CLASSPATH% means retain the already available classpath as it is.
Creating Sub package in a package: We can create sub package in a package in the format:
package packagename.subpackagename;
e.g.: package pack1.pack2;
Here, we are creating pack2 subpackage which is created inside pack1 package. To use the
classes and interfaces of pack2, we can write import statement as:
import pack1.pack2;
Program 5: Program to show how to create a subpackage in a package.
//Creating a subpackage in a package
package pack1.pack2;
public class Sample
{ public void show ()
{
System.out.println ("Hello Java Learners");
}
}
Compiling the above program:
Access Specifier: Specifies the scope of the data members, class and methods.
private members of the class are available with in the class only. The scope of private
members of the class is “CLASS SCOPE”.
public members of the class are available anywhere . The scope of public members of the
class is "GLOBAL SCOPE".
default members of the class are available with in the class, outside the class and in its
sub
class of same package. It is not available outside the package. So the scope of default
members of the class is "PACKAGE SCOPE".
protected members of the class are available with in the class, outside the class and in its
sub
class of same package and also available to subclasses in different package also.
YASEEN’S Page 69
J2SE CORE JAVA MATERIAL 2022
YASEEN’S Page 70
J2SE CORE JAVA MATERIAL 2022
import same.A;
public class C extends A
{ public static void main(String args[])
{ C obj = new C();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}
Compiling the above program:
14. Exceptions
An error in a program is called bug. Removing errors from program is called debugging. There
are basically three types of errors in the Java program:
Compile time errors: Errors which occur due to syntax or format is called compile time
errors. These errors are detected by java compiler at compilation time. Desk checking is
solution for compile-time errors.
Runtime errors: These are the errors that represent computer inefficiency. Insufficient
memory to store data or inability of the microprocessor to execute some statement is
examples to runtime errors. Runtime errors are detected by JVM at runtime.
Logical errors: These are the errors that occur due to bad logic in the program. These
errors
are rectified by comparing the outputs of the program manually.
Exception: An abnormal event in a program is called Exception.
Exception may occur at compile time or at runtime.
Exceptions which occur at compile time are called Checked exceptions.
e.g.: ClassNotFoundException, NoSuchMethodException, NoSuchFieldException etc.
Exceptions which occur at run time are called Unchecked exceptions.
eg: ArrayIndexOutOfBoundsException, ArithmeticException, NumberFormatException
etc.
Exception Handling: Exceptions are represented as classes in java.
YASEEN’S Page 71
J2SE CORE JAVA MATERIAL 2022
An exception can be handled by the programmer where as an error cannot be handled by the
programmer. When there is an exception the programmer should do the following tasks:
If the programmer suspects any exception in program statements, he should write them
inside
try block.
try
{
statements;
}
When there is an exception in try block JVM will not terminate the program abnormally.
JVM stores exception details in an exception stack and then JVM jumps into catch block.
The programmer should display exception details and any message to the user in catch
block.
catch ( ExceptionClass obj)
{ statements;
}
Programmer should close all the files and databases by writing them inside finally block.
Finally block is executed whether there is an exception or not.
finally
{ statements;
}
Performing above tasks is called Exception Handling.
Program 1: Write a program which tells the use of try, catch and finally block.
// Exception example
class ExceptionExample
YASEEN’S Page 72
J2SE CORE JAVA MATERIAL 2022
Output:
Even though multiple exceptions are found in the program, only one exception is raised
at a
time.
We can handle multiple exceptions by writing multiple catch blocks.
YASEEN’S Page 73
J2SE CORE JAVA MATERIAL 2022
throw Clause: throw clause can be used to throw out user defined exceptions. It is useful to
create an exception object and throw it out of try block
Program 3: Write a program which shows the use of throw clause.
//Throw Example
class ThrowDemo
{ static void Demo( )
{ try
{ System.out.println ("inside method");
throw new NullPointerException("my data");
}
catch (NullPointerException ne)
YASEEN’S Page 74
J2SE CORE JAVA MATERIAL 2022
{
System.out.println ("ne");
}
}
public static void main(String args[])
{
ThrowDemo.Demo ( );
}
}
Output:
Types of Exceptions:
Built-in exceptions: These are the exceptions which are already available in java.
e.g.: ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException,
StringIndexOutOfBoundsException, NoSuchMethodException, InterruptedException,
ClassNotFoundException, FileNotFoundException, NumberFormatException,
RuntimeException etc.
User-defined exceptions: - These are the exceptions created by the programmer.
Creating user defined exceptions:
Write user exception class extending Exception class.
e.g.: class MyException extends Exception
Write a default constructor in the user exception class
e.g.: MyException ( ) { }
Write a parameterized constructor with String as a parameter, from there call the
parameterized constructor of Exception class.
e.g.: MyException (String str)
{
super (str);
}
Whenever required create user exception object and throw it using throw statement.
Ex: - throw me;
YASEEN’S Page 75
J2SE CORE JAVA MATERIAL 2022
Output:
YASEEN’S Page 76
J2SE CORE JAVA MATERIAL 2022
Character Class: The Character class wraps a value of the primitive type char in an object. An
object of type character contains a single field whose type is char. We can create Character class
object as: Character obj = new Character (ch); // where ch is a character.
YASEEN’S Page 77
J2SE CORE JAVA MATERIAL 2022
Program 1: Write a program which shows the use of Character class methods.
//Testing a char
import java.io.*;
class CharTest
{ public static void main(String args[]) throws IOException
{ BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
System.out.print ("Enter a character : " );
char ch = (char) br.read();
if (Character.isDigit (ch) )
System.out.println ("It is a digit");
else if (Character.isUpperCase (ch))
System.out.println ("It is a Upper Case Letter");
else if (Character.isLowerCase (ch) )
System.out.println ("It is a Lower Case Letter");
else if ( Character.isSpaceChar (ch))
System.out.println ("It is a Space bar");
else if ( Character.isWhitespace (ch) )
System.out.println ("Dont know what is this character");
}
}
Output:
YASEEN’S Page 78
J2SE CORE JAVA MATERIAL 2022
Byte Class: The Byte class wraps a value of primitive type 'byte' in an object. An object of type
Byte contains a single field whose type is byte.
Constructors:
· Byte (byte num)
e.g.: Byte b1 = new Byte (98);
· Byte (String str)
e.g.: String str = "98";
Byte b2 = new Byte (str);
Methods of Byte Class:
Program 2: Write a program which shows the use of Byte class methods.
//Creating and comparing Byte Objects
import java.io.*;
class Bytes
{ public static void main(String args[]) throws IOException
{ BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
System.out.print ("Enter a byte number: ");
String str = br.readLine ();
//convert str into Byte object
Byte b1 = new Byte (str);
System.out.print ("Enter a another byte number: ");
str = br.readLine ();
//convert str into Byte obj
Byte b2 = Byte.valueOf (str);
//compare b1 and b2
int n = b1.compareTo(b2);
YASEEN’S Page 79
J2SE CORE JAVA MATERIAL 2022
if (n==0)
System.out.println ("Both are Same");
else if(n>0)
System.out.println (b1 + "is bigger");
else
System.out.println (b2 + " is bigger");
}
}
Output:
Short Class: Short class wraps a value of primitive data type 'short' in its object. Short class
object contains a short type field that stores a short number.
Constructors:
· Short (short num)
· Short (String str)
Methods:
Integer Class: Integer class wraps a value of the primitive type 'int' in an object. An object of
type Integer contains a single field whose type is int.
Constructors:
· Integer (int num)
· Integer (String str)
Methods:
YASEEN’S Page 80
J2SE CORE JAVA MATERIAL 2022
Float Class: Float class wraps a value of primitive type float in an object. An object of type float
contains a single field whose type is float.
Constructors:
· Float (float num)
· Float (String str)
Methods:
Long Class: The Long class contains a primitive long type data. The object of Long class
contains a field where we can store a long value.
Constructors: Long has two constructors.
· Long (long num): Long object can be created as: Long obj = new Long (123000);
· Long(String str): String str = "12300044";
Long obj = new Long (str);
Methods:
YASEEN’S Page 81
J2SE CORE JAVA MATERIAL 2022
Boolean class: The Boolean class object contains a primitive 'boolean' type data. The object of
Boolean class contains a field where we can store a boolean value.
Constructors:
· Boolean obj = new Boolean (true);
· String str ="false";
Boolean obj = new Boolean (str);
Methods:
Double Class: Double class wraps a value of primitive type Double in an Object.
Constructors:
· Double (double num)
· Double (String str)
Methods:
YASEEN’S Page 82
J2SE CORE JAVA MATERIAL 2022
Math class: The class Math contains methods for performing basic numeric operations.
Methods:
YASEEN’S Page 83
J2SE CORE JAVA MATERIAL 2022
Output:
YASEEN’S Page 84
J2SE CORE JAVA MATERIAL 2022
YASEEN’S Page 85
J2SE CORE JAVA MATERIAL 2022
Generic Method: We can make a method alone as generic method by writing the generic
parameter before the method return type as:
<T> returntype methodname ()
{
Method code;
}
e.g.: <T> void display_data ()
{
Method body;
}
Program 2: Write a program with generic method which displays any type of data.
//Generic method example
class MyClass
{ <T>void display_data (T arr[])
{
for (int i=0;i<arr.length; i++)
System.out.print ("\t" + arr[i]);
System.out.println ();
}
}
class Gen2
{ public static void main(String args[])
{ MyClass obj = new MyClass ( );
Integer a[] = {1,2,3,4,5,6};
System.out.print ("Reading Integer Objects: ");
obj.display_data (a);
Float b[] = {1.1f,2.2f,3.4f};
System.out.print ("Reading Float Objects: ");
obj.display_data (b);
String c[] = {"Subash","Chandra","Bose"};
YASEEN’S Page 86
J2SE CORE JAVA MATERIAL 2022
Generic Interface: It is possible to develop an interface using generic type concept. The general
form of generic interface looks like:
interface interface_name <T>
{
//method that accepts any object
return_type method_name ( T object_name );
}
Here, T represents any data type which is used in the interface. We can write an implementation
class for the above interface as:
class class_name <T> implements interface_name <T>
{
public return_type method_name ( T object_name )
{
//provide body of the method
}
}
Program 3: Write an example program for generic interface.
//A generic interface
interface inter<T>
{
void displayData (T obj);
}
class AnyClass<T> implements inter<T>
{ public void displayData (T t1)
{
System.out.println ("Entered value is : " + t1);
}
}
class Gen3
{ public static void main (String args[])
YASEEN’S Page 87
J2SE CORE JAVA MATERIAL 2022
YASEEN’S Page 88
J2SE CORE JAVA MATERIAL 2022
Set: A Set represents a group of elements (objects) arranged just like an array. The set
will
grow dynamically when the elements are stored into it. A set will not allow duplicate
elements.
List: Lists are like sets but allow duplicate values to be stored.
Queue: A Queue represents arrangement of elements in FIFO (First In First Out) order.
This
means that an element that is stored as a first element into the queue will be removed
first
from the queue.
Map: Maps store elements in the form of key value pairs. If the key is provided its
corresponding value can be obtained.
Retrieving Elements from Collections: Following are the ways to retrieve any element from a
collection object:
Using Iterator interface.
Using ListIterator interface.
Using Enumeration interface.
Iterator Interface: Iterator is an interface that contains methods to retrieve the elements one by
one from a collection object. It retrieves elementsonly in forward direction. It has 3 methods:
ListIterator Interface: ListIterator is an interface that contains methods to retrieve the elements
from a collection object, both in forward and reverse directions. It can retrieve the elements in
forward and backward direction. It has the following important methods:
YASEEN’S Page 89
J2SE CORE JAVA MATERIAL 2022
Enumeration Interface: This interface is useful to retrieve elements one by one like Iterator. It
has 2 methods.
HashSet Class: HashSet represents a set of elements (objects). It does not guarantee the order of
elements. Also it does not allow the duplicate elements to be stored.
We can write the HashSet class as: class HashSet<T>
We can create the object as: HashSet<String> hs = new HashSet<String> ();
The following constructors are available in HashSet:
HashSet();
HashSet (int capacity); Here capacity represents how many elements can be stored into
the
HashSet initially. This capacity may increase automatically when more number of
elements
is being stored.
Program 1: Write a program which shows the use of HashSet and Iterator.
YASEEN’S Page 90
J2SE CORE JAVA MATERIAL 2022
//HashSet Demo
import java.util.*;
class HS
{ public static void main(String args[])
{ //create a HashSet to store Strings
HashSet <String> hs = new HashSet<String> ();
//Store some String elements
hs.add ("India");
hs.add ("America");
hs.add ("Japan");
hs.add ("China");
hs.add ("America");
//view the HashSet
System.out.println ("HashSet = " + hs);
//add an Iterator to hs
Iterator it = hs.iterator ();
//display element by element using Iterator
System.out.println ("Elements Using Iterator: ");
while (it.hasNext() )
{ String s = (String) it.next ();
System.out.println(s);
}
}
}
Output:
LinkedHashSet Class: This is a subclass of HashSet class and does not contain any additional
members on its own. LinkedHashSet internally uses a linked list to store the elements. It is a
generic class that has the declaration:
class LinkedHashSet<T>
YASEEN’S Page 91
J2SE CORE JAVA MATERIAL 2022
Stack Class: A stack represents a group of elements stored in LIFO (Last In First Out) order.
This means that the element which is stored as a last element into the stack will be the first
element to be removed from the stack. Inserting the elements (Objects) into the stack is called
push operation and removing the elements from stack is called pop operation. Searching for an
element in stack is called peep operation. Insertion and deletion of elements take place only from
one side of the stack, called top of the stack. We can write a Stack class as:
class Stack<E>
e.g.: Stack<Integer> obj = new Stack<Integer> ();
Stack Class Methods:
YASEEN’S Page 92
J2SE CORE JAVA MATERIAL 2022
LinkedList Class: A linked list contains a group of elements in the form of nodes. Each node
will have three fields- the data field contatins data and the link fields contain references to
previous and next nodes.A linked list is written in the form of:
class LinkedList<E>
we can create an empty linked list for storing String type elements (objects) as:
LinkedList <String> ll = new LinkedList<String> ();
YASEEN’S Page 93
J2SE CORE JAVA MATERIAL 2022
Note: In case of LinkedList counting starts from 0 and we start counting from 1.
Program 3: Write a program that shows the use of LinkedList class.
import java.util.*;
//Linked List
class LinkedDemo
{ public static void main(String args[])
{ LinkedList <String> ll = new LinkedList<String>();
ll.add ("Asia");
ll.add ("North America");
ll.add ("South America");
YASEEN’S Page 94
J2SE CORE JAVA MATERIAL 2022
ll.add ("Africa");
ll.addFirst ("Europe");
ll.add (1,"Australia");
ll.add (2,"Antarctica");
System.out.println ("Elements in Linked List is : " + ll);
System.out.println ("Size of the Linked List is : " + ll.size() );
}
}
Output:
ArrayList Class: An ArrayList is like an array, which can grow in memory dynamically.
ArrayList is not synchronized. This means that when more than one thread acts simultaneously
on the ArrayList object, the results may be incorrect in some cases.
ArrayList class can be written as: class ArrayList <E>
We can create an object to ArrayList as: ArrayList <String> arl = new ArrayList<String> ();
YASEEN’S Page 95
J2SE CORE JAVA MATERIAL 2022
YASEEN’S Page 96
J2SE CORE JAVA MATERIAL 2022
al.add (2,"Antarctica");
System.out.print ("Size of the Array List is: " + al.size ());
System.out.print ("\nRetrieving elements in ArrayList using Iterator :");
Iterator it = al.iterator ();
while (it.hasNext () )
System.out.print (it.next () + "\t");
}
}
Output:
Vector Class: Similar to ArrayList, but Vector is synchronized. It means even if several threads
act on Vector object simultaneously, the results will be reliable.
Vector class can be written as: class Vector <E>
We can create an object to Vector as: Vector <String> v = new Vector<String> ();
YASEEN’S Page 97
J2SE CORE JAVA MATERIAL 2022
YASEEN’S Page 98
J2SE CORE JAVA MATERIAL 2022
HashMap Class: HashMap is a collection that stores elements in the form of key-value pairs. If
key is provided later its corresponding value can be easily retrieved from the HAshMap. Keys
should be unique. HashMap is not synchronized and hence while using multiple threads on
HashMap object, we get unreliable results.
We can write HashMap class as: class HashMap<K, V>
For example to store a String as key and an integer object as its value, we can create the
HashMap as: HashMap<String, Integer> hm = new HashMap<String, Integer> ();
The default initial capacity of this HashMap will be taken as 16 and the load factor as 0.75. Load
factor represents at what level the HashMap capacity should be doubled. For example, the
product of capacity and load factor = 16 * 0.75 = 12. This represents that after storing 12th
keyvalue
pair into the HashMap, its capacity will become 32.
HashMap Class Methods:
YASEEN’S Page 99
J2SE CORE JAVA MATERIAL 2022
Hashtable Class: Hashtable is a collection that stores elements in the form of key-value pairs. If
key is provided later its corresponding value can be easily retrieved from the HAshtable. Keys
should be unique. Hashtable is synchronized and hence while using multiple threads on
Output:
Arrays Class: Arrays class provides methods to perform certain operations on any single
dimensional array. All the methods of the Arrays class are static, so they can be called in the
form of Arrays.methodname ().
Arrays Class Methods:
Program 8: Write a program to sort given numbers using sort () method of Arrays Class.
import java.util.*;
//Arrays Demo
class ArraysDemo
{ public static void main(String args[])
{
int x[] = {40,50,10,30,20};
Arrays.sort( x );
for (int i=0;i<x.length;i++)
System.out.print(x[i] + "\t");
}
}
Output:
StringTokenizer: The StringTokenizer class is useful to break a String into small pieces called
tokens. We can create an object to StringTokenizer as:
StringTokenizer st = new StringTokenizer (str, "delimeter");
StringTokenizer Class Methods:
{
public static void main(String args[])
{ //take a String
String str = "Java is an OOP Language";
//brake wherever a space is found
StringTokenizer st = new StringTokenizer (str," ");
//retrieve tokens and display
System.out.println ("The tokens are: ");
while ( st.hasMoreTokens () )
{
String s = st.nextToken ();
System.out.println (s );
}
}
}
Output:
Calendar: This class is useful to handle date and time. We can create an object to Calendar class
as: Calendar cl = Calendar.getInstance ();
Calendar Class Methods:
Date Class: Date Class is also useful to handle date and time. Once Date class object is created,
it should be formatted using the following methods of DateFormat class of java.text package.We
can create an object to Date class as: Date dd = new Date ();
Once Date class object is created, it should be formatted using the methods of DateFormat class
of java.text package.
DateFormat class Methods:
DateFormat fmt = DateFormat.getDateInstance(formatconst, region);
This method is useful to store format information for date value into DateFormat object
fmt.
DateFormat fmt = DateFormat.getTimeInstance(formatconst, region);
This method is useful to store format information for time value into DateFormat object
fmt.
DateFormat fmt = DateFormat.getDateTimeInstance(formatconst, formatconst, region);
This method is useful to store format information for date value into DateFormat object
fmt.
Program 11: Write a program that shows the use of Date class.
//Display System date and time using Date class
import java.util.*;
import java.text.*;
class MyDate
{
public static void main(String args[])
{ Date d = new Date ();
DateFormat fmt = DateFormat.getDateTimeInstance (DateFormat.MEDIUM,
DateFormat.SHORT, Locale.UK);
String str = fmt.format (d);
System.out.println (str);
}
}
Output:
.jpg), we should go for a byte stream. To handle data in the form of 'bytes' the abstract
classes: InputStream and OutputStream are used. The important classes of byte streams
are:
Program 2: Write a program to improve the efficiency of writing data into a file using
BufferedOutputStream.
//Creating a text file using byte stream classes
import java.io.*;
class Create2
{ public static void main(String args[]) throws IOException
{ //attach keyboard to DataInputStream
DataInputStream dis = new DataInputStream (System.in);
//attach file to FileOutputStream, if we use true then it will open in append mode
FileOutputStream fout = new FileOutputStream ("myfile", true);
BufferedOutputStream bout = new BufferedOutputStream (fout, 1024);
//Buffer size is declared as 1024 otherwise default buffer size of 512 bytes is used.
//read data from DataInputStream and write into FileOutputStream
char ch;
System.out.println ("Enter @ at end : " ) ;
while ( (ch = (char) dis.read() ) != '@' )
bout.write (ch);
bout.close ();
fout.close ();
}
}
Output:
Program 4: Write a program to improve the efficiency while reading data from a file using
BufferedInputStream.
//Reading a text file using byte stream classes
import java.io.*;
class Read2
{ public static void main(String args[]) throws IOException
{ //attach the file to FileInputStream
FileInputStream fin = new FileInputStream ("myfile");
BufferedInputStream bin = new BufferedInputStream (fin);
YASEEN’S Page 110
J2SE CORE JAVA MATERIAL 2022
Program 5: Write a program to create a text file using character or text stream classes.
//Creating a text file using character (text) stream classes
import java.io.*;
class Create3
{ public static void main(String args[]) throws IOException
{ String str = "This is an Institute" + "\n You are a student"; // take a String
//Connect a file to FileWriter
FileWriter fw = new FileWriter ("textfile");
//read chars from str and send to fw
for (int i = 0; i<str.length () ; i++)
fw.write (str.charAt (i) );
fw.close ();
}
}
Output:
Program 6: Write a program to read a text file using character or text stream classes.
//Reading data from file using character (text) stream classes
import java.io.*;
class Read3
{ public static void main(String args[]) throws IOException
Note: Use BufferedReader and BufferedWriter to improve the efficiency of the above two
programs.
Serialization of objects:
Serialization is the process of storing object contents into a file. The class whose objects
are
stored in the file should implement "Serializable' interface of java.io package.
Serializable interface is an empty interface without any members and methods, such an
interface is called 'marking interface' or 'tagging interface'.
Marking interface is useful to mark the objects of a class for a special purpose. For
example,
'Serializable' interface marks the class objects as 'serializable' so that they can be written
into
a file. If serializable interface is not implemented by the class, then writing that class
objects
into a file will lead to NotSerializableException.
static and transient variables cannot be serialized.
De-serialization is the process of reading back the objects from a file.
Program 7: Write a program to create Employ class whose objects is to be stored into a file.
//Employ information
import java.io.*;
import java.util.*;
class Employ implements Serializable
{ private int id;
private String name;
private float sal;
oos.writeObject (e1);
}
oos.close ();
fos.close ();
}
}
Output:
fis.close ();
}
}
}
Output:
File Class: File class of java.io package provides some methods to know the properties of a file
or a directory. We can create the File class object by passing the filename or directory name to it.
File obj = new File (filename);
File obj = new File (directoryname);
File obj = new File ("path", filename);
File obj = new File ("path", directoryname);
File class Methods:
20. Threads
Executing the tasks is of two types:
Single Tasking: Executing only one task at a time is called single tasking. In this single
tasking the microprocessor will be sitting idle for most of the time. This means micro
processor time is wasted.
Multi tasking: Executing more than one task at a time is called multi tasking.
Multitasking is
of two types:
Process Based Multitasking: Executing several programs simultaneously is called process
based multi tasking.
Thread Based Multitasking: Executing different parts of the same program
simultaneously
with the help of a thread is called thread based multitasking.
Advantage of multitasking is utilizing the processor time in an optimum way.
Java provides built-in support for multithreaded programming. A multithreaded program
contains two or more parts that can run concurrently. Each part of such a program is called a
thread. Thread is a smallest unit of code. Thread is also defined as a subprocess. A Thread
sometimes called an execution context or a light weight process.
Uses of Threads:
Threads are used in designing serverside programs to handle multiple clients at a time.
Threads are used in games and animations.
Creating a Thread:
Write a class that extends Thread class or implements Runnable interface this is available
in
lang package.
Write public void run () method in that class. This is the method by default executed by
any
thread.
Create an object to that class.
Create a thread and attach it to the object.
Start running the threads.
Program 2: Write a program to create and run a Thread.
//creating and running a Thread
class MyThread extends Thread
{
public void run ()
{
for (int i = 0;i<100;i++)
{
System.out.print (i + "\t");
}
}
}
class TDemo
{ public static void main(String args[])
{ MyThread obj = new MyThread ();
Thread t = new Thread (obj);
t.start ();
}
}
Output:
Multi Tasking Using Threads: In multi tasking, several tasks are executed at a time. For this
purpose, we need more than one thread. For example, to perform 2 tasks we can take 2 threads
and attach them to the 2 tasks. Then those tasks are simultaneously executed by the two threads.
Using more than one thread is called ‘multi threading’.
Program 3: Write a program to create more than one thread.
//using more than one thread is called Multi Threading
class Theatre extends Thread
{ String str;
Theatre (String str)
{ this.str = str;
}
public void run()
{ for (int i = 1; i <= 10 ; i++)
{ System.out.println (str + " : " + i);
try
{ Thread.sleep (2000);
}
catch (InterruptedException ie) { ie.printStackTrace (); }
}
}
}
class TDemo1
{ public static void main(String args[])
{ Theatre obj1 = new Theatre ("Cut Ticket");
Theatre obj2 = new Theatre ("Show Chair");
Thread t1 = new Thread (obj1);
Thread t2 = new Thread (obj2);
t1.start ();
t2.start ();
}
}
Output:
In the preceding example, we have used 2 threads on the 2 objects of TDemo1 class. First
we have taken a String variable str in Theatre class. Then we passed two strings- cut ticket and
show chair into that variable from TDemo1 class. When t1. start () is executed, it starts execution
run () method code showing cut ticket. Note that in run () method, we used: Thread. sleep (2000)
is a static method in Thread class, which is used to suspend execution of a thread for some
specified milliseconds. Since this method can throw InterruptedException, we caught it in catch
block. When Thread t1 is suspended immediately t2. start () will make the thread t2 to execute
and when it encounters Thread.sleep(2000), it will suspend for specified time meanwhile t1 will
get executed respectively. In this manner, both the threads are simultaneously executed.
Multiple Threads Acting on Single Object: When two people (threads) want to perform same
task then they need same object (run () method) to be executed each time. Take the case of
railway reservation. Every day several people want reservation of a berth for them. The
procedure to reserve the berth is same for all the people. So we need some object with same run
() method to be executed repeatedly for all the people (threads).
Let us think that only one berth is available in a train and two passengers (threads) are
asking for that berth in two different counters. The clerks at different counters sent a request to
the server to allot that berth to their passengers. Let us see now to whom that berth is allotted.
Program 4: Write a program to create multiple threads and make the threads to act on single
object.
Output:
If we would not use synchronized (this) block in the preceding program then when thread
t1 enter into the run () method, it sees available number of berths as 1 and hence it allots it to
First Person and displays “1 Berths reserved for First Person”. Then it enters try { } block inside
run () method, where it will sleep for 2 seconds. In this time, the ticket will be printed on the
printer. When the first thread is sleeping thread t2 also enters the run () method, it also sees that
there is 1 berth remaining. The reason is for this is that the available number of berths is not yet
updated by the first thread. So the second thread also sees 1 berth as available and it allots the
same berth to the Second Person. Then the thread t2 will also go into sleep state. Thread t1
wakes up first and then it updates the available number of berths to zero (0). But at the same time
the second thread has already allotted the same berth to the Second Person also. Since both the
threads are acting on the same object simultaneously, the result will be unreliable.
In this way, BookTicket thread keeps on waiting for the CancelTicket thread to unlock the
compartment object and the CancelTicket thread keeps on waiting for the BookTicket to unlock
the train object. Both the threads will wait forever in this way, this situation is called DealLock.
{
Thread.sleep (2000);
}
catch (InterruptedException ie)
{
}
System.out.println ("Book ticket tries to lock train object...");
synchronized (comp)
{
System.out.println ("Book ticket has locked compartment...");
}
}
}
}
class Dead
{ public static void main (String args[])
{ Object train = new Object ();
Object compartment = new Object ();
CancelTicket obj1 = new CancelTicket (train, compartment);
BookTicket obj2 = new BookTicket (train, compartment);
Thread t1 = new Thread (obj1);
Thread t2 = new Thread (obj2);
t1.start ();
t2.start ();
}
}
Output:
There is no specific solutioin for preventing deadlock. The programmer should exercise
proper caution while planning the logic of the program to avoid deadlocks.
Thread Communication: In some cases two or more threads should communicate with each
other. One thread output may be send as input to other thread. For example, a consumer thread is
waiting for a Producer to produce the data (or some goods). When the Producer thread completes
production of data, then the Consumer thread should take that data and use it.
In producer class we take a StringBuffer object to store data, in this case; we take some numbers
from 1 to 5. These numbers are added to StringBuffer object. Until producer completes placing
the data into StringBuffer the consumer has to wait. Producer sends a notification immediately
after the data production is over.
}
}
class Communicate
{ public static void main(String args[])
{
Producer obj1 = new Producer ();
Consumer obj2 = new Consumer (obj1);
Thread t1 = new Thread (obj1);
Thread t2 = new Thread (obj2);
t2.start ();
t1.start ();
}
}
Output:
Both sleep () and wait () methods are used to suspend a thread execution for a specified time.
When sleep () is executed inside a synchronized block, the object is still under lock.When wait ()
method is executed, it breaks the synchronized block, so that the object lock is removed and it is
available.
Thread Group: A ThreadGroup represents a group of threads. The main advantage of taking
several threads as a group is that by using a single method, we will be able to control all the
threads in the group.
Creating a thread group: ThreadGroup tg = new ThreadGroup (“groupname”);
To add a thread to this group (tg): Thread t1 = new Thread (tg, targetobj, “threadname”);
To add another thread group to this group (tg):
ThreadGroup tg1 = new ThreadGroup (tg, “groupname”);
To know the parent of a thread: tg.getParent ();
To know the parent thread group: t.getThreadGroup ();
This returns a ThreadGroup object to which the thread t belongs.
To know the number of threads actively running in a thread group: t.activeCount ();
To change the maximum priority of a thread group tg: tg.setMaxPriority ();
Program 7: Write a program to demonstrate the creation of thread group.
//Using ThreadGroup
YASEEN’S Page 127
J2SE CORE JAVA MATERIAL 2022
import java.io.*;
class WhyTGroups
{ public static void main (String args[]) throws IOException
{ Reservation res = new Reservation ();
Cancellation can = new Cancellation ();
//Create a ThreadGroup
ThreadGroup tg = new ThreadGroup ("Reservation Group");
//Create 2 threads and add them to thread group
Thread t1 = new Thread (tg, res, "First Thread");
Thread t2 = new Thread (tg, res, "Second Thread");
//Create another thread group as a child to tg
ThreadGroup tg1 = new ThreadGroup (tg, "Cancellation Group");
Thread t3 = new Thread (tg1, can, "Third Thread");
Thread t4 = new Thread (tg1, can, "Fourth Thread");
//find parent group of tg1
System.out.println ("Parent of tg1 = " + tg1.getParent ());
//set maximum priority
tg1.setMaxPriority (7);
System.out.println ("Thread group of t1 = " + t1.getThreadGroup ());
System.out.println ("Thread group of t3 = " + t3.getThreadGroup ());
t1.start ();
t2.start ();
t3.start ();
t4.start ();
System.out.println ("Number of threads in this group : " + tg.activeCount () );
}
}
class Reservation extends Thread
{ public void run ()
{ System.out.println ("I am Reservation Thread");
}
}
class Cancellation extends Thread
{ public void run ()
{ System.out.println ("I am Cancellation Thread");
}
}
Output:
Thread States (Life-Cycle of a Thread): The life cycle of a thread contains several states. At
any time the thread falls into any one of the states.
The thread remains in this state until the threads start method is called. This causes the
thread
to enter the ready state.
The highest priority ready thread enters the running state when system assigns a
processor to
the thread i.e., the thread begins executing.
When a running thread calls wait the thread enters into a waiting state for the particular
object on which wait was called. Every thread in the waiting state for a given object
becomes
ready on a call to notify all by another thread associated with that object.
When a sleep method is called in a running thread that thread enters into the suspended
(sleep) state. A sleeping thread becomes ready after the designated sleep time expires. A
sleeping thread cannot use a processor even if one is available.
A thread enters the dead state when its run () method completes (or) terminates for any
reason. A dead thread is eventually be disposed of by the system.
One common way for a running thread to enter the blocked state is when the thread issues
an
input or output request. In this case a blocked thread becomes ready when the input or
output
waits for completes. A blocked thread can’t use a processor even if one is available.
Classes of AWT
A window represents a box shaped area on the screen. Window does not have border and title.
A Frame is a top level window that is not contained in another window. A Frame contains border
and title.
Creating the Frame:
We can create a Frame by creating Frame class object. Frame obj = new Frame ();
(or)
Create a class that extends Frame class then create an object to that class.
class MyClass extends Frame
MyClass obj = new MyClass ();
After creating the Frame we need to set Frame width and height using setSize () method
as:
f.setSize (400, 350);
We can display the frame using setVisible () method as:
f.setVisible (true);
Program 1: Write a program to create a Frame without extending Frame class.
//creating a Frame
YASEEN’S Page 131
J2SE CORE JAVA MATERIAL 2022
import java.awt.*;
class MyFrame
{
public static void main(String args[])
{ Frame f1 = new Frame ();
f1.setSize (500,150);
f1.setTitle ("GUI World");
f1.setVisible (true);
}
}
Output:
The frame can be minimized, maximized and resized but cannot be closed. Even if we click on
close button of the frame, it will not perform any closing action. Closing a frame means attaching
action to the component. To attach actions to the components, we need ‘Event Delegation
Model’.
Event-Delegation-Model: Graphical representation of an object is called a component. User
interaction with the component is called event. When an event is generated by the user on the
component, component will delegate (hand over) the event to the listener. The listener will
delegate the event to one of its method. The method is finally executed and the event is handled.
This is called Event-Delegation-Model. Event-Delegation-Model is used in awt to provide
actions for components. In Event Delegation Model:
Attach the Listener to the component.
Implement all the methods of the Listener.
When an Event is generated one of these methods performs the required action.
Closing the Frame: We know Frame is also a component. We want to close the frame by
clicking on its close button. Let us follow these steps to see how to use event delegation model to
do this:
We should attach a listener to the frame component. Remember, all listeners are available
in
java.awt.event package. The most suitable listener to the frame is ‘WindowListener’. It
can
be attached using addWindowListener () method as:
f.addWindowListener (WindowListener obj);
Please note that the addWindowListener () method has a parameter that is expecting
object of
WindowListener interface. Since it is not possible to create an object to an interface, we
should create an object to the implementation class of the interface and pass it to the
method.
Implement all the methods of the WindowListener interface. The following methods are
found in WindowListener interface:
public void windowActivated (WindowEvent e)
public void windowClosed (WindowEvent e)
public void windowClosing (WindowEvent e)
public void windowDeactivated (WindowEvent e)
We cannot find the name of MyClass anywhere in the code. It means the name of MyClass is
hidden in MyFame class and hence MyClass is an inner class in MyFrame class whose name is
not mentioned. Such an inner class is called ‘anonymous inner class’. An anonymous inner class
is an inner class whose name is not written and for which only one object is created. A class for
which only one object is created is called singleton class.
Displaying text in the Frame: We need paint () method whenever we want to display some new
drawing or text or images in the Frame. The paint () method is automatically called when a frame
is created and displayed. The paint () method refreshes the frame contents automatically when a
drawing is displayed. The paint () method takes Graphics Class object as parameter. Gaphics
class is present in java.awt package.
To display some text or strings in the frame, we can take the help of drawstring () method
of
Graphics class as:
g.drawString (“Hai Readers”, x, y);
Here, the string “Hai Readers” will be displayed starting from the coordinates (x, y).
If we want to set some color for the text, we can use setColor () method of Graphics class
as:
g.setColor (Color.red);
There are two ways to set a color in awt.
The first way is by directly mentioning the needed standard color name from Color class
as Color.black, Color.blue, Color.cyan, Color.pink, Color.red, Color.orange,
Color.magenta, Color.darkGray, Color.gray, Color.lightGray, Color.green, Color.yellow
and Color.white etc.
The second way to mention any color is by combining the three primary colors: red,
green and blue while creating Color class object as:
Color c = new Color (r, g, b);
Here, r, g, b values can change from 0 to 255. 0 represents no color. 10 represent low
intensity whereas 200 represent high intensity of color.
e.g.: Color c = new Color (255, 0, 0); //red color
To set some font to the text, we can use setFont () method of Graphics class, as:
g.setFont (Font object);
This method taked Font class object, which can be created as:
Font f = new Font (“SansSerif”, Font.BOLD, 30);
Here, “SansSerif” represents the font name; Font.BOLD represents the font style and 30
represents the font size in pixels.
Program 4: Write a program to display a message in the frame.
//Displaying a message in the frame
import java.awt.*;
import java.awt.event.*;
class Message extends Frame
{ Message ()
{ //code to close the Frame
this.addWindowListener (new WindowAdapter ()
{ public void windowClosing (WindowEvent we)
{
System.exit (0);
}
});
}
public static void main (String args[])
{ Message m = new Message ();
m.setTitle ("Simple Message");
m.setSize (650,150);
m.setVisible (true);
}
public void paint (Graphics g)
{ this.setBackground (Color.green);
g.setColor (Color.red);
Font f = new Font ("Times New Roman", Font.BOLD+Font.ITALIC, 60);
g.setFont (f);
g.drawString ("Hello Readers!”, 50, 100);
}
}
Output:
Drawing in the Frame: Graphics class of java.awt package has the following methods which
help to draw various shapes.
drawLine (int x1, int y1,int x2, int y2): to draw a line connecting (x1, y1) and (x2, y2).
drawRect (int x, int y, int w, int h): draws outline of the rectangle, rectangles top left
corner
starts at (x, y) the width is w and height is h.
drawRoundRect (int x, int y, int w, int h, int arcw, int arch): draws the outline of the
rectangle with rounded corners. Rectangles top left corner starts at (x, y) the width is w
and
height is h. The rounding is specified by arcw and arch.
drawOval (int x, int y, int w, int h): This method draws a circle or ellipse.
drawArc(int x, int y, int w, int h, int sangle, int aangle): draws an arc where sangle stands
for starting angle and aangle stands for ending angle.
drawPolygon (int x[], int y[], int n): This method draws a polygon that connects pairs of
coordinates . Here, x[] is an array which holds x coordinates of points and y[] is an array
which holds y coordinates, n represents the number of pairs of coordinates.
To fill any shape with a desired color, first of all we should set a color using setColor () method.
Then any of the following methods will draw those respective shapes by filling with the color.
fillRect (int x, int y, int w, int h): Draws a rectangle and fills it with the specified color.
drawRoundRect (int x, int y, int w, int h, int arcw, int arch): Draws filled rectangle with
rounded corners.
drawOval (int x, int y, int w, int h): Draws filled oval with a specified color.
drawArc(int x, int y, int w, int h, int sangle, int aangle): Draws an arc and fills it with a
specified color.
drawPolygon (int x[], int y[], int n): Draws and fills a polygon with a specified color.
Program 5: Write a program to draw different shapes in the frame.
//Program to draw different shapes
import java.awt.*;
import java.awt.event.*;
class Draw1 extends Frame
{
YASEEN’S Page 137
J2SE CORE JAVA MATERIAL 2022
Draw1 ()
{
this.addWindowListener (new WindowAdapter ()
{
public void windowClosing(WindowEvent we)
{
System.exit (0);
}
});
}
public static void main (String args[])
{
Draw1 d = new Draw1 ();
d.setTitle ("Simple Message");
d.setSize (650,350);
d.setVisible (true);
}
public void paint (Graphics g)
{
g.setColor (Color.blue);
g.drawLine (100, 100, 100, 200);
g.fillRect (50, 50, 100, 100);
g.fillRoundRect (300, 200, 100, 80, 10, 10);
g.fillOval (170, 150, 60, 40);
}
}
Output:
Method Description
Font getFont () This method returns the font of the component.
void setFont (Font f) This method sets a particular font f for the text of the
component.
Color getForeground () This method gives the foreground color of the
component.
void setForeground (Color c) This method sets a foreground color c to the component.
Color getBackground () Gets the background color of the component.
void setBackground (Color c) Sets the background color c for the component.
String getName () Returns the name of the component.
void setName (String name) Sets a new name for the component.
int getHeight () Returns the height of the component in pixels as an
integer.
int getWidth () Returns the width of the component in pixels as an
integer.
Dimension getSize () Returns the size of the component as an object of
Dimension class. Dimension.width and Dimension.height
will provide the width and height of the component.
int getX () Returns the current x coordinate of the components
origin.
After creating a component, we should add the component to the frame. For this purpose,
add
() method is used. f.add (component); where f is frame class object.
Similarly, to remove a component from the frame, we can use remove () method as:
f.remove (component); where f is frame class object.
Frame class contains a method called setLayout (). setLayout () is useful to set a layout
for
the frame. A layout represents a manner of arranging components in the frame. All
layouts
are represented as implementation classes of LayoutManager interface. For example, the
following layouts are available in AWT:
FlowLayout: FlowLayout is useful to arrange the components in a line after the other.
When a line is filled with components, they are automatically placed in the next line.
BorderLayout: BorderLayout is useful to arrange the components in the 4 borders of the
frame as well as in the center. The borders are specified as South, North, East, West and
Center.
CardLayout: A cardLayout treats each component as a card. Only one card is visible at a
time and it arranges the components as a stack of cards.
GridLayout: It is useful to divide the display area into a two dimensional grid form that
contains several rows and columns. The display area is divided into equal sized
rectangles and one component is placed in each rectangle.
GridBagLayout: This layout is more flexible as compared to other layouts since in this
layout the components can span more than one row or column and the size of the
components can be adjusted to fit the display area.
The following points are helpful to understand how to work with a layout manager:
To set a layout for out components, we can pass the layout class object to the setLayout ()
method as: setLayout (new FlowLayout ());
Suppose, we do not want to set any layout, then we should pass null to the setLayout ()
method as: setLayout (null);
Suppose, we do not use setLayout () method at all, then the Java compiler assumes a
default
layout manager. The default layout in case of a frame is BorderLayout.
Listeners and Listener Methods: Listeners are available for components. A Listener is an
interface that listens to an event from a component. Listeners are available in java.awt.event
package. The methods in the listener interface are to be implemented, when using that listener.
Component Listener Listener methods
Button ActionListener public void actionPerformed (ActionEvent e)
Checkbox ItemListener public void itemStateChanged (ItemEvent e)
TextField ActionListener public void actionPerformed (ActionEvent e)
FocusListener public void focusGained (FocusEvent e)
public void focusLost (FocusEvent e)
TextArea ActionListener public void actionPerformed (ActionEvent e)
FocusListener public void focusGained (FocusEvent e)
public void focusLost (FocusEvent e)
Choice ActionListener public void actionPerformed (ActionEvent e)
ItemListener public void itemStateChanged (ItemEvent e)
List ActionListener public void actionPerformed (ActionEvent e)
ItemListener public void itemStateChanged (ItemEvent e)
Scrollbar AdjustmentListener public void
MouseMotionListener adjustmentValueChanged (AdjustmentEvent
e)
public void mouseDragged (MouseEvent e)
public void mouseMoved (MouseEvent e)
Label No listener is needed
Creating Push Buttons: Button class is useful to create push buttons. A push button triggers a
series of events.
To create push button: Button b1 =new Button("label");
To get the label of the button: String l = b1.getLabel();
To set the label of the button: b1.setLabel("label");
To get the label of the button clicked: String str = ae.getActionCommand();
where ae is object of ActionEvent
Program 7: Write a program to create push buttons.
Checkbox: A Checkbox is a square shapped box which provides a set of options to the user.
To create a Checkbox: Checkbox cb = new Checkbox ("label");
To create a checked Checkbox: Checkbox cb = new Checkbox ("label", null, true);
To get the state of a Checkbox: boolean b = cb.getState ();
To set the state of a Checkbox: cb.setState (true);
To get the label of a Checkbox: String s = cb.getLabel ();
Program 8: Write a program to create checkboxes.
//Program to create checkboxes
import java.awt.*;
import java.awt.event.*;
class MyCheckbox extends Frame implements ItemListener
{
Checkbox cb1, cb2;
String msg;
MyCheckbox ()
{ setLayout (new FlowLayout ());
cb1 = new Checkbox ("Bold", null, true);
cb2 = new Checkbox ("Italic");
add (cb1);
add (cb2);
cb1.addItemListener (this);
cb2.addItemListener (this);
addWindowListener (new WindowAdapter ( )
{ public void windowClosing (WindowEvent we)
{
System.exit (0);
}
});
}
public void itemStateChanged (ItemEvent ie)
{
repaint ();
}
public static void main (String args[])
{ MyCheckbox ob = new MyCheckbox ();
ob.setTitle ("Checkbox Demo");
ob.setSize (500,200);
ob.setVisible (true);
}
public void paint (Graphics g)
{ g.drawString ("Checkbox state:", 20, 100);
msg = "Bold:" + cb1.getState() ;
g.drawString (msg, 20, 120);
msg = "Italic:" + cb2.getState();
g.drawString (msg, 20, 160);
}
}
Output:
Radio Button: A Radio button represents a round shaped button such that only one can be
selected from a panel. Radio button can be created using CheckboxGroup class and Checkbox
classes.
· To create a radio button: CheckboxGroup cbg = new CheckboxGroup ();
Checkbox cb = new Checkbox ("label", cbg, true);
· To know the selected checkbox: Checkbox cb = cbg.getSelectedCheckbox ();
· To know the selected checkbox label: String label = cbg.getSelectedCheckbox ().getLabel ();
Program 9: Write a program to create Radio Button.
//Program to create a Radio Button
import java.awt.*;
import java.awt.event.*;
Output:
Choice Menu: Choice menu is a popdown list of items. Only one item can be selected.
· To create a choice menu: Choice ch = new Choice();
· To add items to the choice menu: ch.add ("text");
· To know the name of the item selected from the choice menu:
String s = ch.getSelectedItem ();
· To know the index of the currently selected item: int i = ch.getSelectedIndex();
This method returns -1, if nothing is selected.
Program 10: Write a program to create a choice box.
//choice box
import java.awt.*;
import java.awt.event.*;
class MyChoice extends Frame implements ItemListener
{ Choice ch;
MyChoice ()
{ setLayout (new FlowLayout ());
ch = new Choice();
ch.add ("India");
ch.add ("Pakistan");
ch.add ("Afghanistan");
ch.add ("China");
ch.add ("Sri Lanka");
ch.add ("Bangladesh");
add (ch);
ch.addItemListener (this);
addWindowListener (new WindowAdapter()
{
public void windowClosing (WindowEvent we)
{
System.exit (0);
}
});
}
public void itemStateChanged (ItemEvent ie)
{ repaint ();
}
public void paint (Graphics g)
{ g.drawString ("U Selected: ", 20, 100);
g.drawString (ch.getSelectedItem (), 20, 120);
}
public static void main(String args[])
{ MyChoice ob = new MyChoice ();
ob.setSize (500,200);
ob.setTitle ("Choice Demo");
ob.setVisible (true);
}
}
Output:
List box: A List box is similar to a choice box, it allows the user to select multiple items.
To create a list box: List lst = new List();
(or)
List lst = new List (3, true);
This list box initially displays 3 items. The next parameter true represents that the user can select
more than one item from the available items. If it is false, then the user can select only one item.
To add items to the list box: lst.add("text");
To get the selected items: String x[] = lst.getSelectedItems();
To get the selected indexes: int x[] = lst.getSelectedIndexes ();
Program 11: Write a program to create a list box.
//List box
import java.awt.*;
import java.awt.event.*;
class MyList extends Frame implements ItemListener
{ List ch;
YASEEN’S Page 149
J2SE CORE JAVA MATERIAL 2022
int[] msg;
MyList ()
{ setLayout (new FlowLayout());
ch = new List(3,true);
ch.add ("India");
ch.add ("Pakistan");
ch.add ("Afghanistan");
ch.add ("China");
ch.add ("Sri Lanka");
ch.add ("Bangladesh");
add (ch);
ch.addItemListener (this);
addWindowListener (new WindowAdapter ()
{ public void windowClosing (WindowEvent we)
{ System.exit (0);
}
});
}
public void itemStateChanged (ItemEvent ie)
{ repaint ();
}
public void paint (Graphics g)
{ try
{ g.drawString ("U Selected:", 20, 150);
msg = ch.getSelectedIndexes ();
for (int i =0;i<msg.length; i++)
{ String item = ch.getItem (msg[i]);
g.drawString (item, 100, 150+i*20);
}
}catch (NullPointerException ie){}
}
public static void main (String args[])
{ MyList ob = new MyList ();
ob.setSize (500,200);
ob.setTitle ("List Demo");
ob.setVisible (true);
}
}
Output:
Scrollbar Class: Scrollbar class is useful to create scrollbars that can be attached to a frame or
text area. Scrollbars can be arranged vertically or horizontally.
To create a scrollbar : Scrollbar sb = new Scrollbar (alignment, start, step, min, max);
alignment: Scrollbar.VERTICAL, Scrollbar.HORIZONTAL
start: starting value (e.g. 0)
step: step value (e.g. 30) // represents scrollbar length
min: minimum value (e.g. 0)
max: maximum value (e.g. 300)
To know the location of a scrollbar: int n = sb.getValue ();
To update scrollbar position to a new position: sb.setValue (int position);
To get the maximum value of the scrollbar: int x = sb.getMaximum ();
To get the minimum value of the scrollbar: int x = sb.getMinimum ();
To get the alignment of the scrollbar: int x = getOrientation ();
This method return 0 if the scrollbar is aligned HORIZONTAL, 1 if aligned VERTICAL.
Program 13: Write a program to create a vertical scrollbar with scroll button length 30 px and
with the starting and ending positions ranging from 0 to 400 px.
//Creating a vertical scrollbar
import java.awt.*;
import java.awt.event.*;
class MyScroll extends Frame implements AdjustmentListener
{ String msg = "";
Scrollbar sl;
MyScroll ()
{ setLayout (null);
sl = new Scrollbar (Scrollbar.VERTICAL, 0, 30, 0, 400);
sl.setBounds (250, 50, 30, 200);
add (sl);
sl.addAdjustmentListener (this);
YASEEN’S Page 153
J2SE CORE JAVA MATERIAL 2022
Handling Mouse Events: The user may click, release, drag or move a mouse while interacting
with the application. If the programmer knows what the user has done, he can write the code
YASEEN’S Page 154
J2SE CORE JAVA MATERIAL 2022
according to the mouse event. To trap the mouse events, MouseListener and
MouseMotionListener interfaces of jav.awt.event package are used.
MouseListener interface contains the following methods:
{ int x,y;
MouseEvents ()
{ setLayout (new FlowLayout());
addMouseListener (this);
addMouseMotionListener (this);
addWindowListener (new WindowAdapter ()
{ public void windowClosing (WindowEvent we)
{ System.exit (0);
}
});
}
public void paint (Graphics g)
{ g.drawString (x +" , "+ y, x, y);
}
public void mouseClicked (MouseEvent me)
{ setBackground (Color.yellow);
}
public void mousePressed(MouseEvent me)
{ setBackground (Color.red);
}
public void mouseReleased(MouseEvent me)
{ setBackground (Color.green);
}
public void mouseEntered (MouseEvent me)
{ setBackground (Color.blue);
}
public void mouseExited(MouseEvent me)
{ setBackground (Color.white);
}
public void mouseDragged(MouseEvent me)
{ setBackground (Color.black);
}
public void mouseMoved(MouseEvent me)
{ x = me.getX (); y = me.getY ();
setBackground (Color.cyan);
repaint ();
}
public static void main(String args[])
{ MouseEvents ob = new MouseEvents ();
ob.setSize(600,200);
ob.setVisible(true);
}
}
Output:
Handling Keyboard Events: A user interacts with the application by pressing keys on the
keyboard. A programmer should know which key the user has pressed on the keyboard. These
are also called ‘events’. Knowing these events will enable the programmer to write his code
according to the key pressed. KeyListener interface of java.awt.event package helps to know
which key is pressed or released by the user. It has 3 methods:
Method Description
public void keyPressed (KeyEvent ke) This method is called when a key is pressed on
the keyboard. This include any key on the
keyboard along with special keys like function
keys, shift, alter, caps lock, home and end etc.
public void keyTyped (KeyEvent ke) This method is called when a key is typed on
the
keyboard. This is ame as keyPressed () method
but this method is called when general keys
like A to Z or 1 to 9 etc are typed. It cannot
work with special keys.
public void keyReleased (KeyEvent ke) This method is called when a key is released.
KeyEvent class has the following methods to know which key is typed by the user:
Method Description
char getKeyChar () This method returns the key name (or
character)
related to the key pressed or released.
int getKeyCode () This method returns an integer number which
is the value of the key pressed by the user.
The following are the key codes for the keys on the keyboard. They are defined as constants in
YASEEN’S Page 157
J2SE CORE JAVA MATERIAL 2022
}
public void keyTyped (KeyEvent ke)
{
}
public static void main (String args[])
{ KeyBoardEvents ob = new KeyBoardEvents ();
ob.setTitle ("Key demo");
ob.setSize (600,450);
ob.setVisible (true);
}
}
Output:
22. Swings
When awt components are created, internally native methods (c language functions) are executed
which create peer component (equivalent component). awt components are heavy weight
components. The look and feel of awt component change depending upon the operating system.
JFC represents a class library that is extended from awt. JFC stands for Java Foundation Classes.
JFC is an extension of the original awt, it does not replace awt. JFC components are light weight
components, they take less system resources.
Creating a Frame:
Create an object to JFrame: JFrame ob = new JFrame ("title");
(or)
Create a class as subclass to JFrame class: MyFrame extends JFrame
Create an object to that class : MyFrame ob = new MyFrame ();
Program 1: Write a program to create a frame by creating an object to JFrame class.
//A swing Frame
import javax.swing.*;
class MyFrame
{
public static void main (String agrs[])
{ JFrame jf = new JFrame ("My Swing Frame...");
jf.setSize (400,200);
jf.setVisible (true);
jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
}
Output:
Note: To close the frame, we can take the help of getDefaultCloseOperation () method of
JFrame class, as shown here:
getDefaultCloseOperation (constant);
where the constant can be any one of the following:
JFrame.EXIT_ON_CLOSE: This closes the application upon clicking on close button.
JFrame.DISPOSE_ON_CLOSE: This disposes the present frame which is visible on the
screen. The JVM may also terminate.
JFrame.DO_NOTHING_ON_CLOSE: This will not perform any operation upon
clicking on close button.
JFrame.HIDE_ON_CLOSE: This hides the frame upon clicking on close button.
Window Panes: In swings the components are attached to the window panes only.A window
pane represents a free area of a window where some text or components can be displayed. For
example, we can create a frame using JFrame class in javax.swing which contains a free area
inside it, this free area is called 'window pane'. Four types of window panes are available in
javax.swing package.
Glass Pane: This is the first pane and is very close to the monitors screen. Any
components
to be displayed in the foreground are attached to this glass pane. To reach this glass
pane, we
use getGlassPane () method of JFrame class.
Root Pane: This pane is below the glass pane. Any components to be displayed in the
background are displayed in this pane. Root pane and glass pane are used in animations
also.
For example, suppose we want to display a flying aeroplane in the sky. The aeroplane
can be
displayed as a .gif or .jpg file in the glass pane where as the blue sky can be displayed in
the
root pane in the background. To reach this root pane, we use getRootPane () method of
JFrame class.
Layered Pane: This pane lies below the root pane. When we want to take several
components as a group, we attach them in the layered pane. We can reach this pane by
calling getLayeredPane () method of JFrame class.
Content Pane: This is the bottom most pane of all. Individual components are attached
to
this pane. To reach this pane, we can call getContentPane () method of JFrame class.
Displaying Text in the Frame: paintComponent (Graphics g) method of JPanel class is used to
paint the portion of a component in swing. We should override this method in our class. In the
following example, we are writing our class MyPanel as a subclass to JPanel and override the
painComponent () method.
Program 2: Wrire a program to display text in the frame.
import javax.swing.*;
import java.awt.*;
class MyPanel extends JPanel
{ public void paintComponent (Graphics g)
{ super.paintComponent (g); //call JPanel’s method
setBackground (Color.red);
g.setColor (Color.white);
g.setFont (new Font("Courier New",Font.BOLD,30));
g.drawString ("Hello Readers!", 50, 100);
}
}
class FrameDemo extends JFrame
{ FrameDemo ()
{
Container c = getContentPane ();
MyPanel mp = new MyPanel ();
c.add (mp);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{ FrameDemo ob = new FrameDemo ();
ob.setSize (600, 200);
ob.setVisible (true);
}
}
Output:
JComponent Class Methods: JComponent class of javax.swing package is the subclass of the
Component class of java.awt. So, whatever the methods are available in Component class are
also available to JComponent. This is the reason why almost all the methods of AWT are useful
in swing also. Additional methods found in JComponent are also applicable for the components
created in swing.
When a component is created, to dislay it in the frame, we should not attach it to the frame
directly as we did in AWT. On the other hand, the component should be attached to a window
pane.
To add the component to the content pane, we can write, as:
c.add (component); where c represents the content pane which is represented by
Container object.
Similarly, to remove the component we can use remove () method as:
c.remove (component);
To remove all the components from the content pane we can use removeAll () method as:
c.removeAll ();
When components are to be displayed in the frame, we should first set a layout which
arranges the components in a particular manner in the frame as:
c.setLayout (new FlowLayout ());
The following methods of JComponent class are very useful while handling the
components:
To set some background color to the component, we can use setBackground () method,
as:
component.setBackground (Color.yellow);
To set the foreground color to the component, we can use setForeground () method, as:
component.setForeground (Color.red);
To set some font for the text displayed on the component, we can use setFont () method.
We
should pass Font class object to this method, as:
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
JButton1 ob = new JButton1 ();
ob.setTitle ("Swing Frame example");
ob.setSize (600,250);
ob.setVisible (true);
}
}
Output:
Label:
To create a JLabel component: JLabel lbl = new JLabel ();
To set text to JLabel component: lbl.setText ("Hello");
To create a JLabel with text: JLabel lbl = new JLabel ("text", JLabel.RIGHT);
To create a JLabel with image: JLabel lbl = new JLabel (ImageIcon ii);
Program 4: Write a program to create a JLabel component.
//JLabelDemo
import javax.swing.*;
import java.awt.*;
class JLabelDemo extends JFrame
{ JLabel lbl;
ImageIcon ii;
JLabelDemo ()
{
Container c = getContentPane ();
YASEEN’S Page 165
J2SE CORE JAVA MATERIAL 2022
c.setLayout (null);
ii = new ImageIcon("abc.gif");
lbl = new JLabel(ii);
lbl.setBounds (100,100,200,200);
c.add (lbl);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{ JLabelDemo ob = new JLabelDemo ();
ob.setTitle ("Swing Frame example");
ob.setSize (600,250);
ob.setVisible (true);
}
}
Output:
bg.add (rb2);
bg.add (rb3);
To create a textfield: JTextField tf = new JTextField (20);
To create a text area: JTextArea ta = new JTextArea (5, 20);
Program 5: Write a program to create check boxes, radio buttons and text area components.
//Check boxes and radio buttons
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class CheckRadio extends JFrame implements ActionListener
{ JCheckBox cb1,cb2;
JRadioButton rb1,rb2;
ButtonGroup bg;
JTextArea ta;
String msg = "";
CheckRadio ()
{ Container c = getContentPane ();
c.setLayout (new FlowLayout ());
cb1 = new JCheckBox ("J2SE", true);
cb2 = new JCheckBox ("J2EE");
rb1 = new JRadioButton ("Male", true);
rb2 = new JRadioButton ("Female");
bg = new ButtonGroup();
bg.add (rb1);
bg.add (rb2);
ta = new JTextArea (5, 20);
c.add (cb1);
c.add (cb2);
c.add (rb1);
c.add (rb2);
c.add (ta);
cb1.addActionListener (this);
cb2.addActionListener (this);
rb1.addActionListener (this);
rb2.addActionListener (this);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed (ActionEvent ae)
{ if (cb1.getModel ().isSelected ()) //to know the user selection
msg += "J2SE";
if (cb2.getModel ().isSelected ())
msg += "J2EE";
JComboBox class: JComboBox allows us to create a combo box, with a group of items which
are displayed as a drop down list. The user can select a single item only.
· To create an empty combo box: JComboBox box = new JComboBox ();
· To create a combo box with array of elements:
JComboBox box = new JComboBox (Object arr[]);
· To create a combo box with vector of elements:
JComboBox box = new JComboBox (Vector v);
· To add the items to the combo box: box.addItem (“ India”);
· To retrieve the selected item from the combo box: Object obj = box.getSelectedItem ();
· To retrieve the selected items index: int i = box.getSelectedIndex ();
· To get the item of combo box by giving index: Object obj = box.getItemAt (int index);
· To get number of items in the combo box: int n = box.getItemCount ();
· To remove an item obj from the combo box: box.removeItem (Object obj);
· To remove an item by giving index: box.removeItemAt (int index);
· To remove all items: box.removeAllItems ();
Program 6: Write a program to create a combo box with names of some countries.
//JComboBox Demo
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class JComboBoxDemo extends JFrame implements ItemListener
{ JComboBox box;
JLabel lbl;
JComboBoxDemo ()
{ Container c = getContentPane();
c.setLayout (null);
box = new JComboBox ();
box.addItem ("India");
box.addItem ("Pakistan");
box.addItem ("Afghanistan");
box.addItem ("China");
box.addItem ("Sri Lanka");
box.addItem ("Bangladesh");
box.setBounds (100, 50, 100, 30);
c.add (box);
box.addItemListener (this);
lbl = new JLabel ();
lbl.setBounds (100, 120,200,40);
c.add(lbl);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged (ItemEvent ie)
{ String str = (String) box.getSelectedItem ();
lbl.setText ("You Selected : " + str);
}
public static void main(String args[])
{ JComboBoxDemo ob = new JComboBoxDemo ();
ob.setSize (500,250);
ob.setTitle ("My Combo Box Demo");
ob.setVisible (true);
}
}
Output:
JList Class: JList class is useful to create a list which displays a list of items and allows the user
to select one or more items.
· To create an empty list: JList lst = new JList();
· To create a list with the array of elements: JList lst = new JList (Object arr []);
· To create a list with vector of elements: JList lst = new JList (Vector v);
· To know which item is selected in the list: Object item = lst.getSelectedValue ();
· To know the selected items index: int index = lst.getSelectedIndex ();
· To get all the selected items into an array: Object arr [] = lst.getSelectedValues ();
· To get the indexes of all selected items: int arr[] = lst.getSelectedIndices ();
Program 7: Write a program to create a list box with names of some countries such that user can
select one or more items.
//JList Demo
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
class JListDemo extends JFrame implements ListSelectionListener
{ JList lst;
JLabel lbl;
Object arr [];
String msg="";
JListDemo ()
{ Container c = getContentPane();
c.setLayout (null);
String items [ ] = {"India","America","Germany","Japan","France"};
lst = new JList (items);
lst.setBounds(100,20,100,100);
c.add (lst);
lst.addListSelectionListener (this);
lbl = new JLabel ();
lbl.setBounds (100, 150,200,40);
c.add(lbl);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public void valueChanged (ListSelectionEvent le)
{ arr= lst.getSelectedValues ();
for ( int i=0;i<arr.length;i++)
msg += (String) arr [i];
lbl.setText ("You Selected : " + msg);
msg = "";
}
public static void main(String args[])
{ JListDemo ob = new JListDemo ();
ob.setSize (500,250);
ob.setTitle ("JListDemo");
ob.setVisible (true);
}
}
Output:
JTabbedPane: JTabbedPane is a container to add multiple components on every tab. The user
can choose a component from a tab.
To create a JTabbedPane: JTabbedPane jtp = new JTabbedPane ();
To add tabs: jtp.addTab ("title", object);
To create a Panel containing some components: class MyPanel extends JPanel
Now pass 'MyPanel' class object to addTab
()
To remove a tab (and its components) from the tabbedpane: jtp.removeTabAt (int
index);
To remove all the tabs and their corresponding components: jtp.removeAll ();
Program 8: Write a program to create a tabbed pane with two tab sheets.
//JTabbedPane demo
import java.awt.*;
import javax.swing.*;
class JTabbedPaneDemo extends JFrame
{ JTabbedPaneDemo ()
{ JTabbedPane jtp = new JTabbedPane ();
jtp.add ("Countries", new CountriesPanel ());
jtp.add ("Capitals", new CapitalsPanel ());
Container c = getContentPane ();
c.add (jtp);
}
public static void main(String args[])
{ JTabbedPaneDemo demo = new JTabbedPaneDemo ();
demo.setSize (600,450);
demo.setVisible (true);
demo.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
}
class CountriesPanel extends JPanel
{ CountriesPanel ()
{ JButton b1, b2, b3;
b1 = new JButton ("America");
b2 = new JButton ("India");
b3 = new JButton ("Japan");
add (b1); add (b2); add (b3);
}
}
class CapitalsPanel extends JPanel
{ CapitalsPanel ()
{ JCheckBox cb1 = new JCheckBox ("Washington");
JCheckBox cb2 = new JCheckBox ("New Delhi");
JCheckBox cb3 = new JCheckBox ("Tokyo");
add (cb1); add (cb2); add (cb3);
}
}
Output:
JTable: JTable represents data in the form of a table. The table can have rows of data, and
column headings.
To create a JTable: JTable tab = new JTable (data, column_names);
Here, data and column_names can be a 2D array or both can be vector of vectors.
To create a row using a vector: Vector row = new Vector();
row.add (object); //here object represents a column
row.add (object);
row.add (object);
}
public static void main(String args[])
{ JTableDemo demo = new JTableDemo ();
demo.setSize (600, 250);
demo.setVisible (true);
}
}
Output:
JMenu Class: A menu represents a group of items or options for the uset to select. To create a
menu, the following steps should be used:
· Create a menu bar using JMenuBar class object: JMenuBar mb = new JMenuBar ();
· Attach this member to the container. c.add (mb);
· Create separate menu to attach to the menubar. JMenu file = new JMenu ("File");
Note: Here, "File" is title for the menu which appear in the menubar.
· Attach this menu to the menubar. mb.add (file);
· Create menuitems using JMenuItem or JCheckBoxMenuItem or JRadioButtonMenuItem
classes. JMenuItem op = new JMenuITem ("Open");
· Attach this menuitem to the menu. file.add (op);
· Creating a submenu:
Create a menu: JMenu font = new JMenu ("Font");
Here, font represents a submenu to be attached to a menu.
Now attach it to a menu: file.add (font);
Attach menuitems to the font submenu. font.add (obj);
Note: obj can be a JMenuItem or JCheckBoxMenuItem or JRadioButtonMenuItem.
Program 10: Write a program to create a menu with several menu items.
//Menu Creation
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class MyMenu extends JFrame implements ActionListener
{ JMenuBar mb;
JMenu file, edit, font;
JMenuItem op, cl, cp, pt;
JCheckBoxMenuItem pr;
MyMenu ()
{ Container c = getContentPane ();
c.setLayout (new BorderLayout ());
mb = new JMenuBar ();
c.add ("North", mb);
//create file, edit menus
file = new JMenu ("File");
edit = new JMenu ("Edit");
//add menus to mb
mb.add (file);
mb.add (edit);
//create menuitems
op = new JMenuItem ("Open");
cl = new JMenuItem ("Close");
cp = new JMenuItem ("Copy");
pt = new JMenuItem ("Paste");
//add menu items to menus
file.add (op);
file.add (cl);
file.add (cp);
file.add (pt);
//disable close
cl.setEnabled (false);
//create checkbox menu item
pr = new JCheckBoxMenuItem ("Print");
//add checkbox menu item to file menu
file.add (pr);
//display line (separator)
file.addSeparator ();
//create submenu
font = new JMenu ("Font");
//add this submenu in file
file.add (font);
//add menu items to font
font.add ("Arial");
font.add ("Times New Roman");
Layout Manager: Layout Manager is an interface that arranges the components on the screen.
Layout Manager is implemented in the following classes:
FlowLayout, BorderLayout, CardLayout, GridLayout, GridBagLayout
FlowLayout: FlowLayout is useful to arrange the components in a line after the other. When a
line is filled with components, they are automatically placed in the next line.
Program 11: Write a program to create push buttons and arrange them using flow layout.
//Flow layout example
import javax.swing.*;
import java.awt.*;
class Example1 extends JFrame
{ Example1 ()
{ Container c = getContentPane ();
c.setLayout(new FlowLayout(FlowLayout.LEFT,20,40));
// where 20 and 40 specifies hgap and vgap respectively.
JButton b1 = new JButton ("First");
JButton b2 = new JButton ("Second");
JButton b3 = new JButton ("Third");
//add(c);
c.add (b1); c.add (b2); c.add (b3);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{ Example1 ob = new Example1 ();
ob.setTitle ("Flow Layout...");
ob.setSize (600,250);
ob.setVisible (true);
}
}
Output:
BorderLayout: BorderLayout is useful to arrange the components in the 4 borders of the frame
as well as in the center. The borders are specified as South, North, East, West and Center.
Program12: Write a program to create push buttons and arrange them using border layout.
//Border layout example
import javax.swing.*;
import java.awt.*;
class Example2 extends JFrame
{ Example2 ()
{ Container c = getContentPane ();
c.setLayout (new BorderLayout ());
JButton b1 = new JButton ("First");
JButton b2 = new JButton ("Second");
JButton b3 = new JButton ("Third");
JButton b4 = new JButton ("Fourth");
JButton b5 = new JButton ("Fifth");
//add(c);
c.add (b1,"North"); c.add (b2,"South"); c.add (b3, "Center");
c.add (b4,"East"); c.add (b5,"West");
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{ Example2 ob = new Example2 ();
ob.setTitle ("Border Layout...");
ob.setSize (600,250);
ob.setVisible (true);
}
}
Output:
CardLayout: A cardLayout is a layout managere which treats each component as a card. Only
one card is visible at a time and the container acts as a stack of cards.
Program 13: Write a program to create push buttons and arrange them using border layout.
//Card layout example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Example3 extends JFrame implements ActionListener
{ Container c;
CardLayout card;
Example3 ()
{ c = getContentPane ();
card = new CardLayout (50,50);
c.setLayout (card);
JButton b1 = new JButton ("First");
JButton b2 = new JButton ("Second");
JButton b3 = new JButton ("Third");
c.add ("button1", b1);
c.add ("button2", b2);
c.add("button3", b3);
b1.addActionListener (this);
b2.addActionListener (this);
b3.addActionListener (this);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
card.next(c); // when a button is clicked show the next card.
}
public static void main(String args[])
GridLayout: It is useful to divide the container into a two dimensional grid form that contains
several rows and columns. The container is divided into equal sized rectangles and one
component is placed in each rectangle. GridLayout (), GridLayout (int rows, int cols),
GridLayout (int rows, int cols, int hgap, int vgap) are constructors.
Program 14: Write a program to create push buttons and arrange them using grid layout.
//Grid layout example
import javax.swing.*;
import java.awt.*;
class Example4 extends JFrame
{ Container c;
GridLayout grid;
Example4 ()
{ c = getContentPane ();
grid = new GridLayout (2,2,50,10);
c.setLayout (grid);
JButton b1 = new JButton ("First");
JButton b2 = new JButton ("Second");
JButton b3 = new JButton ("Third");
c.add ("button1",b1);
c.add ("button2",b2);
c.add ("button3",b3);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public static void main (String args[])
{ Example4 ob = new Example4 ();
ob.setTitle ("Grid Layout...");
ob.setSize (600,250);
ob.setVisible (true);
}
}
Output:
GridBagLayout: This layout is more flexible as compared to other layouts since in this layout
the components can span more than one row or column and the size of the components can be
adjusted to fit the display area.
· To create grid bag layout: GridBagLayout obj = new GridBagLayout ();
· To apply some constraints on the components, we should first create an object to
GridBagConstraints class, as: GridBagConstraints cons = new GridBagConstraints ();
· GridBagConstraints.gridx, GridBagConstraints.gridy represents the row and column
positions of the component at upper left corner.
Output:
23. Applets
An applet is a program that comes from server into a client and gets executed at client side and
displays the result. An applet represents byte code embedded in a html page. (applet = bytecode
+ html) and run with the help of Java enabled browsers such as Internet Explorer. An applet is a
Java program that runs in a browser. Unlike Java applications applets do not have a main ()
method. To create applet we can use java.applet.Applet or javax.swing.JApplet class. All applets
inherit the super class ‘Applet’. An Applet class contains several methods that helps to control
the execution of an applet.
Advantages:
· Applets provide dynamic nature for a webpage.
· Applets are used in developing games and animations.
Creating an applet:
· Let the Applet class extends Applet or JApplet class.
· Overide the following methods of Applet class.
o public void init (): This method is used for initializing variables, parameters to create
components. This method is executed only once at the time of applet loaded into
memory.
o public void start (): After init() method is executed, the start method is executed
automatically. Start method is executed as long as applet gains focus. In this method code
related to opening files and connecting to database and retrieving the data and processing
the data is written.
o public void stop (): This mehtod is executed when the applet loses focus. Code related to
closing the files and database, stopping threads and performing clean up operations are
written in this stop method.
o public void destroy (): This method is exexuted only once when the applet is terminated
from the memory.
Executing above methods in that sequence is called applet life cycle. We can also use public
void paint (Graphics g) in applets.
After writing an applet, an applet is compiled in the same way as Java application but running of
an applet is different. There are two ways to run an applet.
· Executing an applet within a Java compatible web browser.
· Executing an applet using ‘appletviewer’. This executes the applet in a window.
To execute an applet using web browser, we must write a small HTML file which contains the
appropriate ‘APPLET’ tag. <APPLET> tag is useful to embed an applet into an HTML page. It
has the following form:
<APPLET CODE=”name of the applet class file” CODEBASE=”path of the applet class file”
HEIGHT = maximum height of applet in pixels WIDTH = maximum width of applet
in pixels ALIGN = alignment (LEFT, RIGHT, MIDDLE, TOP, BOTTOM)
ALT = alternate text to be displayed>
<PARAM NAME = parameter name VALUE = its value>
</APPLET>
The <PARAM> tag useful to define a variable (parameter) and its value inside the HTML page
which can be passed to the applet. The applet can access the parameter value using getParameter
() method, as:
String value = getParameter (“pname”);
Where pname is the parameter name and its value is retrieved.
The HTML file must be saved with .html extension. After creating this file, open the Java
compatible browser (Internet Explorer) and then load this file by specifying the complete path,
then Applet program will get executed.
In order to execute applet program with an applet viewer, simply include a comment at the head
of Java Source code file that contains the ‘APPLET’ tag.Thus, our code is documented with a
prototype of the necessary HTML statements and we can test out compiled applet by starting the
appletviewer with the Java file as: appletviewer programname.java
Program 1: Write an applet program with a message and display the message in paint () method.
/* <applet code="MyApplet.class" width = 600 height= 450>
</applet> */
import java.applet.Applet;
import java.awt.*;
public class MyApplet extends Applet
{ String msg="";
public void init()
{
msg += "init";
}
public void start()
{
msg +=" start";
}
public void paint(Graphics g)
{
g.drawString(msg,10,100);
}
public void stop()
{
msg += " stop";
}
public void destroy()
{
msg+= " destroy";
}
}
Output:
Program 2: Write a program to move an image from left to right in an Applet. To load an image
use Image class of java.awt.
/* <applet code="MyApplet1.class" width = 600 height= 450>
</applet> */
import java.applet.*;
import java.awt.*;
public class MyApplet1 extends Applet
{ public void paint (Graphics g)
{ Image i = getImage (getDocumentBase (),"plane.gif");
for (int x= 0 ; x<=800 ; x++)
{ g.drawImage (i, x, 0, null);
try
{ Thread.sleep (20);
}
catch(InterruptedException ie) { }
}
}
}
Output:
24.Swings
Swing is a set of classes that provides more powerful and flexible components than are possible
with the AWT. In addition to the familiar components, such as buttons, check boxes, and labels,
Swing supplies several exciting additions, including tabbed panes, scroll panes, trees, and tables.
Even familiar components such as buttons have more capabilities in Swing. For example, a
button may have both an image and a text string associated with it. Also, the image can be
changed as the state of the button changes. Unlike AWT components, Swing components are not
implemented by platform-specific code. Instead, they are written entirely in Java and, therefore,
are platform-independent. The term lightweight is used to describe such elements. The number of
classes and interfaces in the Swing packages is substantial, and this chapter provides an overview
of just a few. Swing is an area that you will want to explore further on your own.
The Swing component classes that are used in this book are shown here:
Class Description