Oop Unit 1 2 4 5
Oop Unit 1 2 4 5
Objectives:
•To understand Object Oriented Programming concepts and basics of Java programming language.
•To learn the fundamentals core java, packages and collections for computing.
•To provide a good knowledge on string handling.
•To apply the various exception handling mechanism in java.
• To design login id for Gmail using applet and AWT container in java program.
Course Outcomes:
Upon successful completion of this course, the students will be able to:
CO1: Understand the object-oriented programming principles using java.
CO2: Apply the types of Inheritance, Packages and Interfaces supported by Java
CO3: Understand and apply I/O file operations, Generics and String Handling.
CO4: Apply exception handling mechanisms and multithreaded model to solve real world problems
Inheritance – Inheritance hierarchies super and sub classes, Member access rules, super keyword,
preventing inheritance: final classes and methods, the Object class and its methods.
Interfaces- Interfaces Vs Abstract classes, defining an interface, implement interfaces, Inner classes-
Uses of inner classes, local inner classes, anonymous inner classes, static inner classes, examples.
Packages- Defining, creating and accessing a package, Understanding CLASSPATH, importing
packages.
I/O Basics – Reading and Writing Console I/O – Reading and Writing Files. Generics: Generic
Programming – Generic classes – Generic Methods – Bounded Types. Strings: Basic String class,
methods and String Buffer Class.
Total period:45
Text books:
2
UNIT-1 INTRODUCTION TO OOP AND JAVA
OBJECT-ORIENTED PROGRAMMING
Object-Oriented Programming (OOP) is a programming language model
organized around objects rather than actions and data. An object-oriented program can be
characterized as data controlling access to code. Concepts of OOPS
● Object
● Class
● Inheritance
● Polymorphism
● Abstraction
● Encapsulation
OBJECT
Object means a real word entity such as pen, chair, table etc. Any entity that has state
and behavior is known as an object. Object can be defined as an instance of a class. An object
contains an address and takes up some space in memory. Objects can communicate without
knowing details of each other's data or code, the only necessary thing is that the type of
message accepted and type of response returned by the objects.
An object has three characteristics:
● state: represents data (value) of an object.
● behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
● identity: Object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. But, it is used internally by the JVM to
identify each object uniquely.
CLASS
Collection of objects is called class. It is a logical entity. A class can also be defined as
a blueprint from which you can create an individual object. A class consists of Data members
and methods.The primary purpose of a class is to hold data/information. The member functions
determine the behavior of the class,
i. e. provide a definition for supporting various operations on data held in the form of
an object.Class doesn’t store any space.
INHERITANCE
Inheritance can be defined as the procedure or mechanism of acquiring all the
properties and behavior of one class to another, i.e., acquiring the properties and behavior of
child class from the parent class. When one object acquires all the properties and behaviours of
another object, it is known as inheritance. It provides code reusability and establishes
relationships between different classes. A class which inherits the properties is known as Child
Class(sub-class or derived class) whereas a class whose properties are inherited is known as
Parent class(super-class or base class). Types of inheritance in java: single, multilevel and
hierarchical inheritance. Multiple and hybrid inheritance is supported through interface only.
3
POLYMORPHISM
When one task is performed by different ways i.e. known as polymorphism. For
example: to convince the customer differently, to draw something e.g. shape or rectangle etc.
Method Overloading is a feature that allows a class to have two or more methods having the
same name but the arguments passed to the methods are different. Compile time
polymorphism refers to a process in which a call to an overloaded method is resolved at
compile time rather than at run time.
METHOD OVERRIDING(RUN TIME POLYMORPHISM)
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java.In other words, If subclass provides the specific implementation of
the method that has been provided by one of its parent class, it is known as method overriding.
ABSTRACTION
Abstraction is a process of hiding the implementation details and showing only
functionality to the user. For example: phone call, we don't know the internal processing.In
java, we use abstract class and interface to achieve abstraction.
ENCAPSULATION
Encapsulation in java is a process of wrapping code and data together into a single
unit, for example capsule i.e. mixed of several medicines.A java class is the example of
encapsulation.
4
Overview of OOP
5
CHARACTERISTICS OF PROCEDURAL ORIENTED PROGRAMMING:-
1. It focuses on process rather than data.
2. It takes a problem as a sequence of things to be done such as
reading, calculating and printing. Hence, a number of functions are
written to solve a problem.
3. A program is divided into a number of functions and each function
has clearly defined purpose.
4. Most of the functions share global data.
5. Data moves openly around the system from function to function.
6. Employs top-down approach in program design.
DRAWBACK OF POP
⮚ Procedural languages are difficult to relate with the real world objects.
⮚ Procedural codes are very difficult to maintain, if the code grows larger.
⮚ Procedural languages do not have automatic memory management as like in
Java. Hence, it makes the programmer to concern more about the memory
management of the program.
The data, which is used in procedural languages, are exposed to the whole
program.So, there is no security for the data.
⮚ Examples of Procedural languages :
o BASIC
o C
o Pascal
o FORTRAN
Difference between POP and OOP:
Procedure Oriented
Object Oriented Programming
Programming
Divided Into In POP, program is divided into In OOP, program is divided into
smallparts called functions. partscalled objects.
6
In POP, Importance is not given to In OOP, Importance is given to the
Importance data but to functions as well data rather than procedures or
JAVA – as sequence of actions to be done. functions because it works as a
DATA real world.
TYPES Approach POP follows Top Down OOP follows Bottom Up
approach. approach.
Access POP does not have any OOP has access specifiers
Specifiers accessspecifier. named Public,
Private,
Protected, etc.
In POP, Data can move freely from In OOP, objects can move and
Data Moving function to function in the system. communicate with each other
throughmember functions.
Expansion To add new data and function in OOP provides an easy way to add
POPis not so easy. newdata and function.
In POP, Most function uses Global In OOP, data cannot move easily
Data Access data for sharing that can be from function to function, it can be
accessed freely from function to kept public or private so we can
function in the control the access of data.
system.
Data Hiding POP does not have OOP provides Data Hiding
any proper wayfor hiding data so it so provides more security.
is less secure.
In POP, Overloading is In OOP, overloading is possible in
Overloading not possible. the form of Function Overloading
and Operator Overloading.
Examples Examples of POP are: C,VB, Examples of OOP are: C++, JAVA,
FORTRAN, and Pascal. VB.NET, C#.NET.
DATA TYPE IS USED TO ALLOCATE SUFFICIENT MEMORY SPACE FOR THE DATA. DATA TYPES
SPECIFY THE DIFFERENT SIZES AND VALUES THAT CAN BE STORED IN THE VARIABLE.
1. Primitive data types (Intrinsic or built-in types ) :- : The primitive data
types include boolean, char, byte, short, int, long, float and double.
2. Non-primitive data types (Derived or Reference Types): The
non-primitive data types include Classes, Interfaces, Strings and Arrays.
7
1. PRIMITIVE TYPES:
Primitive data types are those whose variables allow us to store only one
value and neverallow storing multiple values of same type. This is a data type
whose variable can hold maximum one value at a time.
⮚ INTEGER TYPES:
The integer types are form numbers without fractional parts. Negative values
are allowed.Java provides the four integer types shown below:
Storage Default
Type Range Example
Requirement Value
-2,147,483,648(-2^31)
int a = 100000,
int 4 bytes to 0
int b = -200000
2,147,483,647
(2^31-1)
short s = 10000,
short 2 bytes -32,768 (-2^15) to 32,767 (2^15-1) 0
short r = -20000
-9,223,372,036,854,775,808 (-2^63)
long a =
long 8 bytes to 0L
100000L, int b =
9,223,372,036,854,775,808 (2^63-1)
-200000L
byte a = 100 ,
byte 1 byte -128 (-2^7) to 127 (2^7-1) 0
byte b = -50
⮚ FLOATING-POINT TYPES:
The floating-point types denote numbers with fractional parts.
The two floating-pointtypes are shown below:
Storage Defa
Type Range Example
Requirement t
8
Valu
Approximately
Float 4 bytes float f1 =234.5f 0.0f
±3.40282347E+38F (6-7
significant decimal digits)
Approximately
double d1
double 8 bytes ±1.79769313486231570E+308 0.0d
= 123.4
(15 significant decimal digits)
⮚ CHAR:
● C
Char
● Char data type is a single 16-bit Unicode character.
● Minimum value is '\u0000' (or 0).
● Maximum value is '\uffff' (or 65,535 inclusive).
● Char data type is used to store any character.
● Example: char letterA ='A'
⮚ BOOLEAN:
● Example
int a[] = {10,20,30};
// valid int b[] = {100, 'A',
"ABC"};
// invalid
9
Animal animal = new Animal("giraffe"); //Object
JAVA - VARIABLES
⮚ A VARIABLE IS A NAMED PIECE OF MEMORY THAT IS USED FOR STORING DATA IN JAVA
PROGRAM.
⮚ A variable is an identifier used for storing a data value.
⮚ A Variable may take different values at different times during the
execution if the program, unlike the constants.
⮚ The variable's type determines what values it can
hold and what operations can beperformed on it.
⮚ SYNTAX TO DECLARE VARIABLES:
datatype identifier [=value][,identifier [ =value] …];
1. A variable name must begin with a letter and must be a sequence of letter
or digits.
2. They must not begin with digits.
3. Uppercase and lowercase variables are not the same.
a. Example: Total and total are two variables which are distinct.
4. It should not be a keyword.
5. Whitespace is not allowed.
6. Variable names can be of any length.
⮚ INITIALIZING VARIABLES:
✔ After the declaration of a variable, it must be initialized by means of
assignment statement.
✔ It is not possible to use the values of uninitialized variables.
10
2.Declare and initialize on the same line:
SYNTAX:
int months=12;
⮚ DYNAMIC INITIALIZATION OF A VARIABLE:
Java allows variables to be initialized dynamically using any valid expression at the
timethe variable is declared.
class FindRemainer
{
OUTPUT:
Remainder is 1
In the above program there are three variables num, den and rem. num and
den ate initialized by constants whereas rem is initialized dynamically by the
modulo division operation on num and den.
11
Class variables also known as
EXAMPLE static variables are declared
PROGRAM Instance variables are declared with the static keyword in a
in a class, but outside a class, but outside a method,
Local variables aredeclared in constructor or a block.
method, constructor or any
methods, constructors, or There would only be one copy
block.
blocks. of each class variable per clas
regardless of how many objec
are created from it.
Access modifiers cannot be used Access modifiers can be used Access modifiers can be used
for local variables. forinstance variables. for class variables.
Local variables are visible only The instance variables are Visibility is similar to instance
within the declared method, visible for all methods, variables.
constructor or block. constructors and block in the
class.
Instance variables have default
values. For numbers the default
There is no default value for value is 0, for Booleans it is
local variables so local false and for object references it Default values are same as
variables should be declared is null. Values can be assigned instance variables.
and an initial value shouldbe during
assigned before the first use. the declaration or within the
constructor.
Instance variables can be
accesseddirectly by calling the
variable name inside the class.
However within static methods Static variables can be accesse
Local variables can only be
and different class should be by calling with the class name
access inside the declared
block. called using the fully qualified ClassName.VariableName.
name as follows:
ObjectReference.VariableNa
me.
ILLUSTRATING THE USE OF ALL THE ABOVE VARIABLES:
class area
{
int length=20; int breadth=30;
12
{
int areas=length*breadth;
System.out.println(“The area is “+areas+” sq.cms”);
}
OUTPUT:
The area is 600 sq.cms
Static Variable Value :
2500
PROGRAM EXPLANATION:
Class name: area
Method names: calc() and main()
Local variables: areas (accessed only in the particular method)
Instance variables: length and breadth (accessed only through the object‘s method) Static
variable: accessed anywhere in the program, without object reference
ARRAYS
AN ARRAY IS A COLLECTION OF SIMILAR TYPE OF ELEMENTS WHICH HAS CONTIGUOUS MEMORY LOCATION.
Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements. We can store only a fixed set of
elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.
ADVANTAGE OF ARRAY:
• Code Optimization: It makes the code optimized; we can retrieve or sort the
data easily.
• Random access: We can get any data located at any index position.
13
DISADVANTAGE OF ARRAY:
● Size Limit: We can store only fixed size of elements in the array. It doesn't
growits size at runtime.
TYPES OF ARRAY:
There are two types of array.
1. One-Dimensional Arrays
2. Multidimensional Arrays
1.ONE-DIMENSIONAL ARRAY:
⮚ Creating an array:
Three steps to create an array:
1.Declaration of the array
2.Instantiation of the array
3.Initialization of arrays
1.DECLARATION OF THE ARRAY:
Declaration of array means the specification of array variable, data_type and array_name.
SYNTAX TO DECLARE AN ARRAY IN JAVA:
Example:
SYNTAX:
arrayRefVar=new datatype[size];
14
Syntax to initialize values to array element:
Example:
floppy[0]=20;
EXAMPLE 1:
int regno[]={101,102,103,104,105,106};
int reg[]=regno;
ARRAY LENGTH:
The variable length can identify the length of array in Java. To find the number of
elements of an array, use array.length.
EXAMPLE1:
int regno[10]; len1=regno.length;
EXAMPLE 2:
for(int
i=0;i<reno.len
gth;i++)
System.out.pr
intln(regno[i])
;
Following picture represents array myList. Here, myList holds ten double values
and the indicesare from 0 to 9.
Example: (One-Dimensional Array)
15
class Array
{
int month_days[];
month_days=new int[12];
month_days[0]=31;
month_days[1]=28;
month_days[2]=31;
month_days[3]=30;
month_days[4]=31;
month_days[5]=30;
month_days[6]=31;
month_days[7]=31;
month_days[8]=30;
month_days[9]=31;
month_days[10]=30;
month_days[11]=31;
OUTPUT:
Example 2: Finding sum of the array elements and maximum from the array:
16
public class TestArray{
public static void main(String[] args)
{
System.out.println(element);
}
total += myList[i];
}
max = myList[0];
for (int i = 1; i < myList.length; i++)
{
OUTPUT:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
2.Multidimensional Arrays:
Definition:
17
Uses of Multidimensional Arrays:
int[][] arr=new int[3][3]; //3 row and 3 column - internally this matrix is implemented as
arrays of arrays of int.
System.out.println("-------Array 1 " );
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
18
{
array1[i][j]=k;k++;
System.out.print(array1[i][j]+"");
}
System.out.println();
}// printing 2D array2
System.out.println("-------Array 2 ");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{System.out.print(array2[i][j]+
System.out.println();
}
}}
Output:
-------------Array1------
------ 0 1 2 3 4
56789
10 11 12 13 14
15 16 17 18 19
-------------Array2------------
123
245
445
19
EXAMPLE: MANUALLY ALLOCATE DIFFERING SIZE SECOND DIMENSIONS:
class twoDarray
{
array1[0]=new int[1];
array1[1]=new int[2];
array1[2]=new int[3];
array1[3]=new int[4];
int i,j,k=0;
for(i=0;i<4;i++)
{ for(j=0;j<i+1;j++) {
array1[i][j]=k;k++;
System.out.print(array1[i][j]+ " ");
}
System.out.println();
}}
OUTPUT:
0
12
345
678
OPERATORS
Operators are used to manipulate primitive data types.
Java operators can be classified as unary,binary, or ternary—meaning taking one, two, or three
arguments, respectively.
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform
various operations
i.e.:
20
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a boolean
JAVA UNARY OPERATOR EXAMPLE: ++ AND –
1. class OperatorExample
2. {
3. public static void main(String args[])
4. {
5. int x=10;
6. System.out.println(x++); //10 (11)
7. System.out.println(++x); //12
8. System.out.println(x--); //12 (11)
9. System.out.println(--x); //108.
10.}
11.}
Output:
10
12
12
10
21
4. int b=-10;
5. BOOLEAN C=TRUE;
OUTPUT:
-11
9
False true
A binary or ternary operator appears between its arguments.Java operators
eight different categories:
1. Assignment
2. Arithmetic
3. Relational
4. Logical
5. Bitwise
6. Compound assignment
7. Conditional
8. Type.
Assignment Operators =
Arithmetic Operators - + * / % ++ --
Relational Operators > < >= <= == !=
Logical Operators && || & | ! ^
Bit wise Operator & | ^ >> >>>
Compound Assignment += -= *= /= %=
Operators <<= >>= >>>=
Conditional Operator ?:
If the value already exists in the variable it is overwritten by the assignment operator (=).
22
JAVA ASSIGNMENT OPERATOR EXAMPLE
1. class OperatorExample{
2. public static void main(String args[])
3. {
4. int a=10;
5. int b=20;
6. a+=4; //a=a+4 (a=10+4)
7. b-=4; //b=b-4 (b=20-4)
8. System.out.println(a);
9. System.out.println(b);
10. }
11.}
OUTPUT:
23
5. System.out.println(10*10/5+3-1*4/2);4.
6. }
7. }
OUTPUT:
21
RELATIONAL OPERATORS
Relational operators in Java are used to compare 2 or more objects. Java provides sixrelational
operators: Assume variable A holds 10 and variable B holds 20, then:
Checks if the value of left operand is greater than or equal (A >= B) is not
>= tothe value of right operand, if yes then condition becomes true.
true.
LOGICAL OPERATORS
Logical operators return a true or false value based on the state of the Variables. Given that x
and y represent boolean expressions, the boolean logical operators are defined in the Table
below.
x&y x|y
X y !x x && y x || y x^y
True true false true true False
True false false false true true
False true true false true true
False false true false false false
24
BITWISE OPERATORS
Java provides Bit wise operators to manipulate the contents of variables at the bit level. The
result of applying bitwise operators between two corresponding bits in the operandsis shown
in the Table below.
A B ~A A&B A|B A^B
1 1 0 1 1 0
1 0 0 0 1 1
0 1 1 0 1 1
0 0 1 0 0 0
CONDITIONAL OPERATORS
The Conditional operator is the only ternary (operator takes three arguments) operator in
25
Java. The operator evaluates the first argument and, if true, evaluates the second argument.
If the first argument evaluates to false, then the third argument is evaluated. The conditional
operator is the expression equivalent of the if-else statement.
The conditional expression can be nested and the conditional operator associates from right
to left: (a?b?c?d:e:f:g) evaluates as (a?(b?(c?d:e):f):g)
EXAMPLE:
instanceof Operator:
This operator is used only for object reference variables. The operator checks whether the
object is of a particular type(class type or interface type). instanceof operator is written as:
( Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check for
the class/interface type on the right side, then the result will be true. Following is the
EXAMPLE:
public class Test
{
26
}}
OPERATOR PRECEDENCE:
The order in which operators are applied is known as precedence. Operators with a higher
precedence are applied before operators with a lower precedence.
The operator precedence order of Java is shown below. Operators at the top of the table are
applied before operators lower down in the table.
If two operators have the same precedence, they are applied in the order they appear in a
statement. That is, from left to right. You can use parentheses to override the default
precedence.
Category Operator Associativity
Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right
EXAMPLE:
First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19. Note
that ‗*‘ takes higher precedence than ‗+‘ according to chart shown above. This kindof
precedence of one operator over another applies to all the operators.
CONTROL-FLOW STATEMENTS
27
Java Control statements control the order of execution in a java program, based on data
values and conditional logic.
There are two types of decision making statements in Java. They are:
● if statements
● if-else statements
● nested if statements
● if-else if-else statements
● switch statements
if Statement:
● An if statement consists of a Boolean expression followed by one or more
statements.
● SYNTAX
IF(<CONDITIONAL EXPRESSION>)
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed.
If not the first set of code after the end of the if statement (after the closingcurly brace) will
be executed.
FLOWCHART:
28
if-else Statement:
The if/else statement is an extension of the if statement. If the statements in the
ifstatement fails, the statements in the else block are executed.
SYNTAX:
The if-else statement has the following syntax:
IF(<CONDITIONAL EXPRESSION>)
else
29
NESTED IF STATEMENT:
Nested if-else statements, is that using one if or else if statement inside another if or
else ifstatement(s).
SYNTAX:
if(condition1)
{
if(condition2)
{
else
{
else
{
30
IF...ELSE IF...ELSE STATEMENT:
An if statement can be followed by an optional else if...else statement, which is veryuseful to test
various conditions using single if...else if statement.
Syntax:
if(Boolean_expression 1){
}else {
EXAMPLE:
public class Test {
31
OUTPUT:
Value of X is 30
switch Statement:
Values. Eachvalue is called a case, and the variable being switched on is checked for
each case.
The switch statement begins with a keyword, followed by an expression that equates
to a no long integral value. Following the controlling expression is a code block that
contains zero or more labeled cases. Each label must equate to an integer constant and
each must be unique.
When the switch statement executes, it compares the value of the controlling
expression to the values of each case label.
The program will select the value of the case label that equals the value of the
controllingexpression and branch down that path to the end of the code block.
If none of the case label values match, then none of the codes within the
switch statementcode block will be executed.
Java includes a default label to use in cases where there are no matches. We
can have a nested switch within a case block of an outer switch.
EXAMPLE:
public class SwitchCaseStatementDemo {
case 3: default:
System.out.println("Cannot be determined");
OUTPUT:
c is the greatest
While Statement
<statements>
Example:
OUTPUT
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
Do
<loop body>
}while (<loop condition>);
Example:
int count = 1;
System.out.println("Printing Numbers from 1 to 10"); do {
System.out.println(count++);
} while (count <= 10);
}
OUTPUT:
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
FOR LOOPS
THE FOR LOOP IS A LOOPING CONSTRUCT WHICH CAN EXECUTE A SET OF INSTRUCTIONS A
SPECIFIEDNUMBER OF TIMES. IT‘S A COUNTER CONTROLLED LOOP. A FOR STATEMENT CONSUMES THE
INITIALIZATION, CONDITION AND INCREMENT/DECREMENT IN ONE LINE. IT IS THE ENTRY CONTROLLED
LOOP.
SYNTAX:
for (<initialization>; <loop condition>; <increment expression>)
<LOOP BODY>
}
System.out.println(count);
}
OUTPUT:
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
ENHANCED FOR LOOP OR FOR- EACH LOOP:
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
The for-each loop is used to traverse array or collection in java.
It is easier to use than simple for loop because we don't need to increment
value and usesubscript notation.
It works on elements basis not index.
It returns element one by one in the defined variable.
Syntax:
for(declaration : expression)
//Statements
System.out.print( x );
System.out.print(",");
System.out.print("\n\n");
String [] names ={"B", "C", "C++", "JAVA"};
for( String name : names )
{
EXAMPLE:
System.out.print( x ); System.out.print("\n");
}
Output:
10
20
if( x == 30 )
{
continue;
}
System.out.pri
nt( x );
System.out.pri
nt("\n");
}
OUTPUT:
10
20
40
50
DEFINING CLASSES AND OBJECTS
DEFINING A CLASS:
The keyword class is used to define a class.
Rules to be followed:
1. Classes must be enclosed in parentheses.
2. The class name, superclass name, instance variables and method names
may be any validJava identifiers.
3. The instance variable declaration and the statements of the methods
must end with ;(semicolon).
4. The keyword extends means derived from i.e. the class to the left of the
EXTENDS
(subclass) is derived from the class to the right of the extends (superclass).
SYNTAX TO DECLARE A CLASS:
✔ The data, or variables, defined within a class are called instance variables.
✔ The code to do operations is contained within methods.
✔ Collectively, the methods and variables defined within a class are called members
of theclass.
✔ Variables defined within a class are called instance variables because
each instance of theclass (that is, each object of the class) contains its
own copy of these variables.
✔ Thus, the data for one object is separate and unique from the data for another.
✔ EXAMPLE:
Program Explanation:
DEFINING OBJECTS
It is a structured set of data with a set of operations for manipulating that data.
The methods are the only gateway to access the data. In other words, the
methods and dataare grouped together and placed in a container called
Object.
CHARACTERISTICS OF AN OBJECT:
An object has three characteristics:
1) State: represents data (value) of an object.
2) Behavior: represents the behavior (functionality) of an
object such as deposit, withdraw etc.
3) Identity: Object identity is an unique ID used internally
by the JVM to identify each object uniquely.
4) For Example: Pen is an object. Its name is Reynolds,
color is white etc. known
state. It is used to write, so writing is its behavior.
CREATING OBJECTS:
Obtaining objects of a class is a two-step process:
1. Declare a variable of the class type – this variable does not define an
object. Instead,it is simply a variable that can refer to an object.
2. Use new operator to create the physical copy of the object and
assign the referenceto the declared variable.
NOTE: The new operator dynamically allocates memory for an object and returns a
referenceto it. This reference is the address in memory of the object allocated by new.
Advantage of using new operator: A program can create as many as objects it needs
duringthe execution of the program.
SYNTAX:
Example:
box b1=new
box();(or) box b2;
b2=new box();
ACCESSING CLASS MEMBERS:
✔ Accessing the class members means accessing instance variable and instance
methods in a class.
✔ To access these members, a dot (.) operator is used along with the objects.
SYNTAX FOR ACCESSING THE INSTANCE MEMBERS AND METHODS:
1.11: METHODS
DEFINITION :
Syntax: Method:
modifier Return –type method_name(parameter_list) throws exception_list
{
// method body
}
modifier: It defines the access type of the method and it is optional to use.
returnType: Method may return a value.
Method_name: This is the method name. The method signature consists of
the methodname and the parameter list.
Parameter List: The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero
parameters.
method body: The method body defines what the method does with statements.
METHOD CALLING (EXAMPLE FOR METHOD THAT TAKES PARAMETERS AND RETURNING
VALUE):
The protected access specifier makes the instance variables and instance
methods visibleto all the classes, subclasses of that package and
subclasses of other packages.
4. DEFAULT (CAN BE ACCESSED ONLY BY THE CLASSES IN THE SAME PACKAGE):
The default access modifier is friendly. This is similar to public modifier
except only theclasses belonging to a particular package knows the
variables and methods.
FirstClas
{
SecondClass obj=new
SecondClass(); obj.method();
}
Output:
I am public variable
I am protected variable
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code -
k has private access in MyPack.FirstClass
“static” MEMBERS:
STATIC MEMBERS ARE DATA MEMBERS (VARIABLES) OR METHODS THAT BELONG TO A STATIC OR
NON-STATIC CLASS RATHER THAN TO THE OBJECTS OF THE CLASS. HENCE IT IS NOT NECESSARY
TO CREATE OBJECT OF THAT CLASS TO INVOKE STATIC MEMBERS.
STATIC VARIABLE:
✔ When a member variable is declared with the static keyword, then it
is called static variable and it can be accessed before any objects of
its class are created, and without reference to any object.
✔ Syntax to declare a static variable:
[ACCESS_SPEFIER] STATIC DATA_TYPE INSTANCE_VARIABLE;
✔ When a static variable is loaded in memory (static pool) it creates only a
single copy of static variable and shared among all the objects of the
class.
✔ A static variable can be accessed outside of its class directly by
the class name anddoesn‘t need any object.
SYNTAX : <CLASS-NAME>.<VARIABLE-NAME>
Advantages of static variable
STATIC METHOD:
If a method is declared with the static keyword , then it is known as static
method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
O SYNTAX: (DEFINING STATIC METHOD)
STATIC BLOCK:
Static block is used to initialize the static data member like constructors helps to
initialize instance members and it gets executed exactly once, when the class is
first loaded.
Syntax:
The following example shows a class that has a static method, some static variables,
and a static
initialization block:
class Student
{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to create and display the values of object
public class TestStaticMembers{
static
{
System.out.println(―*** STATIC MEMBERS – DEMO ***‖);
}
public static void main(String args[])
{
Student.change(); //calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Here is the output of this program:
*** STATIC MEMBERS – DEMO ***
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
1.12: CONTRUCTORS
DEFINITION:
All data fields are initialized to their default value (0, false or null).
All field initializers and initialization blocks are executed, in the order in
which theyoccur in the class declaration.
If the first line of the constructor calls a second constructor, then the body of
thesecond constructor is executed.
The body of the constructor is executed.
TYPES OF CONSTRUCTORS
There are two types of constructors:
Default constructor
no-arg constructor
Parameterized constructor
DEFAULT CONSTRUCTOR
Default constructor refers to a constructor that is automatically created by
compilerin the absence of explicit constructors.
Rule: If there is no constructor in a class, compiler automaticaaly creates a default
constructor.
Purpose of Default Constructor: It is used to provide the default values to the
object members like 0, null etc. depending on the data type.
NO-ARGUMENT CONSTRUCTOR
Constructor without parameters is called no-argument constructor.
Purpose of No-Arg Constructor: It is used to provide values to be common for all objects
of the class.
Parameterized Constructor
A constructor that takes parameters is known as parameterized constructor.
Purpose of parameterized constructor
Parameterized constructor is used to provide different values to the distinct objects.
CONSTRUCTOR OVERLOADING:
Definition:
CONSTRUCTOR CHAINING:
Constructor chaining is the process of calling one constructor of a class from
another constructor of the same class or another class using the current object
of the class.It occurs through inheritance.
Within the same class: If we want to call the constructor from the same class, then we use
this keyword.
From the base class: If we want to call the constructor that belongs to different classes
(parent and child classes), we use the super keyword to call the constructor from the base
class.
RULES OF CONSTRUCTOR CHAINING:
✔ An expression that uses this keyword must be the first line of the
constructor.
✔ Order does not matter in constructor chaining.
✔ There must exist at least one constructor that does not use this
ADVANTAGE:
✔ Avoids duplicate code while having multiple constructors.
✔ Makes code more readable
DESTRUCTOR
A DESTRUCTOR, US THE NAME IMPLIES IS USED TO DESTROY THE OBJECTS THAT HAVE BEEN
CONSTRUCTOR. LIKE A CONSTRUCTOR, THE DESTRUCTOR IS A MEMBER
CREATED BY A
FUNCTION WHOSE NAME IS THE SAME AS THE
For Example:-
~ integer( ) { }
A destructor never takes any argument nor does it return any value. It will be invoked
implicitly by the compiler upon exit from the program to clean up storage that is no longer
accessible. It is a good practice to declare destructor in a program since it releases memory
space for
future use.
Delete is used to free memory which is created by new.
Example:-
matrix : : ~ matrix( )
delete p[i];
delete p;
UNIT 2
INHERITANCE
Inheritance is the mechanism in java by which one class is allow to inherit the
features (fields and methods) of another class. It is process of deriving a new class from an
existing class. A class that is inherited is called a superclass and the class that does the
inheriting is called a subclass. Inheritance represents the IS-A relationship, also known as
parent-child relationship. The keyword used for inheritance is extends.
Syntax:
Here, the extends keyword indicates that we are creating a new class that derives from an
existing class. Note: The constructors of the superclass are never inherited by the subclass
advantages of Inheritance:
• Code reusability — public methods of base class can be reused in derived classes
• Data hiding – private data of base class cannot be altered by derived class
• Overriding—With inheritance, we will be able to override the methods of the base class in
the derived class Example: //
Create a superclass.
System.out.println(“Sum:”+(a+b));
System.out.println(“Difference:”+(a-b));
obj.add(); obj.sub(); } }
Sample Output:
Sum:30
Difference:-10
In this example, Main is the subclass and BaseClass is the superclass. Main object can access
the field of own class as well as of BaseClass class i.e. code reusability.
● Superclass (Parent Class): The class whose properties and methods are inherited by
another class.
● Subclass (Child Class): The class that inherits the properties and methods of the
superclass.
● Use the extends keyword to create a subclass that inherits from a superclass.
Java
Copy code
class Superclass {
// Fields, constructors, methods
}
Example
java
Copy code
// Superclass
public class Animal {
String name;
// Subclass
public class Dog extends Animal {
public void bark() {
System.out.println(“The dog barks.”);
}
}
Inherited Members
● Fields and Methods: All non-private fields and methods of the superclass are
inherited by the subclass.
● Constructors: Constructors are not inherited, but the subclass can call the superclass
constructor using super().
Overriding Methods
Java
Copy code
public class Dog extends Animal {
@Override
public void eat() {
System.out.println(“The dog eats bones.”);
}
}
The super Keyword
Java
Copy code
public class Animal {
String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + “ eats food.”);
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name); // Call to superclass constructor
} @Override
public void eat() {
super.eat(); // Call to superclass method
System.out.println(name + “ eats bones.”);
}
}
Java
Copy code
class A {
// Fields and methods
}
class B extends A {
// Additional fields and methods
}
class C extends B {
// Additional fields and methods
}
● Private Members: Private fields and methods of the superclass are not accessible
directly in the subclass.
● Protected Members: Protected fields and methods are accessible in the subclass.
● Public Members: Public fields and methods are accessible everywhere.
● Package-Private Members: Accessible to subclasses only if they are in the same
package
Types of inheritance
Single Inheritance :
Example:
System.out.println(“Rectangle Area:”+(a*b));
}}
public class Main {
Multilevel Inheritance:
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also act as the base class to other class i.e. a derived class in turn acts as a base
class for another class.
Example:
System.out.println(“Sum of 2 nos.:”+(a+b));
{ System.out.println(“Sum of 3 nos.:”+(a+b+c)); }
obj.sum2();
obj.sum3(); } }
Sample Output:
Sum of 2 nos.:30
Sum of 3 nos.:60
hierarchical Inheritance:
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one
sub class.
Example:
class Shape{
int a=10,b=20; }
System.out.println(“Rectangle Area:”+(a*b)); }
{ System.out.println(“Triangle Area:”+(0.5*a*b)); } }
obj.rectArea();
obj1.triArea(); } }
Sample Output:
Rectangle Area:200
Triangle Area:100.0
Multiple inheritance
For example, Consider a class C derived from two base classes A and B. Class C inherits A
and B features. If A and B have a method with same signature, there will be ambiguity to call
method of A or B class. It will result in compile time error.
Class A{
void msg(){
System.out.println(“Class A”);} }
class B{
void msg()
{System.out.println(“Class B “);} }
Example:
// Create a superclass
class A{
x=a; y=b; } }
Class B extends A{
class Main{
B obj=new B();
obj.set_xy(10,20);
obj.add(); } }
In this example since y is declared as private, it is only accessible by its own class members.
Subclasses have no access to it.
UsIng sUper
The super keyword refers to immediate parent class object. Whenever you create the
instance of subclass, an instance of parent class is created implicitly which is referred by
super reference variable.
• It an be used to refer immediate parent class instance variable when both parent and child
class have member with same name
• It can be used to invoke immediate parent class method when child class has overridden
that method.
When both parent and child class have member with same name, we can use super keyword
to access ubcla of parent class.
Example:
class SuperCls {
int x = 20; }
int x = 80;
void display() {
class Main {
obj.display(); } }
sample Output:
In the above example, both base class and subclass have a member x. We could access x of
base class in ubclass using super keyword.
The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class (Method Overriding).
int x = 80;
class Main {
obj.display(); } }
Sample Output:
In the above example, if we only call method display() then, the display() of sub class gets
invoked. But with the use of super keyword, display() of superclass could also be invoked.
Use of super with constructors: The super keyword can also be used to invoke the parent
class constructor. Syntax:
super();
• super() if present, must always be the first statement executed inside a subclass constructor.
• When we invoke a super() statement from within a subclass constructor, we are invoking
the immediate super class constructor
Example:
class SuperCls {
SuperCls(){
SubCls()
{ super();
class Main {
INTERFACES
• An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
• Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.
Definitions
● Interface: A reference type in Java, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types. Interfaces
cannot contain instance fields.
● Abstract Class: A class that cannot be instantiated on its own and may contain
abstract methods (methods without implementation) as well as concrete methods
(methods with implementation).
When to Use
● Interfaces: Use when you want to define a contract that multiple classes can
implement, without enforcing a specific inheritance hierarchy.
● Abstract Classes: Use when you want to provide a common base class with some
shared implementation that other classes can inherit from and extend.
Syntax
● Interface:
java
Copy code
public interface MyInterface {
void abstractMethod();
default void defaultMethod() {
// Default implementation
}
static void staticMethod() {
// Static implementation
}
}
● Abstract Class:
java
Copy code
public abstract class MyAbstractClass {
abstract void abstractMethod(); // Abstract method (no implementation)
void concreteMethod() {
// Concrete method (with implementation)
}
}
Key Differences
1. Instantiation:
o Interface: Cannot be instantiated.
o Abstract Class: Cannot be instantiated directly.
2. Methods:
o Interface: Can contain abstract methods, default methods, and static methods.
o Abstract Class: Can contain abstract methods and concrete methods.
3. Fields:
o Interface: Can only have static final fields (constants).
o Abstract Class: Can have instance fields.
4. Inheritance:
o Interface: A class can implement multiple interfaces.
o Abstract Class: A class can extend only one abstract class (single
inheritance).
5. Access Modifiers:
o Interface: Methods are implicitly public; fields are implicitly public, static,
and final.
o Abstract Class: Can have any access modifier (public, protected, private) for
methods and fields.
6. Constructor:
o Interface: Cannot have constructors.
o Abstract Class: Can have constructors, which can be called by subclasses.
Example Usage
● Interface:
java
Copy code
public interface Animal {
void eat();
void sleep();
}
@Override
public void sleep() {
System.out.println(“Dog sleeps”);
}
}
● Abstract Class:
java
Copy code
public abstract class Animal {
abstract void eat();
void sleep() {
System.out.println(“Animal sleeps”);
}
}
Multiple Inheritance
Java
Copy code
public class Dog implements Animal, Pet {
// Implement methods from both interfaces
}
● Abstract Class: Does not support multiple inheritance of type. A class can extend
only one class.
Java
Copy code
public class Dog extends Canine {
// Can extend only one superclass
}
Use Cases
● Interfaces:
o When multiple unrelated classes need to implement a set of methods (e.g.,
Comparable, Runnable).
o To define a contract for what a class can do, without dictating how it does it.
o To achieve multiple inheritance of type.
● Abstract Classes:
o When creating a base class that should not be instantiated on its own.
o To provide common functionality to subclasses.
o When you want to define some methods that should be shared by all
subclasses while leaving others abstract.
Uses of interface:
• Since java does not support multiple inheritance in case of class, it can be achieved by using
interface.
Defining an Interface
Syntax:
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
return-type method-nameN(parameter-list);
• The java file must have the same name as the interface.
• The methods that are declared have no bodies. They end with a semicolon after the
parameter list. They are abstract methods; there can be no default implementation of any
method specified within an interface.
• Each class that includes an interface must implement all of the methods.
• Variables can be declared inside of interface declarations. They are implicitly final and
static, meaning they cannot be changed by the implementing class. They must also be
initialized.
Sample Code: The following code declares a simple interface Animal that contains two
methods called eat() and travel() that take no parameter.
interface Animal {
Implementing an Interface
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, the ‘implements’ clause is included in a class definition and then the
methods defined by the interface are created.
Syntax:
{ // class-body }
• If a class implements more than one interface, the interfaces are separated with a comma.
• If a class implements two interfaces that declare the same method, then the same method
will be used by clients of either interface.
Rules
• A class can extend only one class, but can implement many interfaces.
• An interface can extend another interface, in a similar way as a class can extend another
class.
Sample Code 1:
{ System.out.println(“Mammal eats”);
{ System.out.println(“Mammal travels”);
m.eat();
m.travel(); } }
Mammal travels
It is both permissible and common for classes that implement interfaces to define additional
members of their own. In the above code, Mammal class defines additional method called
noOfLegs().
Sample Code 2:
The following code initially defines an interface ‘Sample’ with two members. This interface
is implemented by a class named ‘testClass’.
Import java.io.*;
// A simple interface
interface Sample {
void display(); }
{ System.out.println(“Welcome”);
t.display();
System.out.println(name); } }
Output: Welcome
Shree
nested Interface
Sample Code:
interface MyInterfaceA
{ void display();
interface MyInterfaceB
{ void myMethod(); }
obj.myMethod(); } }
Both classes and Interfaces are used to create new reference types. A class is a collection of
fields and methods that operate on fields. A class creates reference types and these reference
types are used to create objects. A class has a signature and a body. The syntax of class
declaration is shown below:
Signature of a class has class’s name and information that tells whether the class has inherited
another class. The body of a class has fields and methods that operate on those fields. A Class
is created using a keyword class.
When a class is instantiated, each object created contains a copy of fields and methods with
them. The fields and members declared inside a class can be static or nonstatic. Static
members value is constant for each object whereas, the non-static members are initialized by
each object differently according to its requirement.
Members of a class have access specifiers that decide the visibility and accessibility of the
members to the user or to the subclasses. The access specifiers are public, private and
protected. A class can be inherited by another class using the access specifier which will
decide the visibility of members of a superclass (inherited class) in a subclass (inheriting
class).
An interface has fully abstract methods (methods with nobody). An interface is syntactically
similar to the class but there is a major difference between class and interface that is a class
can be instantiated, but an interface can never be instantiated.
An interface is used to create the reference types. The importance of an interface in Java is
that, a class can inherit only a single class. To circumvent this restriction, the designers of
Java introduced a concept of interface. An interface declaration is syntactically similar to a
class, but there is no field declaration in interface and the methods inside an interface do not
have any implementation. An interface is declared using a keyword interface.
Inheritance between concrete (non-abstract) and abstract classes use extends keyword. It is
possible to extend only one class to another. Java does not support multiple inheritance.
However, multilevel inheritance i.e., any number of classes in a ladder is possible. For
example, in the following code class C extends the class B, where the class B extends class
A.
class A {}
class B extends A { }
class C extends B { }
Inheritance between classes (including abstract classes) and interfaces, use implements
keyword.
To support multiple inheritance, it uses interfaces. So after implements keyword, there can be
any number of interfaces. For example, in the following code, class B extends only one class
A and two interfaces I1 and I2.
Interface I1 {}
interface I2 {}
Inheritance between two interfaces, is possible with the use of extends keyword only.
For example, in the following code, interface I2 extends the interface I1.
Interface I1 { }
nested classes
In Java, a class can have another class as its member. The class written within another class
is called the nested class, and the class that holds the inner class is called the outer class.
Java inner class is defined inside the body of another class. Java inner class can be declared
private, public, protected, or with default access whereas an outer class can have only public
or default access. The syntax of nested class is shown below:
class Outer_Demo { class Nested_Demo { } } types of nested classes There are two types of
nested classes in java. They are non-static and static nested classes. The non-static nested
classes are also known as inner classes.
Inner classes can be used as the security mechanism in Java. Normally, a class cannot be
related with the access specifier private. However if a class is defined as a member of other
class, then the inner class can be made private. This class can have access to the private
members of a class.
The Member inner class is a class written within another class. Unlike a class, an inner class
can be private and once you declare an inner class private, it cannot be accessed from an
object outside the class.
System.out.println(“n:”+n);
} } void print_inner()
inn.display(); }
}
public class Myclass
out.print_inner(); } }
In Java, a class can be written within a method. Like local variables of the method, the scope
of the inner class is restricted within the method. A method-local inner class can be
instantiated only within the method where the inner class is defined. The following program
shows how to use a method-local inner class. The following program is an example for
Method-local Inner Class
class MethodInner_class {
System.out.println(“n:”+n); }
out.Method1(); } }
An inner class declared without a class name is known as an anonymous inner class. The
anonymous inner classes can be created and instantiated at the same time. Generally, they are
used whenever you need to override the method of a class or an interface. The syntax of an
anonymous inner class is as follows –
}; inn.Method1(); } }
A static inner class is a nested class which is a static member of the outer class. It can be
accessed without instantiating the outer class, using other static members. Just like static
members, a static nested class does not have access to the instance variables and methods of
the outer class. Instantiating a static nested class is different from instantiating an inner class.
obj.Method1(); } }
There are basically three advantages of inner classes in java. They are as follows:
• Nested classes represent a special type of relationship that is it can access all the members
of outer class including private.
• Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
1. Built-in package
2. user-defined package.
Advantage of Package:
∙ Package is used to categorize the classes and interfaces so that they can be easily
maintained.
∙ The classes of one package are isolated from the classes of another package
⎫ When creating a package, you should choose a name for the package.
⎫ Put a package statement with that name at the top of every source file that contains the
classes and interfaces.
⎫ The package statement should be the first line in the source file.
{ …….. …….. }
2. Include package statement along with the package name as the first statement in the
program.
{ System.out.println(“Hello”); }
4. A package called pack has now been created which contains one class class1.
2.10.2: ACCESSING A PACKAGE (using “import” keyword):
∙ The import keyword is used to make the classes and interface of another package accessible
to the current package.
Syntax:
import package1[.package2][.package3].classname or *;
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
Using packagename.*
∙ If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
Using packagename.classname
∙ If you import package.classname then only declared class of this package will be accessible.
∙ If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.
Example :
package pack;
package Factorial;
if(a==1) return 1;
else return a*fact(a-1); }
import java.util.Scanner;
p1.greet();
System.out.println(“Power(“+n+”,2) = “+Math.pow(n,2));
}}
Enter a Number: 5
Factorial of 5 = 120
Power(5,2) = 25.0
What is CLASSPATH?
Setting CLASSPATH
● CLASSPATH can be set in several ways:
o Command Line: Using the -cp or -classpath option when running Java
applications.
Copy code
java -cp .:/path/to/classes:/path/to/jarfile.jar MyClass
Copy code
export CLASSPATH=.:/path/to/classes:/path/to/jarfile.jar
Components of CLASSPATH
● Current Directory (.): Including . in CLASSPATH allows the JVM to look for
classes in the current directory.
● Directories: Specify directories where compiled classes (.class files) are located.
● JAR Files: Specify JAR files that contain compiled classes and other resources.
● Packages: In Java, packages are used to group related classes and interfaces.
o Example: If you have a class MyClass in a package com.example, the
directory structure should be com/example/MyClass.class.
● Directory Structure: The CLASSPATH should include the parent directory of the
package structure.
o Example: If MyClass is in com/example, and the directory structure is
/myproject/com/example/MyClass.class, then /myproject should be in the
CLASSPATH.
Example
vbnet
Copy code
/myproject
├── com
│ └── example
│ └── MyClass.class
└── lib
└── some-library.jar
sh
Copy code
java -cp /myproject:/myproject/lib/some-library.jar com.example.MyClass
● Environment Variable:
sh
Copy code
export CLASSPATH=/myproject:/myproject/lib/some-library.jar
java com.example.MyClass
Best Practices
● Avoid Hardcoding CLASSPATH: Use build tools like Maven or Gradle to manage
dependencies and CLASSPATH.
● Use Wildcards: In the CLASSPATH, you can use * to include all JAR files in a
directory.
Sh
Copy code
java -cp “lib/*” com.example.MyClass
Understanding and properly setting the CLASSPATH is crucial for successfully running Java
applications, especially when dealing with packages and external libraries.
What is a Package?
● Package: A package in Java is a namespace that organizes a set of related classes and
interfaces. Using packages helps avoid name conflicts and makes it easier to locate
and use classes.
Default Package
● Classes can be part of the default package if they are not explicitly declared in a
package. However, using the default package is not recommended for larger
applications because it can lead to naming conflicts and difficulties in managing the
code.
Declaring a Package
● To declare a package, use the package keyword at the top of your Java file.
Java
Copy code
package com.example.mypackage;
Importing Packages
● Import Statement: To use classes and interfaces from other packages, you need to
import them using the import statement.
o Single Type Import: Imports a specific class.
Java
Copy code
import java.util.List;
Java
Copy code
import java.util.*;
Java
Copy code
import static java.lang.Math.*;
● After importing a class, you can use it directly without specifying its fully qualified
name.
java
Copy code
import java.util.List;
● Instead of using the import statement, you can use the fully qualified name of the
class each time you refer to it. This approach is less common due to verbosity.
Java
Copy code
public class MyClass {
public static void main(String[] args) {
java.util.List<String> myList = new java.util.ArrayList<>();
// Use myList as needed
}
}
Importing Custom Packages
● For custom packages, ensure that the directory structure matches the package name.
o Example: If the package name is com.example.mypackage, the directory
structure should be com/example/mypackage/MyClass.java.
● Compile the classes with the correct directory structure.
Sh
Copy code
javac com/example/mypackage/MyClass.java
Java
Copy code
import com.example.mypackage.MyClass;
● If two packages contain classes with the same name, you can avoid conflicts by using
the fully qualified name for at least one of them.
Java
Copy code
import com.example.package1.MyClass;
import com.example.package2.MyClass;
UNIT 4
An Exception is an event that occurs during program execution which disrupts the normal
flow of a program. It is an object which is thrown at runtime. Occurrence of any kind of
exception in java applications may result in an abrupt termination of the JVM or simply the
JVM crashes.
:Exception Hierarchy
All exceptions and errors extend from a common java.lang.Throwable parent class.
1. Exceptions and
2. Errors.
Exceptions: Exceptions represents errors in the Java application program, written by the user.
Because the error is in the program, exceptions are expected to be handled, either
∙ Try to recover it if possible
Sometimes it also happens that the exception could not be caught and the program may get
terminated. Eg. ArithmeticException
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs. ∙ A user has entered an invalid data.
∙ A network connection has been lost in the middle of communications or the JVM has run
out of memory. Some of these exceptions are caused by user error, others by programmer
error, and others by physical resources that have failed in some manner.
Errors: Errors represent internal errors of the Java run-time system which could not be
handled easily. Eg. OutOfMemoryError.
try Block:
⎫ The java code that might throw an exception is enclosed in try block. It must be used within
the method and must be followed by either catch or finally block.
⎫ If an exception is generated within the try block, the remaining statements in the try block
are not executed.
¬ catch Block:
⎫ Exceptions thrown during execution of the try block can be caught and handled in a catch
block.
⎫ On exit from a catch block, normal execution continues and the finally block is executed.
¬ finally Block:
A finally block is always executed, regardless of the cause of exit from the try block, or
whether any catch block was executed.
⎫ Generally finally block is used for freeing resources, cleaning up, closing connections etc.
⎫ Even though there is any exception in the try block, the statements assured by finally block
are sure to execute.
⎫ Rule:
∙ For each try block there can be zero or more catch blocks, but only one finally block.
∙ The finally block will not be executed if program exits(either by calling System.exit() or by
causing a fatal error that causes the process to abort).
try {
// Code block }
finally {
2) Not all statements in the try block will execute; the execution is interrupted if an exception
occurs
3) For each try block there can be zero or more catch blocks, but only one finally block.
4) The try block is followed by
ii. or, if a try block has no catch block, then it must have the finally block
5) A try block must be followed by either at least one catch block or one finally block.
6) A catch block specifies the type of exception it can catch. It contains the code known as
exception handler 7) The catch blocks and finally block must always appear in conjunction
with a try block.
8) The order of exception handlers in the catch block must be from the most specific
exception
int data=50/0;
Output:
Program Explanation:
The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:
∙ Prints the stack trace (Hierarchy of methods where the exception occurred).
System.out.println(data);
} catch(ArithmeticException e)
{ System.out.println(e); }
finally {
Built-in Exceptions
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions
are suitable to explain certain error situations. Below is the list of important built-in
exceptions in Java.
Checked Exceptions:
⎫ Checked exceptions are called compile-time exceptions because these exceptions are
checked at compile-time by the compiler.
⎫ Checked Exceptions forces programmers to deal with the exception that may be thrown.
⎫ The compiler ensures whether the programmer handles the exception using try.. catch ()
block or not. The programmer should have to handle the exception; otherwise, compilation
will fail and error will be thrown.
EXAMPLE:
1. ClassNotFoundException
2. CloneNotSupportedException
3. IllegalAccessException,
4. MalformedURLException.
5. NoSuchFileException
6. NoSuchMethodException
7. IOException
8. NoSuchFileException
9. NoSuchMethodException
10.IOException
Output:
To make program able to compile, you must handle this error situation in
Below given code will compile absolutely fine.
With try-catch
import java.io.*;
public class CheckedExceptionExample { public
static void main(String[] args) { try {
@SuppressWarnings("resource")
FileReader file = new FileReader("src/somefile.java"); System.out.println(file.toString());}
catch(FileNotFoundException e){ System.out.println("Sorry...Requested resource not
availabe...");
}}
}
Output:
UNCHECKED EXCEPTIONS(RUNTIMEEXCEPTION):
Consider the following Java program. It compiles fine, but it
throws ArithmeticException whenrun. The compiler allows it to compile,
because ArithmeticException is an unchecked exception.
class Main {
public static void main(String args[]) { int x
= 0;
int y = 10; int
z = y/x;
}
}
Output:
EXAMPLE:
1. ArrayIndexOutOfBoundsException
2. ArithmeticException
3. NullPointerException.
{try {
OUTPUT:
NullPointerException..
TRY {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;
System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format
exception");
}
OUTPUT:
Exception types created by the user to describe the exceptions related to their applications
are known as User-defined Exceptions or Custom Exceptions.
4 Write the code that might generate the defined exception inside the
try-catch block.
5.If the exception of user-defined type is generated, handle it using throw
clause
as follows:
THROW EXCEPTIONCLASSOBJECT;
Example:
The following program illustrates how user-defined exceptions can be created and
thrown.
public class EvenNoException extends Exception
EvenNoException(String str)
{
int arr[]={2,3,4,5};
int rem;
int i;
for(i=0;i<arr.length;i++)
{
rem=arr[i]%2;
TRY
if(rem==0)
{
catch(EvenNoException exp)
{
} // for loop
} // main()
} // class
Output:
2 is an Even Number
Exception thrown is EvenNoException: 3 is not an
Even Number 4 is an Even Number
Program Explanation:
In the above program, the EvenNumberException class is created which inherits the
Exception super class. Then the constructor is defined with the call to the super class
constructor. Next, an array arr is created with four integer values. In the main(), the array
elements are checked one by one for even number. If the number is odd, then the object of
EvenNumberException class is created and thrown using throw clause. The
EvenNumberException is handled in the catch block.
Basis
final finally finalize
for
compari
son
Basic Final is a "Keyword" and Finally is a "block" in Finalize is a "method" in
"access modifier" in Java. Java. Java.
Applicabl Final is a keyword applicable to Finally is a block that is finalize() is a method
e classes, variables and methods. always associated with applicable to objects.
try and catch block.
Working (1) Final variable becomes A "finally" block, clean Finalize method performs
constant, and it can't be up the resources used in cleans up activities related
reassigned. "try" block. to the object before its
(2) A final method can't be destruction.
overridden by the child class.
(3) Final Class can not be
extended.
Execution Final method is executed upon "Finally" block executes finalize() method executes
its call. just after the execution just before the destruction
of"try- catch" block. of the object.
Example class FinalExample{ public class FinallyExample{ class FinalizeExample{
static void main(String[] args){ public static void public void
final int x=100; main(String[] args){ try{ finalize(){System.out.pr
x=200;//Compile Time Error int x=300; intln("finalize called");}
}} }catch(Exception public static void
e){System.out.println main(String[] args){
(e);} FinalizeExample f1=new
finally{ FinalizeExample();
System.out.println("fi FinalizeExample f2=new
nally block is executed"); FinalizeExample(); f1=null;
} f2=null; System.gc();
}} }}
Definition: Thread
As
There is context-switching between the threads.
There can be multiple processes inside the OS, and one process can have multiple
threads.
3.6.1 MULTITHREADING
A program can be divided into a number of small processes. Each small process can
be addressed as a single thread.
Different states, a thread (or applet/servlet) travels from its object creation to object
removal (garbage collection) is known as life cycle of thread. A thread goes through
various stages in its life cycle. At any time, a thread always exists in any one of the following
state:
1 New State
2 Runnable State
3 Running State
4 Waiting/Timed Waiting/Blocked state
5 Terminated State/ dead state
A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread by calling start() method, which places the thread in the
runnable state.
✔ A new thread is also referred to as a born thread.
✔ When the thread is in this state, only start() and stop() methods can
be called. Calling any other methods causes an
IllegalThreadStateException.
✔ Sample Code: Thread myThread=new Thread();
2. RUNNABLE STATE:
After a newly born thread is started, the thread becomes runnable or running by
calling the run() method.
A thread in this state is considered to be executing its task.
Sample code: myThread.start();
The start() method creates the system resources necessary to run the thread,
schedules the thread to run and calls the thread’s run() method.
CATCH(INTERRUPTEDEXCEPTION EX) {}
❖ Blocked State:
When a particular thread issues an I/O request, then operating system moves the
thread to blocked state until the I/O operations gets completed.
✔ This can be achieved by calling suspend() method.
✔ After the I/O completion, the thread is sent back to the runnable state.
5. TERMINATED STATE:
A RUNNABLE THREAD ENTERS THE TERMINATED STATE WHEN,
(i) It completes its task (when the run() method has finished)
PUBLIC VOID RUN() { }
} catch(InterruptedException e) {
System.out.println(“Main Thread Interrrupted”);
}
Output:
Creating Threads
We can create threads by instantiating an object of type Thread. Java defines two
ways to create threads:
1.By implementing Runnable interface (java.lang.Runnable)
2.By extending the Thread class (java.lang.Thread)
// IMPLEMENTATION CODE
}
2.Override the run() method to define the code executed by the thread.
3.Create an object of type Thread by passing a Runnable object as
argument.
THREAD T=NEW THREAD(RUNNABLE THREADOBJ, STRING THREADNAME);
4.Invoke the start() method on the instance of the Thread class.
T.START();
● Example:
class MyThread implements Runnable
for(int i=0;i<3;i++)
try
Thread.sleep(1000);
}catch(InterruptedException e)
{
System.out.println(e);
}
}
OUTPUT:
Thread-0 # Printing 0 Thread-1 # Printing 0 Thread-1 # Printing 1 Thread-0 # Printing 1
Thread-0 # Printing 2 Thread-1 # Printing 2
---
2. Override the run() method in the sub class to define the code
executed by the thread.
3.Create an object of this sub class.
MYTHREAD T=NEW MYTHREAD(STRING THREADNAME);
4. Invoke the start() method on the instance of the subclass to
make the thread for running.
START();
● Example:
class SampleThread extends Thread
{
public void run()
{
for(int i=0;i<3;i++)
{
System.out.println(Thread.currentThread().getName()+" # Printing "+i);
try
{
Thread.sleep(1000);
}catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}
OUTPUT
Thread-0 # Printing 0
Thread-1 # Printing 0
Thread-1 # Printing 1
Thread-0 # Printing 1
Thread-0 # Printing 2
Thread-1 # Printing 2
THREAD PRIORITY
✔ Thread priority determines how a thread should be treated with
respect to others.
✔ Every thread in java has some priority, it may be default priority
generated by JVM or customized priority provided by programmer.
✔ Priorities are represented by a number between 1 and 10.
1 – Minimum Priority5 – Normal Priority 10 – Maximum Priority
✔ Thread scheduler will use priorities while allocating processor. The
thread which is having highest priority will get the chance first.
✔ Higher priority threads get more CPU time than lower priority threads.
✔ A higher priority thread can also preempt a lower priority thread.
For instance, when a lower priority thread is running and a higher
priority thread resumes (for sleeping or waiting on I/O), it will
preempt the lower priority thread.
✔ If two or more threads have same priorities, we can’t predict the
execution of waiting threads. It is completely decided by thread
scheduler. It depends on the type of algorithm used by thread
scheduler.
✔ 3 CONSTANTS DEFINED IN THREAD CLASS:
✔ Example:
class TestMultiPriority1 extends Thread{ public void
run(){
System.out.println("running thread name is:"+Thread.currentThread().getNam e());
System.out.println("running thread priority is:"+
Thread.currentThread().getPriority());
OUTPUT:
Thread Synchronization
Definition: Thread Synchronization
Thread synchronization is the concurrent execution of two or more threads that share
critical resources.
When two or more threads need to use a shared resource, they need some way to ensure
that the resource will be used by only one thread at a time. The process of ensuring single
thread access to a shared resource at a time is called synchronization.
✔ THREAD SYNCHRONIZATION
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
✔ 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
class Table{
SYNCHRONIZED VOID PRINTTABLE(INT N)//SYNCHRONIZED METHOD
FOR(INT
I=1;I<=5
;I++) {
SYSTEM.
OUT.PRIN
TLN(N*I);
TRY{
THREAD.
SLEEP(40
0); }
catch(Exception e) { System.out.println(e); }
class MyThread1
extends Thread {
Table t;
MyT
hread
1(Tab
le t){
this.t
=t;
}
public void
run(){
t.printTabl
e(5);
}
class MyThread2
extends Thread{
Table t;
MyT
hread
2(Tab
le t){
this.t
=t;
}
public void
run(){
t.printTabl
e(100);
}
public class
TestSynchronizati
on2{ public static
void main(String
args[]){
Table obj = new Table();
//only one object
MyThread1 t1=new
MyThread1(obj);
MyThread2 t2=new
MyThread2(obj);
t1.start();
t2.start();
}}
OUTPUT:
5
10
15
20
25
100
200
300
400
500
2.SYNCHRONIZED BLOCK IN JAVA
✔ Synchronized block can be used to perform synchronization on any
specific resource of the method.
✔ Suppose you have 50 lines of code in your method, but you want to
synchronize only 5 lines, you can use synchronized block.
✔ If you put all the codes of the method in the synchronized block, it
will work same as the synchronized method.
class Table{
void printTable(int n)
{
for(int
i=1;i<=5;i++)
{
System.out.pri
ntln(n*i);
try{ Thread.sleep(400); }catch(Exception
e){System.out.println(e);}
}
class MyThread1
extends
Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
class MyThread2
extends
Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
t1.start();
t2.start();
}
OUTPUT:
5
10
15
20
25
100
200
300
400
500
: Inter-Thread Communication
Inter-Thread Communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
It is implemented by following methods of Object class and all these
methods can be called only from within a synchronized context.
int Balance=10000;
System.out.println("going to withdraw..."+amount);
if(Balance<amount)
{
wait();
}
catch(Exception e){}
Balance-=amount;
System.out.println("withdr
aw completed...");
}
System.out.println("going to
deposit... Rs. "+amount);
Balance+=amount;
System.out.println("deposit completed... Balance
= "+Balance); notify();
}
class ThreadCommn
{
public static void
main(String
args[]) {
Customer
c=new
Customer();
new
Thread()
}.start();
new Thread(){
}.start();
}
OUTPUT:
going to withdraw...20000
Less balance; Balance = Rs.
10000 Waiting for deposit...
going to deposit... Rs. 15000
deposit completed... Balance =
25000 withdraw completed...
WRAPPERS
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.
THE TABLE BELOW SHOWS THE PRIMITIVE TYPE AND THE EQUIVALENT WRAPPER CLASS:
Primitive Data Type Wrapper Class
Byte Byte
Short Short
Int Integer
Long Long
Float Float
Double Double
Boolean Boolean
Char Character
Example:
//Java Program to convert all primitives into its corresponding
//wrapper objects and vice-versa public class Wrapper
OUTPUT
---Printing
object
values---
Byte
object: 10
Short object: 20
Integer object: 30
Long object: 40
Float object: 50.0
Double
object:
60.0
Character
object: a
Boolean
object: true
---Printing primitive
values--- byte value:
10
short value: 20
int value: 30
long value: 40
float value: 50.0
double
value:
60.0
char
value:
a
boole
n
value:
true
3.14. AUTOBOXING
The automatic conversion of primitive data type into its corresponding
wrapper class is known as autoboxing, for example, byte to Byte, char to
Character, int to Integer, long to Long, float to Float, boolean to Boolean,
double to Double, and short to Short.
EXAMPLE:
public class
WrapperExample
1{ public static
void main(String
args[]){
//Convert
ing int
into
Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}
OUTPUT
20 20 20
3.14.1. UNBOXING
The automatic conversion of wrapper type into its corresponding primitive
type is known as unboxing. It is the reverse process of autoboxing.
EXAMPLE:
//Unboxing example
of Integer to int
public class
WrapperExample2
{
//Convertin
g Integer to
int Integer
a=new
Integer(3);
int i=a.intValue(); //converting Integer to int explicitly
int j=a; //unboxing, now compiler will write
a.intValue() internally System.out.println(a+" "+i+" "+j);
}
OUTPUT
3 3 3
UNIT - V GUI PROGRAMMING WITH SWING
Introduction
Java Swing tutorial is a part of Java Foundation Classes (JFC) that 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:
The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but
limited graphical interface. One reason for the limited nature of the AWT is that it translates its
various visual components into their corresponding, platform- specific equivalents or peers. This
means that the look and feel of a component is defined by the platform, not by java. Because the
AWT components use native code resources, they are referred to as heavy weight. The use of
native peers led to several problems. First, because of variations between operating systems, a
component might look, or even act, differently on different platforms. This variability threatened
java’s philosophy: write once, run anywhere. Second, the look and feel of each component was
fixed and could not be changed. Third, the use of heavyweight components caused some
frustrating restrictions. Due to these limitations Swing came and was integrated to java. Swing is
built on the AWT. Two key Swing features are: Swing components are light weight, Swing
supports a pluggable look and feel.
●The way that the component looks when rendered on the screen
Containers:
A component is an independent visual control, such as a push button. A container holds a group of
components. Furthermore in order for a component to be displayed it must be held with in a
container. Swing components are derived from JComponent class. Note that all component classes
begin with the letter J. For example a label is JLabel, a button is JButton etc. Swing defines two
types of containers. The first are top level containers: JFrame, JApplet, JWindow, and JDialog.
These containers do not inherit JComponent. They do, however inherit the AWT classes Container
and Component. Unlike Swing’s other components which are heavy weight, the top level containers
are heavy weight. The second type of containers are light weight inherit from JComponent.
Example- Jpanel.
Java Layout Managers
The Layout Managers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout managers.
There are the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
import java.awt.*;
import javax.swing.*;
{ JFrame;
Border()
f = new JFrame();
// creating buttons
fsetSize(300,300);
f.setVisible(true);
}
new Border();
OUTPUT:
Example of BorderLayout class: Using BorderLayout(int hgap, int vgap) constructor
The following example inserts horizontal and vertical gaps between buttons
using the parameterized constructor BorderLayout(int hgap, int gap)
FileName: BorderLayoutExample.java
JFrame jframe;
// constructor
BorderLayoutExample()
{// creating a aFrame jframe = new JFrame();
jframe.setVisible(true);}
// main method
public static void main(String argvs[]) {new BorderLayoutExample(); } }
Output:
The add() method of the JFrame class can work even when we do not specify the region. In
such a case, only the latest component added is shown in the frame, and all the components
added previously get discarded. The latest component covers the whole area. The following
example shows the same.
FileName: BorderLayoutWithoutRegionExample.java
//constructor
BorderLayoutWithoutRegionExample(){
jframe.setSize(300,300);
jframe.setVisible(true);
}// main method
{new BorderLayoutWithoutRegionExample();
}}
Output:
Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular
grid. One component is displayed in each rectangle.
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no
gaps between the components.
GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given
rows and columns along with given horizontal and vertical gaps.
The GridLayout() constructor creates only one row. The following example shows the usage of
the parameterless constructor.
FileName: GridLayoutExample.java
// import statements
import java.awt.*;
import javax.swing.*;
Public class
GridLayoutExample
{new GridLayoutExample();}
Output:
Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one
after another (in a flow). It is the default layout of the applet or panel.
\ields of FlowLayout class
FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the
given alignment and the given horizontal and vertical gap.
FileName: FlowLayoutExample.java
// import statements
import java.awt.*;
import javax.swing.*;
JFrame frameObj;
//constructor
FlowLayoutExample()
// main method
Output:
Java CardLayout
The Java 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.
Constructors of CardLayout Class
CardLayout(): creates a card layout with zero horizontal and vertical gap.
CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.
public void first(Container parent): is used to flip to the first card of the
given container.
public void last(Container parent): is used to flip to the last card of the
given container.
FileName: CardLayoutExample1.java
CardLayout crd;
// button variables to hold the references of buttons
JButton btn1, btn2, btn3;
Container cPane;
//construct or of the class
CardLayoutExample1()
{
cPane = getContentPane();
// Upon clicking the button, the next card of the container is shown
// after the last card, again, the first card of the container is shown upon
cliking crd.next(cPane);
}
// main method
public static void main(String argvs[])
OUTPUT:
Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along
their baseline.
Modifier and Type Field Description
protected layoutInfo o
GridBagLayoutInfo It is used to hold the layout information f the gridbag. r
protected static int MAXGRIDSIZE No longer in use just for backward compatibility d
protected static int MINSIZE It is smallest grid that can be laid out by the grid bag e
layout.
protected static int PREFERREDSIZ It is preferred grid size that can be laid o by the grid u
E bag layout. t
protected GridBagLayoutInfo getLayoutInfo(Container parent, int This method is obsolete and supplied
sizeflag) for backwards compatibility.
protected GridBag GetLayoutInfo(Container parent, int This method is obsolete and
sizeflag)
LayoutInfo supplied for backwards compatibility.
Constructor
GridBagLayout(): The parameterless constructor is used to create a grid bag layout manager.
GridBagLayout Methods
Example 1
FileName: GridBagLayoutExample.java
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
Public GridBagLayoutExample() {
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints(); setLayout(grid);
setTitle("GridBag Layout Example"); GridBagLayout layout
= new GridBagLayout();
this.setLayout(layout);
gbc.fill=GridBagConstraints.HORIZONTAL; gbc.gridx= 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300,300); setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE); } }
OUTPUT:
But, the modern approach for event processing is based on the Delegation Model. It defines a
standard and compatible mechanism to generate and process events. 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. The UI elements are able to delegate
the processing of an event to a separate function.
The key advantage of the Delegation Event Model is that the application logic is completely
separated from the interface logic.In this model, the listener must be connected with a source to
receive the event notifications. Thus, the events will only be received by the listeners who wish to
receive them. So, this approach is more convenient than the inheritance-based event model (in Java
1.0).
In the older model, an event was propagated up the containment until a component was handled. This
needed components to receive events that were not processed, and it took lots of time. The
Delegation Event model overcame this issue.
Basically, an Event Model is based on the following three components:
o Events
Events Sources
Events
Listener 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.
The Events may also occur that may be not related to user interaction, such as a timer expires,
counter exceeded, system failures, or a task is completed, etc. We can define events for any of the
applied actions.
Event Sources
A source is an object that causes and generates an event. It generates an event when the internal state
of the object is changed. The sources are allowed to generate several different types of events.
A source must register a listener to receive notifications for a specific event. Each event contains its
registration method. Below is an example:
1. public void addTypeListener (TypeListener e1)
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. In few cases, the event notification will only be sent
to listeners that register to receive them.
Some listeners allow only one listener to register. Below is an example:
From the above syntax, the Type is the name of the event, and e2 is the event listener's reference.
When the specified event occurs, it will be notified to the registered listener. This process is known
as unicasting events.
A source should contain a method that unregisters a specific type of event from the listener if not
needed. Below is an example of the method that will remove the event from the listener.
1. public void removeTypeListener(TypeListener e2?)
From the above syntax, the Type is an event name, and e2 is the reference of the listener. For
example, to remove the keyboard listener, the removeKeyListener() method will be called.
The source provides the methods to add or remove listeners that generate the events. For example,
the Component class contains the methods to operate on the different types of events, such as adding
or removing them from the listener.
Event Listeners
An event listener is an object that is invoked when an event triggers. The listeners require two things;
first, it must be registered with a source; however, it can be registered with several resources to
receive notification about the events. Second, it must implement the methods to receive and process
the received notifications.
The methods that deal with the events are defined in a set of interfaces. These interfaces can be
found in the java.awt.event package.
For example, the MouseMotionListener interface provides two methods when the mouse is dragged
and moved. Any object can receive and process these events if it implements the
MouseMotionListener interface.
Types of Events
THE FOREGROUND EVENTS:THE FOREGROUND EVENTS ARE THOSE EVENTS THAT REQUIRE DIRECT INTERACTION OF THE
USER. THESE TYPES OF EVENTS ARE GENERATED AS A RESULT OF USER INTERACTION WITH THE GUI COMPONENT. FOR
EXAMPLE, CLICKING ON A BUTTON, MOUSE MOVEMENT, PRESSING A KEYBOARD KEY, SELECTING AN OPTION FROM THE LIST,
ETC.
The Background events are those events that result from the interaction of the end-user. For example,
an Operating system interrupts system failure (Hardware or Software).
To handle these events, we need an event handling mechanism that provides control over the events
and responses.
Handling Mouse Events
Mouse events occur with mouse movements in forms and controls. Following are the various mouse
events related with a Control class −
MouseDown − it occurs when a mouse button is pressed
MouseEnter − it occurs when the mouse pointer enters the control
MouseHover − it occurs when the mouse pointer hovers over the control
MouseLeave − it occurs when the mouse pointer leaves the control
MouseMove − it occurs when the mouse pointer moves over the control
MouseUp − it occurs when the mouse pointer is over the control and the mouse buttonis released
MouseWheel − it occurs when the mouse wheel moves and the control has focus
The event handlers of the mouse events get an argument of type MouseEventArgs.
The MouseEventArgs object is used for handling mouse events. It has the following properties −
Buttons − indicates the mouse button pressed
Clicks − indicates the number of clicks
Delta − indicates the number of detents the mouse wheel rotated
X − indicates the x-coordinate of mouse click
Y − indicates the y-coordinate of mouse click
Example
Following is an example, which shows how to handle mouse events.
Take the following steps
−Add three labels, three text boxes and a button control in the form.
Change the text properties of the labels to - Customer ID, Name and Address, respectively.
Change the name properties of the text boxes to txtID, txtName and txtAddress, respectively.
Change the text property of the button to 'Submit'.
Add the following code in the code editor window − Public Class
Form1
Private Sub Form1_Load(sender As Object, e As EventArgs)
Handles MyBase.Load ' Set the caption bar text of the form.
Me.Text = "tutorialspont.com" End Sub
Private Sub txtID_MouseEnter(sender As Object, e As EventArgs)_ Handles
txtID.MouseEnter
'code for handling mouse enter on ID textbox txtID.BackColor
= Color.CornflowerBlue txtID.ForeColor = Color.White
End Sub
Private Sub txtID_MouseLeave(sender As Object, e As EventArgs) _ Handles txtID.MouseLeave
'code for handling mouse leave on ID textbox txtID.BackColor = Color.White txtID.ForeColor =
Color.Blue
End Sub
Private Sub txtName_MouseEnter(sender As Object, e As EventArgs) _ Handles
txtName.MouseEnter
'code for handling mouse enter on Name textbox
txtName.BackColor = Color.CornflowerBlue
txtName.ForeColor = Color.White
End Sub
Private Sub txtName_MouseLeave(sender As Object, e As EventArgs) _ Handles
txtName.MouseLeave
'code for handling mouse leave on Name textbox
txtName.BackColor = Color.White txtName.ForeColor =
Color.Blue
End Sub
Try to enter text in the text boxes and check the mouse events −
Handling Keyboard Events
Following are the various keyboard events related with a Control class −
● KeyDown − occurs when a key is pressed down and the control has focus
● KeyPress − occurs when a key is pressed and the control has focus
● KeyUp − occurs when a key is released while the control has focus
The event handlers of the KeyDown and KeyUp events get aargument
of type KeyEventArgs. This object has the following properties −
● Alt − it indicates whether the ALT key is pressed
● Control − it indicates whether the CTRL key is pressed
● Handled − it indicates whether the event is handled
● KeyCode − stores the keyboard code for the event
● KeyData − stores the keyboard data for the event
● KeyValue − stores the keyboard value for the event
● Modifiers − it indicates which modifier keys (Ctrl, Shift, and/or Alt) are pressed
● Shift − it indicates if the Shift key is pressed
The event handlers of the KeyDown and KeyUp events get an
argument of type KeyEventArgs. This object has the following properties −
● Handled − indicates if the KeyPress event is handled
● KeyChar − stores the character corresponding to the key pressed
Example
Let us continue with the previous example to show how to handle keyboard events.
The code will verify that the user enters some numbers for his customer ID and age.
● Add a label with text Property as 'Age' and add a corresponding text box
named txtAge.
● Add the following codes for handling the KeyUP events of the text
box txtID. Private Sub txtID_KeyUP(sender As Object, e As KeyEventArgs)
_
Handles txtID.KeyUp
If you leave the text for age or ID as blank or enter some non-numeric data, it gives a warning
message box and clears the respective text –
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces
. If you inherit the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.
Pros of using Adapter classes:
It assists the unrelated classes to work combinedly.
. The Adapter classes with their corresponding listener interfaces are given below. java.awt.event Adapter
classes
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
DragTargetAdapter DragTargetListener
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
ADAPTEREXAMPLE.JAVA
import java.awt.event.*;
// object of
Frame
Frame f;
// class
constructor
AdapterExa
mple() {
});
// main method
public static void main(String[] args) {
new AdapterExample();
}
OUTPUT:
Java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place to be more readable and
maintainable.Additionally, it can access all the members of the outer class, including private data
members and methods.
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
There are three advantages of inner classes in Java. They are as follows:
Nested classes represent a particular type of relationship that is it can access all the members (data
members and methods) of the outer class, including private.
Nested classes are used to develop more readable and maintainable code because it logically
group classes and interfaces in one place only.
In simple words, a class that has no name is known as an anonymous inner class in Java. It should be
used if you have to override a method of class or interface. Java Anonymous inner class can be
created in two ways:
2. Interface
TESTANONYMOUSINNER.JAVA
abstract class Person{
class TestAnonymousInner{
p.eat();
}
OUTPUT:
nice fruits
A Simple Swing Application, Applets
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.
Advantage of Applet
There are many advantages of applet. They are as follows:
It works at client side so less response time.
Secured
It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os
etc.
Drawback of Applet
Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the
Component.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is used to
start the Applet.
1. public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.
2. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
To execute the applet by html file, create an applet and compile it. After that create an html file and
place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
Updated: 2021-03-08
An applet is a Java™ program designed to be included in an HTML Web document. You can
write your Java applet and include it in an HTML page, much in the same way an image is included.
When you use a Java-enabled browser to view an HTML page that contains an applet, the applet's
code is transferred to your system and is run by the browser's Java virtual machine.
The HTML document contains tags, which specify the name of the Java applet and its Uniform
Resource Locator (URL). The URL is the location at which the applet bytecodes reside on the
Internet. When an HTML document containing a Java applet tag is displayed, a Java-enabled Web
browser downloads the Java bytecodes from the Internet and uses the Java virtual machine to
process the code from within the Web document. These Java applets are what enable Web pages to
contain animated graphics or interactive content.
You can also write a Java application that does not require the use of a Web browser.
For more information, see Writing Applets, Sun Microsystems' tutorial for Java applets. It includes
an overview of applets, directions for writing applets, and some common applet problems.
Applications are stand-alone programs that do not require the use of a browser. Java applications
run by starting the Java interpreter from the command line and by specifying the file that contains
the compiled application. Applications usually reside on the system on which they are deployed.
Applications access resources on the system, and are restricted by the Java security model.
Parameters passed to an applet
Steps to accomplish this task -:
● To pass the parameters to the Applet we need to use the param attribute of <applet> tag.
● To retrieve a parameter's value, we need to use the getParameter()
method of Applet class.
● Method takes a String argument name, which represents the name of the
parameter which was specified with the param attribute in the <applet> tag.
● Method returns the value of the name parameter(if it was defined) else null is returned.
import java.awt.*;
/*
</applet>
*/
{String name; String age; String sport; String food; String fruit;
String destination;
g.drawString("Reading parameters passed to this applet -", 20, 20); g.drawString("Name -" + name, 20, 40);
g.drawString("Age -" + age, 20, 60); g.drawString("Favorite fruit -" + fruit, 20,
80); g.drawString("Favorite food -" + food, 20, 100); g.drawString("Favorite
destination -" + name, 20, 120); g.drawString("Favorite sport -" + sport, 20,
140);
OUTPUT
In order to run our applet using the appletviewer, type the following command at the command
prompt-
In the above example, we have created all the controls in init() method because it is invoked
only once.
myapplet.html
<html>
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
</html>
Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of MouseMotionListener.
}
public void mouseDragged(MouseEvent me){ Graphics
g=getGraphics(); g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5);
}
In the above example, getX() and getY() method of MouseEvent is used to get the
current x-axis and y getGraphics() method of Component class returns the object of Graphics.
myapplet.html
<html>
<body>
<applet code="MouseDrag.class" width="300" height="300">
</applet>
</body>
</html>
A Paint example
// Paint lines to a panel. import
java.awt.Graphics; import java.awt.Insets;
// Construct a panel.
PaintPanel() {// w w w . d e m o2 s . c o m
}
// Get the height and width of the component. int height = getHeight();
int width = getWidth();
ins = getInsets();
x = width - ins.left;
y = height - ins.bottom; x2 = width -
ins.left;
y2 = height - ins.bottom;
// Draw the line.
jfrm.setVisible(true);
}
new Main();
});
Java JLabel
The object of JLabel 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 an application but a user cannot edit it directly. It
inherits JComponent class.
JLabel class declaration
JLabel Example
import javax.swing.*;
class LabelExample
Java 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.
JButton class declaration
Let's see the declaration for javax.swing.JButton class.
public class JButton extends AbstractButton implements Accessible Java JButton Example
import javax.swing.*;
JToggleButton Example
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
new JToggleButtonExample();
}
if (button.isSelected()) button.setText("OFF");
else
button.setText("ON");
}
Output
Java 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.
JCheckBox class declaration
Let's see the declaration for javax.swing.JCheckBox class.
public class JCheckBox extends JToggleButton implements Accessible Java
JCheckBox Example
import javax.swing.*;
public class CheckBoxExample
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example"); JCheckBox
checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50); f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
{new CheckBoxExample();
}}
Output:
Next →← Prev
Java 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.
JRadioButton Example
import javax.swing.*;
new RadioButtonExample();
}
Output:
SWING JTABBEDPANE :
We can see the tabbed pane in windows operating by opening the system properties like below.
Java 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.
JScrollPane Example
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
javax.swing.SwingUtilities.invokeLater(new Runnable() {
});
}
OUTPUT
Java JList
The object of JList class represents a list of text items. The list of text items can be set up so that
the user can choose either one item or multiple items. It inherits JComponent class.
JList class declaration
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4"); JList<String> list =
new JList<>(l1); list.setBounds(100,100, 75,75);
f.add(list); f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
new ListExample();
}}
Output:
Java JComboBox
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 JComponent class.
JComboBox class declaration
Let's see the declaration for javax.swing.JComboBox class.
public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, Action
ComboBoxExample(){
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20); f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
new ComboBoxExample();
}
Output:
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must
belong to the JMenuItem or any of its subclass.
class declaration
public class JMenu extends JMenuItem implements MenuElement, Accessible JMenuItem
class declaration
class MenuExample
new MenuExample();
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
}}
Output:
Java 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. JDialog class
declaration
Output: