OOPJ Course Content
OOPJ Course Content
UNIT-I
Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts,
coping with complexity, abstraction mechanisms. A way of viewing world – Agents,
responsibility, messages, methods, History of Java, Java buzzwords, data types, variables, scope
and lifetime of variables, arrays, operators, expressions, control statements, type conversion and
casting, simple java program, concepts of classes, objects, constructors, methods, access control,
this keyword, garbage collection, overloading methods and constructors, method binding,
inheritance, overriding and exceptions, parameter passing, recursion, nested and inner classes,
exploring string class.
When computers were first invented, programming was done manually by toggling in a
binary machine instructions by use of front panel.
As programs began to grow, high level languages were introduced that gives the
programmer more tools to handle complexity.
The first widespread high level language is FORTRAN. Which gave birth to structured
Programming in 1960’s. The Main problem with the high level language was they have
no specific structure and programs become larger; the problem of complexity also
increases.
So C became the popular structured oriented language to solve all the above problems.
However in SOP, when project reaches certain size its complexity exceeds. So in 1980’s
a new way of programming was invented and it was OOP. OOP is a programming
methodology that helps to organize complex programs through the use of inheritance,
encapsulation & polymorphism.
CSE,NRCM Page 1
Object Oriented Programming Through Java(23CY305)
Everything is an object.
Computation is performed by objects communicating with each other, requesting that
other objects perform actions. Objects communicate by sending & receiving messages. A
message is a request for an action bundled with whatever arguments may be necessary to
complete the task.
Each object has its own memory, which consists of other objects.
Every Object is an instance of class. A class simply represents a grouping of similar
objects, such as integers or lists.
The class is the repository for behavior associated with an object. That is all objects that
are instances of same class can perform the same actions.
Classes are organized into a singly rooted tree structure, called inheritance hierarchy.
OOP CONCEPTS
OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every
program is follows the concept of object. In other words, OOP is a way of writing programs
based on
CSE,NRCM Page 2
Object Oriented Programming Through Java(23CY305)
Class
Object
Encapsulation
Inheritance
Polymorphism
Abstraction
Class
Class is a blue print which is containing only list of variables and methods and no memory is
allocatedfor them. A class is a group of objects that has common properties.
Object
Encapsulation
Encapsulation is the process of combining data and code into a single unit.
In OOP, every object is associated with its data and code.
In programming, data is defined as variables and code is defined as methods.
The java programming language uses the class concept to implement encapsulation.
Inheritance
Inheritance is the process of acquiring properties and behaviors from one object to
another object or one class to another class.
In inheritance, we derive a new class from the existing class. Here, the new class acquires
the properties and behaviors from the existing class.
In the inheritance concept, the class which provides properties is called as parent class
and the class which recieves the properties is called as child class.
CSE,NRCM Page 3
Object Oriented Programming Through Java(23CY305)
Person
name,designationlearn(),
walk(),eat()
Polymorphism
Abstraction
Abstraction is hiding the internal details and showing only essential functionality.
In the abstraction concept, we do not show the actual implementation to the end user,
instead we provide only essential things.
For example, if we want to drive a car, we does not need to know about the internal
functionality like how wheel system works? how brake system works? how music system
works? etc.
Coping with complexity in Java, or any programming language, is an essential skill for
software developers.
As your Java projects grow in size and complexity, maintaining, debugging, and
extending yourcode can become challenging.
Here are some strategies to help you cope with complexity in Java:
CSE,NRCM Page 4
Object Oriented Programming Through Java(23CY305)
1. Modularization: Breaking down the code into smaller, self-contained modules, classes, or
packages to manage complexity. Each module should have a specific responsibility and interact
2. Design Patterns: Using established design patterns to solve common architectural and design
development.
3. Encapsulation: Restricting access to class members using access modifiers (public, private,
protected) to hide implementation details and provide a clear API for interacting with the class.
4. Abstraction: Creating abstract classes and interfaces to define contracts that classes must
adhere
explain how the code works, its purpose, and how to use it.
6. Testing: Implementing unit tests to ensure that individual components of the code function
7. Code Reviews: Collaborating with team members to review and provide feedback on code to
catch
8. Version Control: Using version control systems like Git to manage changes, track history, and
9. Refactoring: Regularly improving and simplifying the codebase by removing redundancy and
ABSTRACTION MECHANISM
CSE,NRCM Page 5
Object Oriented Programming Through Java(23CY305)
Let us consider a situation, I am at my office and I wish to get food to my family members who
are at my home from a hotel. Because of the distance from my office to home, there is no
possibility of getting food from a hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delevery community), tell them the
variety and quantity of food and the hotel name from which I wish to delever the food to my
familymembers. An object-oriented program is structured as a community of interacting agents,
called objects. Where each object provides a service (data and methods) that is used by other
members of the community.
In our example, the online food delivery system is a community in which the agents are zomato
and set of hotels. Each hotel provides a variety of services that can be used by other members
like zomato, myself, and my family in the community.
RESPONSIBILITIES
In our example, my request for action indicates only the desired outcome (food delivered to my
family). The agent (zomato) free to use any technique that solves my problem. By discussing a
problem in terms of responsibilities increases the level of abstraction. This enables more
independence between the objects in solving complex problems.
CSE,NRCM Page 6
Object Oriented Programming Through Java(23CY305)
To solve my problem, I started with a request to the agent zomato, which led to still more
requests among the members of the community until my request has done. Here, the members of
a community interact with one another by making requests until the problem has satisfied.
In our example, I send a request to zomato with a message that contains food items, the quantity
of food, and the hotel details. The receiver uses a method to food get delivered to my home.
HISTORY OF JAVA
CSE,NRCM Page 7
Object Oriented Programming Through Java(23CY305)
1. Simple
2. Secure
3. Portable
4. Object-oriented
5. Robust
6. Architecture-neutral (or) Platform Independent
7. Multi-threaded
8. Interpreted
9. High performance
10. Distributed
11. Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and code.
Most of the syntaxes in java follow basic programming language C and object-oriented
programming concepts are similar to C++.
In a java programming language, many complicated features like pointers, operator
overloading, structures, unions, etc. have been removed.
One of the most useful features is the garbage collector it makes java more simple.
Secure
Java is said to be more secure programming language because it does not have pointers
concept.
java provides a feature "applet" which can be embedded into a web application.
The applet in java does not allow access to other parts of the computer, which keeps
away from harmful programs like viruses and unauthorized access.
Portable
CSE,NRCM Page 8
Object Oriented Programming Through Java(23CY305)
Object-oriented
Robust
Java has invented to archive "write once; run anywhere, anytime, forever".
The java provides JVM (Java Virtual Machine) to archive architectural-neutral or
platform independent.
The JVM allows the java program created using one operating system can be executed on
any other operating system.
Multi-threaded
Interpreted
High performance
CSE,NRCM Page 9
Object Oriented Programming Through Java(23CY305)
Distributed
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a running
system and it has a dynamic memory allocation and deallocation (objects and garbage collector).
Java programming language has a rich set of data types. The data type is a category of data
stored in variables. In java, data types are classified into two types and they are as follows.
CSE,NRCM Page 10
Object Oriented Programming Through Java(23CY305)
The primitive data types are built-in data types and they specify the type of value stored in a
variable and the memory size.
Integer Data Types represent integer numbers, i.e numbers without any fractional parts or
decimal points.
-9223372036854775808to
long 8bytes 0L
+9223372036854775807
MinimumandMaximum
DataType MemorySize DefaultValue
values
-3.4e38to-1.4e-45and1.4e-45
float 4byte 0.0f
to3.4e38
-1.8e308to-4.9e-324and4.9e-
double 8bytes 0.0d
324to1.8e308
Note: Float data type can represent up to 7 digits accurately after decimal point.
Double data type can represent up to 15 digits accurately after decimal point.
Character data type are represents a single character like a, P, &, *,..etc.
CSE,NRCM Page 11
Object Oriented Programming Through Java(23CY305)
Boolean data types represent any of the two values, true or false. JVM uses 1 bit to represent a
Boolean value internally.
VARIABLES
Variable is a name given to a memory location where we can store different values of the same
data type during the program execution.
Declaration of Variable
Declaration of a variable tells to the compiler to allocate required amount of memory with
specified variable name and allows only specified datatype values into that memory location.
Example : int a;
Example : int a, b;
CSE,NRCM Page 12
Object Oriented Programming Through Java(23CY305)
Initialization of a variable:
In programming, a variable can be declared and defined inside a class, method, or block.
It defines the scope of the variable i.e. the visibility or accessibility of a variable.
Variable declared inside a block or method are not visible to outside.
If we try to do so, we will get a compilation error. Note that the scope of a variable can be
nested.
Lifetime of a variable indicates how long the variable stays alive in the memory.
1. local variable
2. instance variable
3. static variable
Local Variables
Variables declared inside the methods or constructors or blocks are called as local
variables.
The scope of local variables is within that particular method or constructor or block in
which they have been declared.
CSE,NRCM Page 13
Object Oriented Programming Through Java(23CY305)
Local variables are allocated memory when the method or constructor or block in which
they are declared is invoked and memory is released after that particular method or
constructor or block is executed.
Access modifiers cannot be assigned to local variables.
It can’t be defined by a static keyword.
Local variables can be accessed directly with their name.
Program
class LocalVariables
int a = 10;
int b = 20;
obj.show();
obj.display();
CSE,NRCM Page 14
Object Oriented Programming Through Java(23CY305)
Instance Variables:
Variables declared outside the methods or constructors or blocks but inside the class are
called as instance variables.
The scope of instance variables is inside the class and therefore all methods, constructors
and blocks can access them.
Instance variables are allocated memory during object creation and memory is released
during object destruction. If no object is created, then no memory is allocated.
For each object, a separate copy of instance variable is created.
Heap memory is allocated for storing instance variables.
Access modifiers can be assigned to instance variables.
It is the responsibility of the JVM to assign default value to the instance variables as per
the type of Variable.
Instance variables can be called directly inside the instance area.
Instance variables cannot be called directly inside the static area and necessarily requires
an object reference for calling them.
Program
class InstanceVariable
int x = 100;
x = x + 100;
CSE,NRCM Page 15
Object Oriented Programming Through Java(23CY305)
obj.show();
obj.display();
Static variables
Syntax: classname.variablename;
Example
class Employee
CSE,NRCM Page 16
Object Oriented Programming Through Java(23CY305)
empid++;
System.out.println("Employee id:"+empid);
class Sample
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();
ARRAYS
In java, there are two types of arrays and they are as follows.
CSE,NRCM Page 17
Object Oriented Programming Through Java(23CY305)
In the java programming language, an array must be created using new operator and with a
specific size. The size must be an integer value but not a byte, short, or long. We use the
following syntax to create an array.
Syntax
(or)
Example
class Onedarray
a[0]=10;
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<5;i++)
System.out.println(a[i]);
CSE,NRCM Page 18
Object Oriented Programming Through Java(23CY305)
Here, the size is automatically decided based on the number of values that are initialized.
Example
Multidimensional Array
In java, we can create an array with multiple dimensions. We can create 2-dimensional,
3- dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays.
To create a multidimensional array variable, specify each additional index using another
set of square brackets.
Syntax
(or)
When an array is initialized at the time of declaration, it need not specify the size of the
array and use of the new operator.
Here, the size is automatically decided based on the number of values that are initialized.
Example
class Twodarray
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
System.out.print(arr[i][j]+" ");
CSE,NRCM Page 19
Object Oriented Programming Through Java(23CY305)
System.out.println();
OPERATORS
An operator is a symbol that performs an operation. An operator acts on some variables called
Example: a + b
Types of Operators
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
6. Conditional operator
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modular
CSE,NRCM Page 20
Object Oriented Programming Through Java(23CY305)
class ArithmeticOperators
int a = 12, b = 5;
2. Relational Operators: Relational operators are used to compare two values and return a true
or
false result based upon that comparison. Relational operators are of 6 types
Operator Description
> Greaterthan
>= Greaterthanorequalto
< Lessthan
<= Lessthanorequalto
== Equalto
!= Notequalto
CSE,NRCM Page 21
Object Oriented Programming Through Java(23CY305)
class RelationalOperator
int a = 10;
int b = 3;
int c = 5;
3. Logical Operator: The Logical operators are used to combine two or more conditions
.Logical
2. Logical OR (||)
1. Logical AND (&&) : Logical AND is denoted by double ampersand characters (&&).it is used
to check the combinations of more than one conditions. if any one condition false the complete
condition becomes false.
CSE,NRCM Page 22
Object Oriented Programming Through Java(23CY305)
2. Logical OR ( || ) : Logical OR is denoted by double pipe characters (||). it is used to check the
combinations of more than one conditions. if any one condition true the complete condition
becomes true.
Condition1 !Condition2
True False
False True
Example of Logical Operators
class LogicalOp
int x=10;
CSE,NRCM Page 23
Object Oriented Programming Through Java(23CY305)
System.out.println(x==10 || x>=5));
4. Assignment Operator: Assignment operators are used to assign a value (or) an expression
(or) a value of a variable to another variable.
Example : x=10;
y=20;
class AssignmentOperator
int a = 4;
CSE,NRCM Page 24
Object Oriented Programming Through Java(23CY305)
int var;
var = a;
var += a;
var *= a;
5: Increment And Decrement Operators : The increment and decrement operators are very
useful. ++ and == are called increment and decrement operators used to add or subtract. Both are
unary operators.
Operator Meaning
++x PreIncrement
--x PreDecrement
x++ PostIncrement
x-- PostDecrement
Where
CSE,NRCM Page 25
Object Oriented Programming Through Java(23CY305)
Example
class Increment
int var=5;
System.out.println (var++);
System.out.println (++var);
System.out.println (var--);
System.out.println (--var);
6 : Conditional Operator: A conditional operator checks the condition and executes the
statement depending on the condition. Conditional operator consists of two symbols.
2 : colon ( : ).
It first evaluate the condition, if it is true (non-zero) then the “exp1” is evaluated, if the condition
is false (zero) then the “exp2” is evaluated.
Example :
class ConditionalOperator
CSE,NRCM Page 26
Object Oriented Programming Through Java(23CY305)
String result;
System.out.println(result);
7. Bitwise Operators:
Bitwise operators are used for manipulating a data at the bit level, also called as bit level
programming. Bit-level programming mainly consists of 0 and 1.
They are used in numerical Computations to make the calculation process faster.
The bitwise logical operators work on the data bit by bit.
Starting from the least significant bit, i.e. LSB bit which is the rightmost bit, working
towards the MSB (Most Significant Bit) which is the leftmost bit.
Operator Meaning
& BitwiseAND
| BitwiseOR
^ BitwiseXOR
~ BitwiseComplement
<< LeftShift
>> RightShift
1. Bitwise AND (&):
0 0 0
0 1 0
CSE,NRCM Page 27
Object Oriented Programming Through Java(23CY305)
1 0 0
1 1 1
Example :
int x = 10;
int y = 20;
x&y=?
x = 0000 1010
y = 0000 1011
2. Bitwise OR:
0 0 0
0 1 1
1 0 1
1 1 1
Example :
int x = 10;
int y = 20;
x|y=?
x = 0000 1010
y = 0000 1011
CSE,NRCM Page 28
Object Oriented Programming Through Java(23CY305)
x | y = 0000 1011 = 11
3. Bitwise Exclusive OR :
Example :
int x = 10;
int y = 20;
x^y=?
x = 0000 1010
y = 0000 1011
x ^ y = 0000 0001 = 1
Example :
x = 0000 1010
Example:
int x = 10;
x << 2 = ?
Example:
int x = 10;
x >> 2 = ?
EXPRESSIONS
CSE,NRCM Page 30
Object Oriented Programming Through Java(23CY305)
Expression Types
In the java programming language, expressions are divided into THREE types. They are as
follows.
Infix Expression
Postfix Expression
Prefix Expression
Infix Expression
The expression in which the operator is used between operands is called infix expression.
Example
a+b
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
Example
ab+
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
Example
+ab
CONTROL STATEMENTS
CSE,NRCM Page 31
Object Oriented Programming Through Java(23CY305)
In java, the selection statements are also known as decision making statements or branching
statements. The selection statements are used to select a part of the program to be executed based
on a condition.
if statement
if-else statement
if-elif statement
nested if statement
switch statement
if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of
statements based on that condition result.
The if statement checks, the given condition then decides the execution of a block of
statements. If the condition is True, then the block of statements is executed and if it is
False, then the block of statements is ignored.
Syntax
CSE,NRCM Page 32
Object Oriented Programming Through Java(23CY305)
if(condtion)
if-block of statements;
Example
int x=10;
if(x>0)
x++;
In the above execution, the number 12 is not divisible by 5. So, the condition becomes False and
the condition is evaluated to False. Then the if statement ignores the execution of its block of
statements.
In java, we use the if-else statement to test a condition and pick the execution of a block
of statements out of two blocks based on that condition result.
The if-else statement checks the given condition then decides which block of statements
to be executed based on the condition result.
If the condition is True, then the true block of statements is executed and if it is False,
then the false block of statements is executed.
Syntax
CSE,NRCM Page 33
Object Oriented Programming Through Java(23CY305)
if(condtion)
true-block of statements;
else
false-block of statements;
Example
int a=29;
if(a % 2==0)
else
Syntax
CSE,NRCM Page 34
Object Oriented Programming Through Java(23CY305)
if(condition_1)
if(condition_2)
...
...
Example
int num=1;
if(num<10)
if(num==1)
else
CSE,NRCM Page 35
Object Oriented Programming Through Java(23CY305)
else
Syntax
if(condition_1)
condition_1 true-block;
...
else if(condition_2)
condition_2 true-block;
...
Example
CSE,NRCM Page 36
Object Oriented Programming Through Java(23CY305)
int x = 30;
if( x == 10 )
System.out.print("Value of X is 10");
else if( x == 20 )
System.out.print("Value of X is 20");
else if( x == 30 )
System.out.print("Value of X is 30");
else
Switch
CSE,NRCM Page 37
Object Oriented Programming Through Java(23CY305)
Using the switch statement, one can select only one option from more number of options
very easily.
In the switch statement, we provide a value that is to be compared with a value associated
with each option. Whenever the given value matches the value associated with an option,
the execution starts from that option.
In the switch statement, every option is defined as a case.
Syntax:
switch (expression)
break;
break;
….
case valueN:
Example
class SampleSwitch
switch(color )
case 'r':
System.out.println("RED") ; break ;
CSE,NRCM Page 38
Object Oriented Programming Through Java(23CY305)
case 'g':
System.out.println("GREEN") ; break ;
case 'b':
System.out.println("BLUE") ; break ;
case 'w':
System.out.println("WHITE") ; break ;
default:
System.out.println("No color") ;
2.Iteration Statements
The java programming language provides a set of iterative statements that are used to
execute a statement or a block of statements repeatedly as long as the given condition is
true.
The iterative statements are also known as looping statements or repetitive statements.
Java provides the following iterative statements.
1. while statement
2. do-while statement
3. for statement
4. for-each statement
The while statement is used to execute a single statement or block of statements repeatedly as
long as the given condition is TRUE. The while statement is also known as Entry control looping
statement.
Syntax
while(condition)
CSE,NRCM Page 39
Object Oriented Programming Through Java(23CY305)
// body of loop
Example
int num = 1;
System.out.println(num);
num++;
Syntax
do
// body of loop
CSE,NRCM Page 40
Object Oriented Programming Through Java(23CY305)
} while (condition);
Example
int num = 1;
do
System.out.println(num);
num++;
The for statement is used to execute a single statement or a block of statements repeatedly as
long as the given condition is TRUE.
Syntax
// body
If only one statement is being repeated, there is no need for the curly braces.
CSE,NRCM Page 41
Object Oriented Programming Through Java(23CY305)
In for-statement, the execution begins with the initialization statement. After the initialization
statement, it executes Condition. If the condition is evaluated to true, then the block of
statements executed otherwise it terminates the for-statement. After the block of statements
execution, the modification statement gets executed, followed by condition again.
Example
3. Jump Statements
The java programming language supports jump statements that used to transfer execution control
1. break statement
2. continue statement
break
When a break statement is encountered inside a loop, the loop is terminated and program control
resumes at the next statement following the loop.
Example
CSE,NRCM Page 42
Object Oriented Programming Through Java(23CY305)
class BreakStatement
int i;
i=1;
while(true)
if(i >10)
break;
System.out.print(i+" ");
i++;
Continue
This command skips the whole body of the loop and executes the loop with the next iteration. On
finding continue command, control leaves the rest of the statements in the loop and goes back to
the top of the loop to execute it with the next iteration (value).
Example
class NumberExcept
CSE,NRCM Page 43
Object Oriented Programming Through Java(23CY305)
int i;
for(i=1;i<=10;i++)
if(i==5)
continue;
Type Casting
When a data type is converted into another data type by a programmer using the casting
operator while writing a program code, the mechanism is known as type casting.
In typing casting, the destination data type may be smaller than the source data type when
converting the data type to another data type, that’s why it is also called narrowing
conversion.
Syntax
destination_datatype = (target_datatype)variable;
target_datatype : is a data type in which we want to convert the source data type.
Example
float x;
byte y;
y=(byte)x;
Program
CSE,NRCM Page 44
Object Oriented Programming Through Java(23CY305)
double d = 166.66;
int i = (int)d;
Output
Type Conversion
If a data type is automatically converted into another data type at compile time is known
as type conversion.
The conversion is performed by the compiler if both data types are compatible with each
other.
Remember that the destination data type should not be smaller than the source type.
It is also known as widening conversion of the data type.
Example
int a = 20;
Float b;
Program
CSE,NRCM Page 45
Object Oriented Programming Through Java(23CY305)
int x = 7;
float y = x;
Output :
Documentation Section
The documentation section is an important section but optional for a Java program.
It includes basic information about a Java program. The information includes the author's name,
date of creation, version, program name, company name, and description of the program. It
improves the readability of the program. Whatever we write in the documentation section, the
Java compiler ignores the statements during the execution of the program. To write the
statements in the documentation section, we use comments.
CSE,NRCM Page 46
Object Oriented Programming Through Java(23CY305)
2. Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols.
Example : /* It is an example of
multiline comment */
3. Documentation Comment: It starts with the delimiter (/**) and ends with */.
Class sample
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
CSE,NRCM Page 47
Object Oriented Programming Through Java(23CY305)
System.out.println() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class.
WHAT IS JVM
Java Virtual Machine is the heart of entire java program execution process. It is responsible for
taking
the .class file and converting each byte code instruction into the machine language instruction
that can be executed by the microprocessor.
CSE,NRCM Page 48
Object Oriented Programming Through Java(23CY305)
CLASSES
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs)
that are used to represent real-world concepts and entities.
classes usually consist of two things: instance variables and methods.
The class represents a group of objects having similar properties and behavior.
For example, the animal type Dog is a class while a particular dog named Tommy is an
object of the Dog class.
It is a user-defined blueprint or prototype from which objects are created.
For example, Student is a class while a particular student named Ravi is an object.
The java class is a template of an object.
Every class in java forms a new data type.
Once a class got created, we can generate as many objects as we want.
Class Characteristics
1. Class is not a real-world entity. It is just a template or blueprint or prototype from which
objects are created.
Data member
Method
Constructor
Nested Class
Interface
Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties as
variables and behaviors as methods.
CSE,NRCM Page 49
Object Oriented Programming Through Java(23CY305)
Syntax
class className
methods definition;
The ClassName must begin with an alphabet, and the Upper-case letter is preferred.
The ClassName must follow all naming rules.
Example
Here is a class called Box that defines three instance variables: width, height, and depth.
class Box
double width;
double height;
double depth;
void volume()
………………….
OBJECT
CSE,NRCM Page 50
Object Oriented Programming Through Java(23CY305)
Syntax
The objectName must begin with an alphabet, and a Lower-case letter is preferred.
The objectName must follow all naming rules.
Example
Example
class Box
double width;
double height;
double depth;
class BoxDemo
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
CSE,NRCM Page 51
Object Oriented Programming Through Java(23CY305)
METHODS
A method is a block of statements under a name that gets executes only when it is called.
Every method is used to perform a specific task. The major advantage of methods is code
reusability (define the code once, and use it many times).
In a java programming language, a method defined as a behavior of an object. That
means, every method in java must belong to a class.
Every method in java must be declared inside a class.
Every method declaration has the following characteristics.
returnType - Specifies the data type of a return value.
name - Specifies a unique name to identify it.
parameters - The data values it may accept or recieve.
{ } - Defienes the block belongs to the method.
Creating a method
Syntax
class ClassName
// body of method
Calling a method
In java, a method call precedes with the object name of the class to which it belongs and
a dot operator.
It may call directly if the method defined with the static modifier.
Every method call must be made, as to the method name with parentheses (), and it must
CSE,NRCM Page 52
Object Oriented Programming Through Java(23CY305)
Syntax
objectName.methodName(actualArguments );
Example
Class Box
void volume()
System.out.print("Volume is ");
class BoxDemo3
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
CSE,NRCM Page 53
Object Oriented Programming Through Java(23CY305)
mybox2.height = 6;
mybox2.depth = 9;
mybox1.volume();
mybox2.volume();
CONSTRUCTORS
Constructor in Java is a special member method which will be called automatically by the
JVM whenever an object is created for placing user defined values in place of default
values.
In a single word constructor is a special member method which will be called
automatically whenever object is created.
The purpose of constructor is to initialize an object called object initialization.
Initialization is a process of assigning user defined values at the time of allocation of
memory space.
Syntax
ClassName()
.......
.......
Types of Constructors
Based on creating objects in Java constructor are classified in two types. They are
2. Parameterized constructor
1. Default Constructor
A constructor is said to be default constructor if and only if it never take any parameters.
CSE,NRCM Page 54
Object Oriented Programming Through Java(23CY305)
If any class does not contain at least one user defined constructor then the system will
create a default constructor at the time of compilation it is known as system defined
default constructor.
Note: System defined default constructor is created by java compiler and does not have any
statement in the body part. This constructor will be executed every time whenever an object is
created if that class does not contain any user defined constructor.
Example
class Test
int a, b;
Test()
a=10;
b=20;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
class TestDemo
2. Parameterized Constructor
CSE,NRCM Page 55
Object Oriented Programming Through Java(23CY305)
If any constructor contain list of variables in its signature is known as paremetrized constructor.
A parameterized constructor is one which takes some parameters.
Example
class Test
int a, b;
a=n1;
b=n2;
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
class TestDemo
In Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or
data member. It provides security, accessibility, etc to the user depending upon the access
modifier used with the element.
CSE,NRCM Page 56
Object Oriented Programming Through Java(23CY305)
2. Private
3. Protected
4. Public
When no access modifier is specified for a class, method, or data member – It is said to
be having the default access modifier by default.
The default modifier is accessible only within package.
It cannot be accessed from outside the package.
It provides more accessibility than private. But, it is more restrictive than protected, and
public.
Example
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
//save by A.java
package pack;
class A
void msg()
System.out.println("Hello");
//save by B.java
package mypack;
CSE,NRCM Page 57
Object Oriented Programming Through Java(23CY305)
import pack.*;
class B
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
2. Private
Example
class A
CSE,NRCM Page 58
Object Oriented Programming Through Java(23CY305)
System.out.println("Hello java");}
A obj=new A();
3. Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier is specified using the keyword protected.
Example
In this example, we have created the two packages pack and mypack.
The A class of pack package is public, so can be accessed from outside the package.
But msg method of this package is declared as protected, so it can be accessed from
outside the class only through inheritance.
//save by A.java
package pack;
public class A
CSE,NRCM Page 59
Object Oriented Programming Through Java(23CY305)
System.out.println("Hello");
//save by B.java
package mypack;
import pack.*;
class B extends A
obj.msg();
4. Public
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
The public access modifier is specified using the keyword public.
Example
//save by A.java
package pack;
public class A
CSE,NRCM Page 60
Object Oriented Programming Through Java(23CY305)
System.out.println("Hello");
//save by B.java
package mypack;
import pack.*;
class B
obj.msg();
CSE,NRCM Page 61
Object Oriented Programming Through Java(23CY305)
this is a reference variable that refers to the current object. It is a keyword in java language
The main purpose of using this keyword is to differentiate the formal parameter and data
members of class, whenever the formal parameter and data members of the class are
similar then JVM get ambiguity (no clarity between formal parameter and member of the
class).
To differentiate between formal parameter and data member of the class, the data
member of the class must be preceded by "this".
class Employee
int id;
String name;
id = id;
name = name;
void show()
System.out.println(id+" "+name);
class ThisDemo1
CSE,NRCM Page 62
Object Oriented Programming Through Java(23CY305)
e1.show();
Output: 0 null
In the above example, parameters (formal arguments) and instance variables are same. So, we
are using this keyword to distinguish local variable and instance variable.
class Employee
int id;
String name;
this.id = id;
this.name = name;
void show()
System.out.println(id+" "+name);
class ThisDemo2
CSE,NRCM Page 63
Object Oriented Programming Through Java(23CY305)
e1.show();
Garbage collection in Java is the process by which Java programs perform automatic memory
management.
It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.
CSE,NRCM Page 64
Object Oriented Programming Through Java(23CY305)
1. By nulling a reference:
2. e=null;
3. By anonymous object:
1. new Employee();
OVERLOADING METHODS
Whenever same method name is exiting multiple times in the same class with different
number of parameter or different order of parameters or different types of parameters is
known as method overloading.
Method overloading in Java is also known as Compile-time Polymorphism, Static
Polymorphism, or Early binding.
Example
class Addition
System.out.println(a+b);
CSE,NRCM Page 65
Object Oriented Programming Through Java(23CY305)
System.out.println(a+b+c);
System.out.println(a+b);
class Methodload
obj.sum(10, 20);
obj.sum(10.05f, 15.20f);
OVERLOADING CONSTRUCTORS
Constructor overloading is a concept of having more than one constructor with different
parameters list, so that each constructor performs a different task.
Example
Person()
CSE,NRCM Page 66
Object Oriented Programming Through Java(23CY305)
System.out.println("Introduction:");
Person(String name)
METHOD BINDING
Static Binding
When type of the object is determined at compiled time(by the compiler), it is known as static
binding.
CSE,NRCM Page 67
Object Oriented Programming Through Java(23CY305)
If there is any private, final or static method in a class, there is static binding.
Example
class Dog
d1.eat();
Dynamic binding
Example
class Animal
void eat()
System.out.println("animal is eating...");
void eat()
CSE,NRCM Page 68
Object Oriented Programming Through Java(23CY305)
System.out.println("dog is eating...");
a.eat();
In the above example object type cannot be determined by the compiler, because the instance of
Dog is
also an instance of Animal. So compiler doesn't know its type, only its base type.
Parameter passing in Java refers to the mechanism of transferring data between methods or
functions.
1. Call-by-value
2. Call-by-reference.
1. Call-by-Value
In Call-by-value the copy of the value of the actual parameter is passed to the formal parameter
of the method. Any of the modifications made to the formal parameter within the method do not
affect the actual parameter.
Example
CSE,NRCM Page 69
Object Oriented Programming Through Java(23CY305)
modifyValue(num);
value=20;
System.out.println("Inside method:"+value);
Output:
Inside method: 20
Call-by-Reference
call by reference" is a method of passing arguments to functions or methods where the memory
address (or reference) of the variable is passed rather than the value itself. This means that
changes made to the formal parameter within the function affect the actual parameter in the
calling environment.
In "call by reference," when a reference to a variable is passed, any modifications made to the
parameter inside the function are transmitted back to the caller. This is because the formal
parameter receives a reference (or pointer) to the actual data.
Example
class CallByReference
CSE,NRCM Page 70
Object Oriented Programming Through Java(23CY305)
int a,b;
CallByReference(int x,int y)
a=x;
b=y;
obj.a+=10;
obj.b+=20;
object.changeValue(object);
Output:
CSE,NRCM Page 71
Object Oriented Programming Through Java(23CY305)
Value of a: 10 & b: 20
Value of a: 20 & b: 40
RECURSION IN JAVA
Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called recursive method. It makes the code compact but complex to understand.
Syntax:
returntype methodname()
methodname();
Example
if (n == 1)
return 1;
else
return(n * factorial(n-1));
CSE,NRCM Page 72
Object Oriented Programming Through Java(23CY305)
INNER CLASSES
class Outer_class
//code
class Inner_class
//code
A non-static class that is created inside a class but outside a method is called member inner class.
Syntax:
class Outer
//code
CSE,NRCM Page 73
Object Oriented Programming Through Java(23CY305)
class Inner
//code
Example
class TestMemberOuter
class Inner
void msg()
System.out.println("data is "+data);
in.msg();
CSE,NRCM Page 74
Object Oriented Programming Through Java(23CY305)
In Java, a class can contain another class known as nested class. It's possible to create a
nested class without giving any name.
A nested class that doesn't have any name is known as an anonymous class.
An anonymous class must be defined inside another class. Hence, it is also known as an
anonymous inner class.
Example
class TestAnonymousInner
void eat()
System.out.println("nice fruits");
};
p.eat();
1. A class is created, but its name is decided by the compiler, which extends the Person class and
CSE,NRCM Page 75
Object Oriented Programming Through Java(23CY305)
2. An object of the Anonymous class is created that is referred to by 'p,' a reference variable of
Person type.
A class i.e. created inside a method is called local inner class in java.
If you want to invoke the methods of local inner class, you must instantiate this class
inside the method.
Example
void display()
class Local
void msg()
System.out.println(data);
l.msg();
obj.display();
CSE,NRCM Page 76
Object Oriented Programming Through Java(23CY305)
A static class i.e. created inside a class is called static nested class in java. It cannot
access nonstatic data members and methods. It can be accessed by outer class name.
It can access static data members of outer class including private.
Static nested class cannot access non-static (instance) data member or method.
Example
class TestOuter
void msg()
System.out.println("data is "+data);
obj.msg();
CSE,NRCM Page 77
Object Oriented Programming Through Java(23CY305)
In this example, you need to create the instance of static nested class because it has instance
method msg(). But you don't need to create the object of Outer class because nested class is static
and static properties, methods or classes can be accessed without object.
Example
siteName = "javaprogramminglanguage";
In java programming language, the String class contains various methods that can be used to
handle string data values.
The following table depicts all built-in methods of String class in java.
CSE,NRCM Page 78
Object Oriented Programming Through Java(23CY305)
Replacesthefirststringwithsecondstringatall
replaceAll(String,String)
13 occurrences.
Extractsasub-stringfromspecifiedstartandendindex
substring(int,int)
14 values
15 toLowerCase() Convertsastringtolowercaseletters
16 toUpperCase() Convertsastringtouppercaseletters
17 trim() Removeswhitespacefrombothends
18 toString(int) ConvertsthevaluetoaStringobject
Example
UNIT – II
CSE,NRCM Page 79
Object Oriented Programming Through Java(23CY305)
Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass,
subtype, substitutability, forms of inheritance specialization, specification, construction,
extension, limitation, combination, benefits of inheritance, costs of inheritance. Member access
rules, super uses, using final with inheritance, polymorphism- method overriding, abstract
classes, the Object class. Defining, Creating and Accessing a Package, Understanding
CLASSPATH, importing packages, differences between classes and interfaces, defining an
interface, implementing interface, applying interfaces, variables in interface and extending
interfaces. Exploring java.io.
INHERITANCE IN JAVA
Super Class/Parent Class: The class whose features are inherited is known as a superclass(or a
base class or a parent class).
Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a derived
class, extended class, or child class). The subclass can add its own fields and methods in addition
to the superclass fields and methods.
Code Reusability: The code written in the Superclass is common to all subclasses. Child classes
can directly use the parent class code.
Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the
ways by which Java achieves Run Time Polymorphism.
Abstraction: The concept of abstract where we do not have to provide all details is achieved
through inheritance. Abstraction only shows the functionality to the user.
Syntax
CSE,NRCM Page 80
Object Oriented Programming Through Java(23CY305)
TYPES OF INHERITANCE
Based on number of ways inheriting the feature of base class into derived class we have
five types of inheritance they are:
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid inheritance
1.Single inheritance
In single inheritance there exists single base class and single derived class.
Example
class Animal
String name;
void show()
CSE,NRCM Page 81
Object Oriented Programming Through Java(23CY305)
void bark()
System.out.println("Barking");
class TestInheritance
d.name="DOG";
d.show();
d.bark();
CSE,NRCM Page 82
Object Oriented Programming Through Java(23CY305)
Example
In the example, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.
class Animal
String name;
void show()
void bark()
CSE,NRCM Page 83
Object Oriented Programming Through Java(23CY305)
void weep()
class TestInheritance2
d.name="MotherDog";
d.show();
d.bark();
d.weep();
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than
one subclass. In the below image, class A serves as a base class for the derived class B, C and D.
CSE,NRCM Page 84
Object Oriented Programming Through Java(23CY305)
Example
class Animal
void eat()
System.out.println("eating...");
void bark()
System.out.println("barking...");
void meow()
CSE,NRCM Page 85
Object Oriented Programming Through Java(23CY305)
System.out.println("meowing...");
class TestInheritance3
c.meow();
c.eat();
//c.bark();//C.T.Error
4. Multiple inheritance
In multiple inheritance there exist multiple classes and single derived class.
The concept of multiple inheritance is not supported in java through concept of classes
but it can be supported through the concept of interface.
5. Hybrid inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support
multiple inheritances with classes, hybrid inheritance is also not possible with classes. In Java,
we can achieve hybrid inheritance only through Interfaces.
CSE,NRCM Page 86
Object Oriented Programming Through Java(23CY305)
SUBSTITUTABILITY
The inheritance concept used for the number of purposes in the java programming language.
One of the main purposes is substitutability.
The substitutability means that when a child class acquires properties from its parent class,
the object of the parent class may be substituted with the child class object.
For example, if B is a child class of A, anywhere we expect an instance of A we can use an
instance of B.
The substitutability can achieve using inheritance, whether using extends or implements
keywords.
FORMS OF INHERITANCE
Specialization
Specification
Construction
Extension
Limitation
Combination
Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent class.
It holds the principle of substitutability.
Specification
CSE,NRCM Page 87
Object Oriented Programming Through Java(23CY305)
This is another commonly used form of inheritance. In this form of inheritance, the parent
class just specifies which methods should be available to the child class but doesn't implement
them. The java provides concepts like abstract and interfaces to support this form of inheritance.
It holds the principle of substitutability.
Construction
This is another form of inheritance where the child class may change the behavior
defined by the parent class (overriding). It does not hold the principle of substitutability.
Extension
This is another form of inheritance where the child class may add its new properties. It
holds the principle of substitutability.
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It
does not hold the principle of substitutability.
Combination
This is another form of inheritance where the subclass inherits properties from multiple
parent classes. Java does not support multiple inheritance type.
BENEFITS OF INHERITANCE
Inheritance helps in code reuse. The child class may use the code defined in the parent class
without re-writing it.
Inheritance can save time and effort as the main code need not be written again.
Inheritance provides a clear model structure which is easy to understand.
An inheritance leads to less development and maintenance costs.
With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived class. An
inheritance leads to less development and maintenance costs.
In inheritance base class can decide to keep some data private so that it cannot be altered by
the derived class.
Inheritance decreases the execution speed due to the increased time and effort it takes, the
program to jump through all the levels of overloaded classes.
Inheritance makes the two classes (base and inherited class) get tightly coupled. This means
one cannot be used independently of each other.
CSE,NRCM Page 88
Object Oriented Programming Through Java(23CY305)
The changes made in the parent class will affect the behavior of child class too.
The overuse of inheritance makes the program more complex.
In Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or
data member. It provides security, accessibility, etc to the user depending upon the access
modifier used with the element.
2. Private
3. Protected
4. Public
When no access modifier is specified for a class, method, or data member – It is said to be
having the default access modifier by default.
The default modifier is accessible only within package.
It cannot be accessed from outside the package.
It provides more accessibility than private. But, it is more restrictive than protected, and
public.
Example
In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from outside
the package.
//save by A.java
package pack;
class A
void msg()
CSE,NRCM Page 89
Object Oriented Programming Through Java(23CY305)
System.out.println("Hello");
//save by B.java
package mypack;
import pack.*;
class B
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
2. private
Example
CSE,NRCM Page 90
Object Oriented Programming Through Java(23CY305)
class A
System.out.println("Hello java");}
A obj=new A();
3. protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier is specified using the keyword protected.
Example
In this example, we have created the two packages pack and mypack.
CSE,NRCM Page 91
Object Oriented Programming Through Java(23CY305)
The A class of pack package is public, so can be accessed from outside the package.
But msg method of this package is declared as protected, so it can be accessed from outside
the class only through inheritance.
//save by A.java
package pack;
public class A
System.out.println("Hello");
//save by B.java
package mypack;
import pack.*;
class B extends A
obj.msg();
4. public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
CSE,NRCM Page 92
Object Oriented Programming Through Java(23CY305)
Example
//save by A.java
package pack;
public class A
System.out.println("Hello");
//save by B.java
package mypack;
import pack.*;
class B
obj.msg();
CSE,NRCM Page 93
Object Oriented Programming Through Java(23CY305)
Private YES NO NO NO
SUPER KEYWORD
Super keyword in java is a reference variable that is used to refer parent class features.
Whenever the derived class is inherits the base class features, there is a possibility that base
class features are similar to derived class features and JVM gets an ambiguity.
In order to differentiate between base class features and derived class features must be
preceded by super keyword.
Syntax
super.baseclass features
Whenever the derived class inherit base class data members there is a possibility that base
class data member are similar to derived class data member and JVM gets an ambiguity.
In order to differentiate between the data member of base class and derived class, in the
context of derived class the base class data members must be preceded by super keyword.
CSE,NRCM Page 94
Object Oriented Programming Through Java(23CY305)
Syntax
Example
class Animal
String color="white";
String color="black";
void printColor()
class TestSuper1
d.printColor();
CSE,NRCM Page 95
Object Oriented Programming Through Java(23CY305)
The super keyword can also be used to invoke or call parent class method.
It should be use in case of method overriding. In other word super keyword use when base
class method name and derived class method name have same name.
Example
class Animal
void eat()
System.out.println("eating...");
void eat()
System.out.println("eating bread...");
void dispay()
eat();
super.eat();
class TestSuper2
CSE,NRCM Page 96
Object Oriented Programming Through Java(23CY305)
d.display();
The super keyword can also be used to invoke the parent class constructor.
class Animal
Animal()
System.out.println("animal is created");
Dog()
super();
System.out.println("dog is created");
CSE,NRCM Page 97
Object Oriented Programming Through Java(23CY305)
class TestSuper3
FINAL KEYWORD
A variable declared with the final keyword cannot be modified by the program after
initialization.
This is useful to universal constants, such as "PI".
Example
class Bike
void run()
speedlimit=400;
CSE,NRCM Page 98
Object Oriented Programming Through Java(23CY305)
obj.run();
It makes a method final, meaning that sub classes can not override this method. The compiler
checks and gives an error if you try to override the method.
When we want to restrict overriding, then make a method as a final.
Example
class Bike
System.out.println("running");
void run()
CSE,NRCM Page 99
Object Oriented Programming Through Java(23CY305)
honda.run();
It makes a class final, meaning that the class cannot be inheriting by other classes. When
we want to restrict inheritance then make class as a final.
Example
void run()
honda.run();
POLYMORPHISM
The polymorphism is the process of defining same method with different implementation.
That means creating multiple methods with different behaviors.
Whenever same method name is exiting multiple times in the same class with different
number of parameter or different order of parameters or different types of parameters is known
as method overloading.
Example
class Addition
System.out.println(a+b);
System.out.println(a+b+c);
System.out.println(a+b);
class Methodload
obj.sum(10, 20);
obj.sum(10.05f, 15.20f);
Whenever same method name is existing in both base class and derived class with same
types of parameters or same order of parameters is known as method Overriding.
In a java programming language, pure polymorphism carried out with a method overriding
concept.
Example
class Walking
void walk()
void walk()
super.walk();
class OverridingDemo
obj.walk();
Note:
Whenever we are calling overridden method using derived class object reference
the highest priority is given to current class (derived class). We can see in the
above example high priority is derived class.
super. (super dot) can be used to call base class overridden method in the derived
class.
ABSTRACT CLASS
A class which is declared with the abstract keyword is known as an abstract class in Java. It
can have abstract and non-abstract methods (method with the body).
An abstract class must be declared with an abstract keyword.
It cannot be instantiated. It can have constructors and static methods also.
It can have final methods which will force the subclass not to change the body of the method.
2. Interface (100%)
Syntax
......
ABSTRACT METHOD
An abstract method contains only declaration or prototype but it never contains body or
definition.
In order to make any undefined method as abstract whose declaration is must be predefined
by abstract keyword.
Syntax
Example
void draw()
System.out.println("drawing rectangle");
void draw()
System.out.println("drawing circle");
class TestAbstraction1
s.draw();
Example2
import java.util.*;
void printArea()
length = input.nextInt();
breadth = input.nextInt();
void printArea()
length = input.nextInt();
breadth = input.nextInt();
void printArea()
radius = input.nextInt();
rec.printArea();
tri.printArea();
cri.printArea();
OBJECT CLASS
In java, the Object class is the super most class of any class hierarchy. The Object class in the
java programming language is present inside the java.lang package.
Every class in the java programming language is a subclass of Object class by default.
The Object class is useful when you want to refer to any object whose type you don't know.
Because it is the superclass of all other classes in java, it can refer to any type of object.
Return Value
Method Description
hashCode() returns the hashcode number for object being used. int
notifyAll() wakes up all the threads, waiting on invoking object's monitor. void
wait() causes the current thread to wait, until another thread notifies. void
wait(long,int) causes the current thread to wait for the specified milliseconds and void
nanoseconds, until another thread notifies.
finalize() It is invoked by the garbage collector before an object is being void
garbage collected.
PACKAGES IN JAVA
CSE,NRCM Page 108
Object Oriented Programming Through Java(23CY305)
Types of packages
Package are classified into two type which are given below.
These are the packages which are already designed by the Sun Microsystem and supply
as a part of java API, every predefined package is collection of predefined classes, interfaces and
sub-package.
DEFINING A PACKAGE
The modifier of method of class or interface which is present in the package must be public
(This rule is optional in case of interface because interface methods by default public)
Every package program should be save either with public class name or public Interface
name
If you omit the package statement, the class names are put into the default package, which
has no name.
Syntax
package packagename;
Example
package mypack;
For compilation of package program first we save program with public className.java
and it compile
Syntax
javac -d . className.java
Explanation
In above syntax "-d" is a specific tool which tells to java compiler create a separate folder for
the given package in given path.
When we give specific path then it create a new folder at that location and when we use .
(dot) then it create a folder at current working directory.
Note: Any package program can be compile but can not be execute or run. These program can be
executed through user defined program which are importing package program.
Package program which is save with A.java and compile by javac -d . A.java.
package mypack;
public class A
System.out.println("Sum method");
IMPORTING PACKAGES
To import the java package into a class, we need to use the java import keyword which is
used to access the package and its classes into the java program.
Use import to access built-in and user-defined packages into your java source file to refer to a
class in another package by directly using its name.
syntax:
Example:
Example
import mypack.A;
A a=new A();
a.show();
CLASSPATH
To check the current setting of the CLASSPATH, issue the following command:
INTERFACES
Interface is similar to class which is collection of public static final variables (constants) and
abstract methods.
The interface is a mechanism to achieve fully abstraction in java. There can be only abstract
methods in the interface. It is used to achieve fully abstraction and multiple inheritance in
Java.
Since java does not support multiple inheritances in the case of class, by using an interface it
can achieve multiple inheritances.
Any class can extend only 1 class but can any class implement infinite number of interface.
Interfaces are used to implement abstraction. So the question arises why use interfaces when
we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in the
interface are final, public and static.
Class Interface
The keyword used to create a class is The keyword used to create an interface is
“class” “interface”
A class can be instantiated i.e., objects of a An Interface cannot be instantiated i.e. objects
class can be created. cannot be created.
Classes do not support multiple
The interface supports multiple inheritance.
inheritance.
It can be inherited from another class. It cannot inherit a class.
It can be inherited by a class by using the keyword
It can be inherited by another class using
‘implements’ and it can be inherited by an interface
the keyword ‘extends’.
using the keyword ‘extends’.
It can contain constructors. It cannot contain constructors.
It cannot contain abstract methods. It contains abstract methods only.
Variables and methods in a class can be
All variables and methods in an interface
declared using any access
aredeclared as public.
specifier(public,
private, default, protected).
Variables in a class can be static, final, or
All variables are static and final.
neither.
DEFINING INTERFACES
Syntax
interface interface_name
Example
interface A
void display();
IMPLEMENTING INTERFACES
Example
interface A
void display();
class B implements A
System.out.println("Hello");
class InterfaceDemo
obj.display();
System.out.println(a);
APPLYING INTERFACES
Example:
interface IntStack
int pop();
FixedStack(int size)
top = -1;
if(top==stck.length-1)
System.out.println("Stack is full.");
else
stck[++top] = item;
if(top ==-1)
System.out.println("Stack underflow.");
return 0;
else
return stck[top--];
class InterfaceTest
mystack1.push(i);
mystack2.push(i);
System.out.println(mystack1.pop());
System.out.println(mystack2.pop());
VARIABLES IN INTERFACE
Variables can be declared inside of interface declarations. They are implicitly final and static,
meaning they cannot be changed by the implementing class.
You can use interfaces to import shared constants into multiple classes by simply declaring
an interface that contains variables that are initialized to the desired values.
Example
interface SharedConstants
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int NEVER = 4;
int ask()
String ans=br.readLine();
if (ans= =”no”)
return NO;
else if (ans==”yes”)
return YES;
else if (ans==”notnow”)
return LATER;
else
return NEVER;
class AskMe
System.out.println(q.ask());
EXTENDING INTERFACES
interface A
void meth1();
void meth2();
interface B extends A
void meth3();
System.out.println("Implement meth1().");
System.out.println("Implement meth2().");
System.out.println("Implement meth3().");
class InterfaceDemo
ob.meth1();
ob.meth2();
ob.meth3();
Example
interface Printable
void print();
interface Showable
void show();
System.out.println("Hello");
System.out.println("Welcome");
obj.print();
obj.show();
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all
the classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
STREAM
In Java, streams are the sequence of data that are read from the source and written to the
destination.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
1. System.in: This is the standard input stream that is used to read characters from the keyboard
or any other standard input device.
2. System.out: This is the standard output stream that is used to produce the result of a program
on an output device like the computer screen.
3. System.err: This is the standard error stream that is used to output all the error data that a
program might throw, on a computer screen or any standard output device.
TYPES OF STREAMS
Depending on the type of operations, streams can be divided into two primary classes:
1. Byte Stream
2. Character Stream
1. BYTE STREAM
Java byte streams are used to perform input and output of 8-bit bytes.
All byte stream classes are derived from base abstract classes called InputStream and
OutputStream.
InputStream Class
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
Subclasses of InputStream
In order to use the functionality of InputStream, we can use its subclasses. Some of them are:
Methods of InputStream
The InputStream class provides different methods that are implemented by its subclasses. Here
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes.
Subclasses of OutputStream
In order to use the functionality of OutputStream, we can use its subclasses. Some of them are:
Methods of OutputStream
The OutputStream class provides different methods that are implemented by its subclasses. Here
are some of the methods:
2. CHARACTER STREAM
All the character stream classes are derived from base abstract classes Reader and Writer.
Reader Class
The Reader class of the java.io package is an abstract super class that represents a stream of
characters.
In order to use the functionality of Reader, we can use its subclasses. Some of them are:
Methods of Reader
The Reader class provides different methods that are implemented by its subclasses. Here are
Writer Class
The Writer class of the java.io package is an abstract super class that represents a stream of
characters.
Since Writer is an abstract class, it is not useful by itself. However, its subclasses can be used
to write data.
Subclasses of Writer
Methods of Writer
The Writer class provides different methods that are implemented by its subclasses. Here are
some of the methods:
write(char[] array) - writes the characters from the specified array to the output stream
write(String data) - writes the specified string to the writer
append(char c) - inserts the specified character to the current writer
flush() - forces to write all the data present in the writer to the corresponding destination
close() - closes the writer
There are times when it is important for you to get input from users for execution of programs.
To do this you need Java Reading Console Input Methods.
Reading input data using the BufferedReader class is the traditional technique. This way of
the reading method is used by wrapping the System.in (standard input stream) in an
InputStreamReader which is wrapped in a BufferedReader, we can read input from the
console.
The BufferedReader class has defined in the java.io package.
We can use read() method in BufferedReader to read a character.
int read() throws IOException
import java.io.*;
class ReadingConsoleInputTest
char ch;
do
ch = (char) br.read();
System.out.println(ch);
} while(ch != 'x');
import java.io.*;
class MyInput
String text;
System.out.println(text);
Scanner is one of the predefined class which is used for reading the data dynamically from the
keyboard.
java.util.Scanner
Scanner(InputStream)
This constructor create an object of Scanner class by talking an object of InputStream class. An
object of InputStream class is called in which is created as a static data member in the System
class.
import java.util.Scanner
int num1=s.nextInt();
int num2=s.nextInt();
This is another way of reading user input from the console in Java.
The Java Console class is be used to get input from console. It provides methods to read texts
and passwords.
If you read password using Console class, it will not be displayed to the user.
The Console class is defined in the java.io class which needs to be imported before using the
console class.
Example
import java.io.*;
class consoleEg
String name;
Console c = System.console();
name = c.readLine();
print and println methods in System.out are mostly used for console output.
These methods are defined by the class PrintStream which is the type of object referenced by
System.out.
System.out is the byte stream.
PrintStream is the output derived from OutputStream. write method is also defined in
PrintStream for console output.
import java.io.*;
class WriteCharacterTest
int byteval;
byteval = 'J';
System.out.write(byteval);
System.out.write('\n');
UNIT-3
Exception handling and Multithreading - Concepts of exception handling, benefits of
exception handling, Termination or resumptive models, exception hierarchy, usage of
try, catch, throw, throws and finally, built in exceptions, creating own exception
subclasses. String handling, Exploring java.util. Differences between multithreading
and multitasking, thread life cycle, creating threads, thread priorities, synchronizing
threads, inter thread communication, thread groups, daemon threads. Enumerations,
autoboxing , annotations, generics.
CONCEPTS OF EXCEPTION HANDLING
EXCEPTION
An Exception is a run time error, which occurs during the execution of a program, that
disrupts the normal flow of the program's instructions.
It is an unwanted or unexpected event, which occurs during the execution of a program, i.e.
at run time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object.
This object is called the exception object.
It contains information about the exception, such as the name and description of the
exception and the state of the program when the exception occurred.
Errors
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out
of memory, memory leaks, stack overflow errors, library incompatibility, infinite
recursion, etc.
Errors are usually beyond the control of the programmer, and we should not try to handle
errors.
The Exception Handling in Java is one of the powerful feature to handle the runtime
errors so that normal flow of the application can be maintained.
Exception Handling is used to convert system error message into user friendly error
message.
statement 1;
statement 2;
statement 3;
statement 4;
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be
executed.
If we perform exception handling, the rest of the statement will be executed. That is why
we use exception handling in Java.
class ExceptionDemo
int c=a/b;
ExceptionDemo.main(ExceptionDemo.java:7)
at ExceptionDemo.main(ExceptionDemo.java:7)
This error message is not understandable by user so we convert this error message into
user friendly error message, like "denominator should not be zero".
3. Propagation of Errors
In java, there are two exception models. Java programming language has two models of
exception handling. The exception models that java supports are as follows.
Termination Model
Resumptive Model
Termination Model
Resumptive Model
EXCEPTION HIERARCHY
1. try
2. catch
3. throw
4. throws
5. finally
1. try block
The try block contains set of statements where an exception can occur.
In other words try block always contains problematic statements.
A try block is always followed by a catch block, which handles the exception that occurs in
associated try block. A try block must be followed by catch blocks or finally block or both.
CSE,NRCM Page 135
Object Oriented Programming Through Java(23CY305)
Syntax :
try
2. catch block
A catch block is where we handle the exceptions, this block must follow the try block.
A single try block can have multiple catch blocks associated with it. We can catch different
exceptions in different catch blocks.
When an exception occurs in try block, the corresponding catch block that handles that
particular exception executes.
For example if an arithmetic exception occurs in try block then the statements enclosed in
catch block for arithmetic exception executes.
try
Example1: ArithmeticException
class ExceptionDemo
try
int c=a/b;
catch (ArithmeticException e)
}}
Example2: NullPointerException
class NullPointer_Demo
try
System.out.println(a.charAt(0));
catch(NullPointerException e)
System.out.println("NullPointerException..");
Output: NullPointerException..
Example3: FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo
try
catch(FileNotFoundException e)
We can write multiple catch blocks for generating multiple user friendly error messages
to make our application strong.
Example
class ExceptionDemo
try
int c=a/b;
System.out.println("Result: "+c);
catch(NullPointerException e)
catch(ArithmeticException e)
The try block within a try block is known as nested try block in java. Why use nested try
block.Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Syntax :
try {
statement 1;
statement 2;
try
statement 1;
statement 2;
catch(Exception e)
…………
} } catch(Exception e) {
……….. } Example
class NestedTry
try
try
a[5]=4;
catch(ArrayIndexOutOfBoundsException e)
System.out.println(e);
catch(Exception e)
System.out.println("handeled");
} System.out.println("normal flow..");
3.throw
The throw keyword in Java is used to explicitly throw an exception from a method or any
block of code.
We can throw either checked or unchecked exception.
The throw keyword is mainly used to throw custom exceptions.
Syntax:
throw Instance
Example
CSE,NRCM Page 141
Object Oriented Programming Through Java(23CY305)
Example
class ThrowExcep
try
catch(NullPointerException e)
try
fun();
catch(NullPointerException e)
System.out.println("Caught in main.");
Caught in main.
4. throws
throws is a keyword in java language which is used to throw the exception which is
raised in the called method to it's calling method throws keyword always followed by method
signature.
Syntax
.....
Example
class ThrowsExecp
try
fun();
catch(IllegalAccessException e)
System.out.println("caught in main.");
Output:
Inside fun().
caught in main.
5.finally Block
Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.
Example
class TestFinallyBlock
try
int data=25/0;
CSE,NRCM Page 144
Object Oriented Programming Through Java(23CY305)
System.out.println(data);
catch(NullPointerException e)
System.out.println(e);
finally
Output:
RE-THROWING EXCEPTIONS
Example
class RethrowExcep
try
catch(NullPointerException e)
try
fun();
catch(NullPointerException e)
System.out.println("Caught in main.");
Output:
Caught in main.
If any exception is design by the user known as user defined or Custom Exception.
Custom Exception is created by user. Rules to design user defined Exception
3. Make that user defined class as derived class of Exception or RuntimeException class.
5. call super class constructor by passing string variable within the derived class
constructor.
Example
package nage;
super(s);
class CustomException
if(age<18)
else
System.out.println("welcome to vote");
try
validate(13);
catch(Exception m)
Output:
BUILT IN EXCEPTIONS
The Java programming language has several built-in exception class that support exception
handling.
Every exception class is suitable to explain certain error situations at run time.
All the built-in exception classes in Java were defined a package java.lang.
In java, exceptions are mainly categorized into two types, and they are as follows.
Checked Exceptions
Unchecked Exceptions
Checked Exceptions
The checked exception is an exception that is checked by the compiler during the
compilation process to confirm whether the exception is handled by the programmer or
not. If it is not handled, the compiler displays a compilation error using built-in classes.
The checked exceptions are generally caused by faults outside of the code itself like
missingresources, networking errors, and problems with threads come to mind.
The following are a few built-in classes used to handle checked exceptions in java.
In the exception class hierarchy, the checked exception classes are the direct children of
the Exception class.
1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the
specified class cannot be found in the classpath.
2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an object, but that
the object's class does not implement the Cloneable interface.
3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers donot
allow.
4 InstantiationException
It is thrown when an application tries to create an instance of a class using the newInstance
method in class, but the specified class object cannot be instantiated because it is an interface or
is an abstract class.
5 InterruptedException
6 NoSuchFieldException
7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at compile time, a
No Such Method Exception occurs during reflection when we try to access a method that does
not exist.
Unchecked Exceptions
The unchecked exception is an exception that occurs at the time of program execution. The
unchecked exceptions are not caught by the compiler at the time of compilation.
The unchecked exceptions are generally caused due to bugs such as logic errors, improper
use of resources, etc.
In the exception class hierarchy, the unchecked exception classes are the children of
RuntimeException class, which is a child class of Exception class.
1 ArithmeticException
2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.
3 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type of
5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to another. 6
6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal
orinappropriate argument.
7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or has
attempted to notify other threads that wait on an object's monitor, without owning the specified
monitor.
8 IllegalStateException
9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to modify the state
of the thread when it is illegal.
10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as an array,
vector , string , and so forth.
11 NegativeArraySizeException
12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or integer, but the
format of the input string is not appropriate or illegal.
14 SecurityException
15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is eithernegative,
or greater than the size of the string itself.
16 UnsupportedOperationException
STRING HANDLING
Example
siteName = "javaprogramminglanguage";
In java programming language, the String class contains various methods that can be used
to handle string data values.
The following table depicts all built-in methods of String class in java.
13replaceAll(String, String)Replaces the first string with second string at all occurrences.
14substring(int, int)Extracts a sub-string from specified start and end index values
Example
Multi-tasking and multi-threading are two techniques used in operating systems to manage
multiple processes and tasks.
Multi-tasking is the ability of an operating system to run multiple processes or tasks
concurrently, sharing the same processor and other resources.
In multi-tasking, the operating system divides the CPU time between multiple tasks, allowing
them to execute simultaneously.
Each task is assigned a time slice, or a portion of CPU time, during which it can execute its
code.
Multi-tasking is essential for increasing system efficiency, improving user productivity, and
achieving optimal resource utilization.
Threads share the same memory space and resources of the parent process, allowing them to
communicate and synchronize data easily.
Multi-threading is useful for improving application performance by allowing different parts
of the application to execute simultaneously.
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1. New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
Example
2. Runnable
When a thread calls start( ) method, then the thread is said to be in the Runnable state.
This state is also known as a Ready state.
Example
t1.start( );
3. Running
When a thread calls run( ) method, then the thread is said to be Running. The run( ) method of a
thread called automatically by the start( ) method.
4. Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
A thread in the Running state may move into the blocked state due to various reasons like
sleep( )method called, wait( ) method called, suspend( ) method called, and join( ) method
called, etc.
When a thread is in the blocked or waiting state, it may move to Runnable state due to
reasons like sleep time completed, waiting time completed, notify( ) or notifyAll( ) method
called, resume( ) method called, etc.
Example
Thread.sleep(1000);
wait(1000);
wait();
suspend();
notify();
notifyAll();
resume();
5. Terminated
A thread in the Running state may move into the dead state due to either its execution
completed or the stop( ) method called.
The dead state is also known as the terminated state.
CREATING THREADS
The java contains a built-in class Thread inside the java.lang package. The Thread class contains
all the methods that are related to the threads.
To create a thread using Thread class, follow the step given below.
Step-1: Create a class as a child of Thread class. That means, create a class that extends Thread
class.
Step-2: Override the run( ) method with the code that is to be executed by the thread. The run( )
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Call the start( ) method on the object created in the above step.
t1.start();
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i = 10
The java contains a built-in interface Runnable inside the java.lang package.
The Runnable interface implemented by the Thread class that contains all the methods that
are related to the threads.
To create a thread using Runnable interface, follow the step given below.
Step-2: Override the run( ) method with the code that is to be executed by the thread. The run(
)method must be public while overriding.
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Create the Thread class object by passing above created object as parameter to the
Thread class constructor.
Step-5: Call the start( ) method on the Thread class object created in the above step.
thread.start();
Output:
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i = 10
1. Thread()
2. Thread(String name)
3. Thread(Runnable r)
2. public void start():It moves the thread from Ready state to Running state by calling run( )
method.
3. public void sleep(long milliseconds): Moves the thread to blocked state till the specified
number of milliseconds.
5. public void join(long milliseconds): waits for a thread to die for the specified milliseconds.
10. public Thread currentThread(): returns the reference of currently executing thread.
try
Thread.sleep(1000);
catch(Exception e)
System.out.println(e);
t1.start();
try
t1.join();
catch(Exception e)
System.out.println(e);
t2.start();
t3.start();
THREAD PRIORITIES
1. MIN_PRIORITY
2. NORM_PRIORITY
3. MAX_PRIORITY
setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread.
Example
threadObject.setPriority(4);
or
threadObject.setPriority(MAX_PRIORITY);
getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread.
It does not takes any argument and returns name of the thread as String.
Example
Example1
System.out.println("Inside SampleThread");
threadObject1.setName("first");
threadObject2.setName("second");
threadObject1.setPriority(4);
threadObject2.setPriority(Thread.MAX_PRIORITY);
threadObject1.start();
threadObject2.start();
Output:
Inside SampleThread
Inside SampleThread
CurrentThread: second
CurrentThread: first
Example2
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
Output
SYNCHRONIZING THREADS
SYNCHRONIZATION
Example:
class Table
{ void printTable(int n)
for(int i=1;i<=5;i++)
System.out.println(n*i);
try
Thread.sleep(400);
catch(Exception e)
System.out.println(e);
{ Table t; MyThread1(Table t)
t.printTable(5); }
{ Table t; MyThread2(Table t)
t.printTable(100); }
class TestSynchronization
t1.start();
t2.start();
}}
Output:
100
10
200
15
300
20
400
25
500
Thread Synchronization
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. This can be done by two ways in java:
1. by synchronized method
2. by synchronized block
Example:
class Table
int number;
this.table = table;
this.number = number;
table.printTable(number);
int number;
this.table = table;
this.number = number;
table.printTable(number);
class ThreadSynchronizationExample
thread1.start();
thread2.start();
Output:
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100
The synchronized block is used when we want to synchronize only a specific sequence of
lines in a method.
For example, let's consider a method with 20 lines of code where we want to synchronize
only a sequence of 5 lines code, we use the synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Scope of synchronized block is smaller than the method.
//code block }
class Table
{ void printTable(int n)
synchronized(this)
{ //synchronized block
for(int i=1;i<=5;i++)
System.out.println(n*i);
try
Thread.sleep(400);
catch(Exception e)
System.out.println(e);
{ Table t; MyThread1(Table t)
t.printTable(5); }
{ Table t; MyThread2(Table t)
t1.start();
t2.start(); } }
Output:
10
15
20
25
100
200
300
400
500
INTERTHREAD COMMUNICATION
Inter thread communication is the concept where two or more threads communicate to solve
the problem of polling.
In java, polling is the situation to check some condition repeatedly, to take appropriate
action, once the condition is true.
That means, in inter-thread communication, a thread waits until a condition becomes true
such that other threads can execute its task.
The inter-thread communication allows the synchronized threads to communicate with each
other.
void wait( ) It makes the current thread to pause its execution until other thread in
the same monitor calls notify( )
void notify( ) It wakes up the thread that called wait( ) on the same object.
void notifyAll() It wakes up all the threads that called wait( ) on the same object.
The producer produces the item and the consumer consumes the same.
But here, the consumer cannot consume until the producer produces the item, and producer
cannot produce until the consumer consumes the item that already been produced.
So here, the consumer has to wait until the producer produces the item, and the producer also
needs to wait until the consumer consumes the same.
Here we use the inter-thread communication to implement the producer and consumer
problem.
Example
class ItemQueue
int item;
while (!valueSet)
try
wait();
catch (InterruptedException e)
System.out.println("InterruptedException caught");
try
Thread.sleep(1000);
catch (InterruptedException e)
System.out.println("InterruptedException caught");
notify();
return item;
while (valueSet)
try
wait();
catch (InterruptedException e)
System.out.println("InterruptedException caught");
try
Thread.sleep(1000);
catch (InterruptedException e)
System.out.println("InterruptedException caught");
notify();
ItemQueue itemQueue;
Producer(ItemQueue itemQueue)
this.itemQueue = itemQueue;
int i = 0;
while(true)
itemQueue.putItem(i++);
ItemQueue itemQueue;
Consumer(ItemQueue itemQueue)
this.itemQueue = itemQueue;
while(true)
itemQueue.getItem();
class ProducerConsumer
new Producer(itemQueue);
new Consumer(itemQueue);
THREADGROUP IN JAVA
Java provides a convenient way to group multiple threads in a single object. In such a way,
we can suspend, resume or interrupt a group of threads by a single method call.
Java thread group is implemented by java.lang.ThreadGroup class.
A Thread Group represents a set of threads. A thread group can also include the other thread
group. The thread group creates a tree in which every thread group except the initial thread
group has a parent.
A thread is allowed to access information about its own thread group, but it cannot access the
information about its thread group's parent thread group or any other thread groups.
ThreadGroup Example
System.out.println(Thread.currentThread().getName());
t1.start();
t2.start();
t3.start();
Output :
one
two
three
In Java, daemon threads are low-priority threads that run in the background to perform tasks
such as garbage collection or provide services to user threads.
The life of a daemon thread depends on the mercy of user threads, meaning that when all user
threads finish their execution, the Java Virtual Machine (JVM) automatically terminates the
daemon thread.
To put it simply, daemon threads serve user threads by handling background tasks and have
no role other than supporting the main execution. Methods for Java Daemon thread by
Thread class The java.lang.Thread class provides two methods for java daemon thread.
1 public void setDaemon(boolean status) is used to mark the current thread as daemon thread or
user thread.
Example
if(Thread.currentThread().isDaemon())
else
t2.start();
t3.start();
}}
JAVA ENUMS
The Enum in Java is a data type which contains a fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and
WEST), season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED,
YELLOW, BLUE, GREEN, WHITE, and BLACK) etc.
According to the Java naming conventions, we should have all constants in capital letters. So,
we have enum constants in capital letters.
Java Enums can be thought of as classes which have a fixed set of constants (a variable that
does not change).
The Java enum constants are static and final implicitly.
Enums are used to create our own data type like classes.
The enum data type (also known as Enumerated Data Type) is used to define an enum in
Java.
Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it can
implement many interfaces.
We can have fields, constructors, methods, and main methods in Java enum.
Example
class EnumExample1
System.out.println(s); }
AUTOBOXING
The automatic conversion of primitive data types into its equivalent Wrapper type is known
as boxing and opposite operation is known as unboxing.
So java programmer doesn't need to write the conversion code.
Advantage
No need of conversion between primitives and Wrappers manually so less coding is required.
Example
class BoxingExample1
int a=50;
System.out.println(a2+" "+a3);
}}
Output: 50 5
JAVA ANNOTATIONS
Java Annotation is a tag that represents the metadata i.e. attached with class, interface,
methods or fields to indicate some additional information which can be used by java
compiler and JVM.
Annotations in Java are used to provide additional information, so it is an alternative option
for XML and Java marker interfaces.
Example
@Override
@SuppressWarnings @Deprecated
@Override
@Override annotation assures that the subclass method is overriding the parent class method.
If it is not so, compile time error occurs.
Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to mark
@Override annotation that provides assurity that method is overridden.
Example
class Animal
void eatSomething()
System.out.println("eating something");}
@Override
void eatsomething()
System.out.println("eating foods");
} //should be eatSomething
class TestAnnotation1
@Deprecated
Example
class A
void m()
System.out.println("hello m");
@Deprecated
void n()
System.out.println("hello n");
class TestAnnotation3
A a=new A();
a.n();
Output
At Compile Time:
At Runtime:
hello n
JAVA GENERICS
Java Generics allows us to create a single class, interface, and method that can be used with
different types of data (objects).
This helps us to reuse our code.
Note: Generics does not work with primitive types (int, float, char, etc).
UNIT - IV
Event Handling: Events, Event sources, Event classes, Event Listeners, Delegation event
model,handling mouse and keyboard events, Adapter classes. The AWT class hierarchy, user
interface components- labels, button, canvas, scrollbars, text components, check box, checkbox
groups, choices,lists panels –scrollpane, dialogs, menubar, graphics, layout manager – layout
manager types – border, grid, flow, card and grid bag.
EVENT HANDLING
In general we can not perform any operation on dummy GUI screen even any button click or
select any item.
To perform some operation on these dummy GUI screen you need some predefined classes
and interfaces.
All these type of classes and interfaces are available in java.awt.event package.
Changing the state of an object is known as an event.
The process of handling the request in GUI screen is known as event handling (event
represent an action). It will be changes component to component.
Note: In event handling mechanism event represent an action class and Listener represent an
interface. Listener interface always contains abstract methods so here you need to write your
own logic.
EVENTS
The Events are the objects that define state change in a source.
An event can be generated as a reaction of a user while interacting with GUI elements.
Some of the event generation activities are moving the mouse pointer, clicking on a button,
pressing the keyboard key, selecting an item from the list, and so on.
We can also consider many other user operations as events.
EVENT SOURCES
Syntax
From the above syntax, the Type is the name of the event, and e1 is a reference to the event
listener.
For example, for a keyboard event listener, the method will be called as addKeyListener().
For the mouse event listener, the method will be called as addMouseMotionListener().
When an event is triggered using the respected source, all the events will be notified to
registered listeners and receive the event object.
This process is known as event multicasting.
EVENT LISTENERS
The Delegation Event model is defined to handle events in GUI programming languages.
The GUI stands for Graphical User Interface, where a user graphically/visually interacts with
the system.
The GUI programming is inherently event-driven; whenever a user initiates an activity such
as a mouse activity, clicks, scrolling, etc., each is known as an event that is mapped to a code
to respond to functionality to the user. This is known as event handling. The below image
demonstrates the event processing.
In this model, a source generates an event and forwards it to one or more listeners.
The listener waits until it receives an event. Once it receives the event, it is processed by the
listener and returns it.
REGISTRATION METHODS
For registering the component with the Listener, many classes provide the registration
methods.
Button
MenuItem
TextField
TextArea
Checkbox
Choice
List
.......
.......
addcomponentobject.addXXXListener(this);
....... // override abstract method of given interface and write proper logic
.......
.......
.......
For handling event for mouse you need Mouse Event class and Mouse Listener interface.
The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five
methods.
Example
import java.awt.*;
import java.awt.event.*;
Label l;
MouseListenerExample()
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
l.setText("Mouse Clicked");
l.setText("Mouse Entered");
l.setText("Mouse Exited");
l.setText("Mouse Pressed");
l.setText("Mouse Released");
new MouseListenerExample();
Output:
The Java KeyListener is notified whenever you change the state of key. It is notified
against KeyEvent.
EXAMPLE
import java.awt.*;
import java.awt.event.*;
Label l;
TextArea area;
KeyListenerExample()
l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
l.setText("Key Pressed");
l.setText("Key Released");
l.setText("Key Typed");
new KeyListenerExample();
Output:
ADAPTER CLASSES
In a program, when a listener has many abstract methods to override, it becomes complex for
the programmer to override all of them.
For example, for closing a frame, we must override seven abstract methods of
WindowListener, but we need only one method of them.
For reducing complexity, Java provides a class known as "adapters" or adapter class.
Adapters are abstract classes, that are already being overriden.
Frame f;
AdapterExample()
f.addWindowListener(new WindowAdapter()
f.dispose();
});
f.setSize(400,400);
f.setVisible(true);
new AdapterExample();
}}
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In
Java AWT, there are classes for each component as shown in above diagram. In order to place
every component in a particular position on a screen, we need to add them to a container.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
AWT FRAME
The Frame is the container that contain title bar and can have menu bars. It can have
other components like button, textfield etc.
Methods
1. setTitle()
It is used to display user defined message on title bar. Frame f=new Frame();
f.setTitle("myframe");
2. setBackground()
f.setBackground(Color.red);
3. setForground()
f.setForground(Color.red);
4. setSize()
It is used to set the width and height for frame. Frame f=new Frame();
f.setSize(400,300);
5. setVisible()
It is used to make the frame as visible to end user. Frame f=new Frame();
f.setVisible(true);
Note: You can write setVisible(true) or setVisible(false), if it is true then it visible otherwise not
visible.
7.add()
f.add(b);
Explanation: In above code we add button on frame using f.add(b), here b is the object of Button
class..
Example
import java.awt.*;
class FrameDemo {
Frame fObj;
ButtonExample2() {
button3.setLabel("Button 3");
fObj.add(button1);
fObj.add(button2);
fObj.add(button3);
fObj.setLayout(new FlowLayout());
fObj.setSize(300,400);
fObj.setVisible(true);
} }
AWT PANEL
Note: Frame is always visible to end user where as panel is not visible to end user. Panel is a
derived class of container class so you can use all the methods which is used in frame. Syntax
Example
import java.awt.*;
PanelExample()
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
new PanelExample();
Output:
AWT Label
The object of the Label class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by a programmer but a user
cannot edit it directly.
Example
import java.awt.*;
f.add(l1);
f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
Output
A button is basically a control component with a label that generates an event when pushed.
The Button class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed.
Example
import java.awt.*;
b.setBounds(50,100,80,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
Output:
The Canvas class controls and represents a blank rectangular area where the application can draw
or trap input events from the user. It inherits the Component class.
Example
import java.awt.*;
public CanvasExample()
f.add(new MyCanvas());
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
new CanvasExample();
public MyCanvas()
setBackground (Color.GRAY);
setSize(300, 200);
g.setColor(Color.red);
Output:
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is
Example
import java.awt.*;
ScrollbarExample1()
f.add(s);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
new ScrollbarExample1();
Output:
The object of a TextField class is a text component that allows a user to enter a single line
text and edit it. It inherits TextComponent class, which further inherits Component class.
Example:
import java.awt.*;
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
Output:
The object of a TextArea class is a multiline region that displays text. It allows the editing of
multiple line text. It inherits TextComponent class.
Example
import java.awt.*;
TextAreaExample()
f.add(area);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
new TextAreaExample();
Output :
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off
(false).
Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
Example
import java.awt.*;
CheckboxExample1()
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
new CheckboxExample1();
Output :
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only
one check box button is allowed to be in "on" state and remaining check box button in "off"
state. It inherits the object class.
Example
import java.awt.*;
CheckboxGroupExample()
checkBox1.setBounds(100,100, 50,50);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
new CheckboxGroupExample();
Output :
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.
Example
import java.awt.*;
ChoiceExample1()
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
new ChoiceExample1();
Output:
The object of List class represents a list of text items. With the help of the List class, user can
choose either one item or multiple items. It inherits the Component class.
Example
import java.awt.*;
ListExample1()
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
f.add(l1);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
new ListExample1();
Output :
The Dialog control represents a top level window with a border and a title used to take
some form of input from the user. It inherits the Window class.
Example
import java.awt.*;
import java.awt.event.*;
DialogExample()
DialogExample.d.setVisible(false);
});
d.add(b);
d.setSize(300,300);
d.setVisible(true);
new DialogExample();
Output :
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a
menu must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu bar. It
inherits the MenuItem class.
import java.awt.*;
class MenuExample
MenuExample()
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
new MenuExample();
Output:
Graphics is an abstract class provided by Java AWT which is used to draw or paint on the
components. It consists of various fields which hold information like components to be painted,
font, color, XORmode, etc., and methods that allow drawing various shapes on the GUI
components. Example
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public MyFrame()
setVisible(true);
setSize(300, 200);
addWindowListener(new WindowAdapter()
@Override
System.exit(0);
});
new MyFrame();
Output:
There are following classes that represents the layout managers: 1. BorderLayout
2. FlowLayout
3. GridLayout
4. CardLayout
5. GridBagLayout
BORDERLAYOUT
The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
EXAMPLE
import java.awt.*;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
new Border();
Output:
FLOWLAYOUT
This layout is used to arrange the GUI components in a sequential flow (that means one after
another in horizontal way)
You can also set flow layout of components like flow from left, flow from right.
FlowLayout Left
f.setLayout(new FlowLayout(FlowLayout.LEFT));
FlowLayout Right
f.setLayout(new FlowLayout(FlowLayout.RIGHT))
EXAMPLE
import java.awt.*;
import javax.swing.*;
JFrame frameObj;
// constructor
FlowLayoutExample()
frameObj.add(b9); frameObj.add(b10);
frameObj.setLayout(new FlowLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
// main method
new FlowLayoutExample();
Output:
GRIDLAYOUT
This layout is used to arrange the GUI components in the table format. EXAMPLE
import java.awt.*;
import javax.swing.*;
MyGridLayout()
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5); f.add(b6);
f.add(b7);
f.add(b8);
f.add(b9);
f.setLayout(new GridLayout(3,3));
f.setSize(300,300);
new MyGridLayout(); } }
Output
CARDLAYOUT
The CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.
1. public void next(Container parent): is used to flip to the next card of the given container.
2. public void previous(Container parent): is used to flip to the previous card of the given
container.
3. public void first(Container parent): is used to flip to the first card of the given container.
4. public void last(Container parent): is used to flip to the last card of the given container.
5. public void show(Container parent, String name): is used to flip to the specified card with the
given name.
EXAMPLE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample()
c=getContentPane();
card=new CardLayout(40,30);
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);
c.add("b",b2);
c.add("c",b3);
card.next(c);
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
Output:
GridBagLayout
Example
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
public GridBagLayoutExample()
setLayout(grid);
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
output:
UNIT – V
Applets – Concepts of Applets, differences between applets and applications, life cycle of an
applet, types of applets, creating applets, passing parameters to applets. Swing –
Introduction, limitations of AWT, MVC architecture, components, containers, exploring
swing- JApplet, JFrame and JComponent, Icons and Labels, text fields, buttons – The
JButton class, Check boxes, Radio buttons, Combo boxes, Tabbed Panes, Scroll Panes,
Trees, and Tables.
JAVA APPLET
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Applets are used to make the website more dynamic and entertaining.
An applet is embedded in an HTML page using the APPLET or OBJECT tag and hosted on a
web server.
Important points
HIERARCHY OF APPLET
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
The java.applet.Applet class provides 4 life cycle methods and java.awt.Component class
provides 1 life cycle method for an applet.
java.applet.Applet class
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to
start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object
that can be used for drawing oval, rectangle, arc etc.
CREATING APPLETS
1. By html file.
1. By html file
To execute the applet by html ile, create an applet and compile it. After that create an html ile
and place the applet code in html ile. Now click the html ile.
Example
import java.applet.Applet;
import java.awt.Graphics;
myapplet.html
<html>
<body>
</applet>
</body>
</html>
2. By appletViewer tool
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html ile is not required but it is
for testing purpose only.
Example
import java.applet.Applet;
import java.awt.Graphics;
g.drawString("welcome applet",150,150);
/*
</applet>
*/
);
c:\>javac First.java
c:\>appletviewer First.java
A special type of Java program that runs in a Web browser is referred to as Applet .
It has less response time because it works on the client-side.
It is much secured executed by the browser under any of the platforms such as Windows,
Linux and Mac OS etc.
There are two types of applets that a web page can contain.
1. Local Applet
2. Remote Applet
1. Local Applet
Local Applet is written on our own, and then we will embed it into web pages.
Local Applet is developed locally and stored in the local system.
A web page doesn't need the get the information from the internet when it inds the local
Applet in the system.
It is specified or deined by the ile name or pathname.
There are two attributes used in deining an applet, i.e., the codebase that speci ies the path
name and code that deined the name of the ile that contains Applet's code.
<applet
codebase ="tictactoe"
code = "FaceApplet.class"
width = 120
</applet>
Example
mport java.applet.Applet;
import java.awt.*;
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
myapplet.html
<html>
<body>
</applet>
</body>
</html>
2. Remote Applet
In order to locate and load a remote applet, we must know the applet's address on the web that
is referred to as Uniform Recourse Locator(URL).
<applet
codebase = "http://www.myconnect.com/applets/"
code = "FaceApplet.class"
width = 120
height =120>
</applet>
PARAMETER IN APPLET
We can get any information from the HTML ile as a parameter. For this purpose, Applet class
provides a method named getParameter().
Syntax:
import java.applet.Applet;
import java.awt.Graphics;
String str=getParameter("msg");
g.drawString(str,50, 50);
myapplet.html
<html>
<body>
</applet>
</body>
</html>
SWING INTRODUCTION
Java Swing is used to create window-based applications. It is built on the top of AWT
(Abstract Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
LIMITATIONS OF AWT
MVC ARCHITECTURE
The MVC design pattern consists of three modules model, view and controller.
Model
The model represents the state (data) and business logic of the application.
For example-in case of a check box, the model contains a ield which indicates whether the
box is checked or unchecked.
View
The view module is responsible to display data i.e. it represents the presentation.
The view determines how a component has displayed on the screen, including any aspects of
view that are affected by the current state of the model.
Controller
The controller determines how the component will react to the user.
The controller module acts as an interface between view and model.
It intercepts all the requests i.e. receives input and commands to Model / View to change
accordingly.
COMPONENT CLASS
The methods of Component class are widely used in java swing that are given below.
Method
CONTAINER
The Container is a component that can contain another components like buttons, textfields,
labels etc.
The classes that extends Container class are known as container such as Frame, Dialog and
Panel.
WINDOW
The window is the container that have no borders and menu bars.
You must use frame, dialog or another window for creating a window.
JPANEL
The Panel is the container that doesn't contain title bar and menu bars.
It can have other components like button, textfield etc.
JDIALOG
The JDialog control represents a top level window with a border and a title used to take some
form of input from the user.
It inherits the Dialog class.
Unlike JFrame, it doesn't have maximize and minimize buttons.
JFrame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
import javax.swing.*;
);
Output:
We can also inherit the JFrame class, so there is no need to create the instance of JFrame class
explicitly.
EXAMPLE
import javax.swing.*;
JFrame f;
Simple2(){
b.setBounds(130,100,100, 40);
setSize(400,500);
setLayout(null);
setVisible(true);
new Simple2();
}}
SWING COMPONENTS
JButton
The JButton class is used to create a labeled button that has platform independent
implementation.
The application result in some action when the button is pushed.
It inherits AbstractButton class.
Example
import javax.swing.*;
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
Output:
JLabel
Example
mport javax.swing.*;
class LabelExample
JLabel l1,l2;
l1.setBounds(50,50, 100,30);
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
Output :
JTextField
The object of a JTextField class is a text component that allows the editing of a single line
text.
It inherits JTextComponent class.
Example
import javax.swing.*;
class TextFieldExample
JTextField t1,t2;
t1.setBounds(50,100, 200,30);
t2.setBounds(50,150, 200,30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
JTextArea
The object of a JTextArea class is a multiline region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class.
Example
import javax.swing.*;
TextAreaExample(){
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
new TextAreaExample();
}}
Output:
JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false).
Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
Example
import javax.swing.*;
CheckBoxExample(){
checkBox1.setBounds(100,100, 50,50);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
new CheckBoxExample();
}}
JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
Example
import javax.swing.*;
JFrame f;
RadioButtonExample()
f=new JFrame();
r1.setBounds(75,50,100,30);
bg.add(r1);
bg.add(r2);
f.add(r1);
f.add(r2);
f.setSize(300,300);
f.setVisible(true);
newRadioButtonExample();
Output:
JComboBox
Example
import javax.swing.*;
JFrame f;
ComboBoxExample()
String country[]={"India","Aus","U.S.A","England","Newzealand"};
f.add(cb);
f.setSize(400,500);
f.setVisible(true);
newComboBoxExample();
Output :
JTable
Example
import javax.swing.*;
JFrame f;
TableExample()
f=new JFrame();
String column[]={"ID","NAME","SALARY"};
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
newTableExample();
Output
JTree
The JTree class is used to display the tree structured data or hierarchical data.
JTree is a complex component. It has a 'root node' at the top most which is a parent for all
nodes in the tree. It inherits JComponent class.
Example
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
JFrame f;
TreeExample()
f=new JFrame();
style.add(color);
style.add(font);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
newTreeExample();
Output:
JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking on a tab
with a given title or icon. It inherits JComponent class.
Example
import javax.swing.*;
JFrame f;
TabbedPaneExample()
f=new JFrame();
p1.add(ta);
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
newTabbedPaneExample();
Output:
JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we
use a scroll pane to display a large component or a component whose size can change
dynamically.
Example
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_
ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWA
YS);
frame.getContentPane().add(scrollableTextArea);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
createAndShowGUI();
});
Output: