Unit I
Unit I
Unit I
1
UNIT I
2
Need for OOP Paradigm
Java was created by a team lead by James Gosling in 1995 for Sun
Microsystems
Compiler
5
The Java platform
●
The compiled code is independent of the
architecture of the computer.
●
The price to pay is a slower execution.
Linux
Compiler
Interpreter (JVM)
6
Data Types
A data type defines the type or/and behavior of a
data, it tells to the compiler about the type of data
which is going to be stored and the compiler reserves
the fixed number of bytes for that particular
variable/constant.
(4 bytes)
(1 byte)
(1 byte) (2 bytes)
(2 bytes) (8 bytes)
(4 bytes)
(8 bytes)
Java Primitive Data Types
Data Characteristics Range
Type
byte 8 bit signed integer -128 to 127
Examples:
int
while
for
break
class
static
final etc
Identifiers in Java
Identifiers are used for class names, method names, and variable
names. In Java, there are several points to remember about
identifiers
byte(1)---->short(2)---->int (4)---->long(8)----->float(4)----->double(8)
^
|
|
char(2)
Example:
Examples:
class Test
class Test
{
{
public static void
public static void main(String[]
main(String[] args)
args)
{
{
char ch = 'a';
byte b = 10;
int i;
int i;
i = ch;//---> 2 byte
i = b;//---> 1 byte into
into 4 bytes
4 bytes
System.out.println(ch);//a
System.out.println(b);//10
System.out.println(i);//97
System.out.println(i);//10
}
}
}}
}
Example:
class Test
{
public static void main(String[] args)
{
int i=10;
boolean b;
b = i;
}
}
Output:
Test.java:7: error: incompatible types: int cannot be converted to boolean
b = i;
^
1 error
Explicit casting:
1. Manual conversion of higher data type into lower data type is called as explicit.
2. programmer is responsible to do this.
3. loss of information will be there.
4. manual conversion | narrowing | down casting.
5. diagram
byte(1)<----short(2)<----int(4)<----long(8)<-----float(4)<-----double(8)
|
char(2)
Syntax :
type variable=(new_type) variable;
Example:
double D=6.865;
int A=(int) D; // fractional part will not be considered
Note: Boolean type can not be type cast to any other type
class Conversion
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d; System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d; System.out.println ("d and b " + d + " " + b);
}
}
Output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
Example:
Output:
short value : 50
int value : 50
long value : 50
float value : 50.0
double value : 50.0
Variable Scope
• Scope determines the visibility of program elements with respect to other program
elements.
• Declare the variable before you use it
• In Java, scope is defined separately for classes and methods:
{
…
}
class Scope
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
Nested scope:
Cannot declare a variable to have the same name as one in an outer scope.
Output
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
output statements:
we can use output statements to print output on screen/console.
1. System.out.print() - print the info on the screen and control will be in the same
line
class Test
{
public static void main(String[] args)
{
System.out.print("Java\n"); // System.out.println("Java");
System.out.print("Python\n");
System.out.print("LINUX/UNIX");
}
}
Java
Python
LINUX/UNIX
Types of Variables
+ Addition 34 + 1 35
% Remainder 20 % 3 2
52
Integer Division
+, -, *, /, and %
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
53
Examples:
class Test
{
public static void main(String[] args)
{
System.out.println(5+2); //7
System.out.println(5-2); //3
System.out.println(5*2); //10
System.out.println(5/2); //2
System.out.println(5%2); //1
}
}
-------------------------------------------------------------------------------------------------------------------
-
class Test
{
public static void main(String[] args)
{
System.out.println(5/2);//2
System.out.println(5.0/2);//2.5
System.out.println(5/2.0);//2.5
System.out.println(5.0/2.0);//2.5
Assignment Operator(=)
Note: 1. Can not use more than one variable at left hand side of = operator.
Example: x + y=15
2. can not use literal or constant at the left hand side Example: 15=x
Compact Notation when same variable have to be used on both the sides of the
operator:
55
Assignment Operator(=)
class Test
L ----> only variable {
R ----> variable | constant | expressions public static void main(String[] args)
{
int a=4,b=1;
>> op1 >> op2 Shifts all bits in op1 right by the value of
op2
<< op1 << op2 Shifts all bits in op1 left by the value of
op2
Bit wise operators
Examples:
63
Increment and Decrement Operators, cont.
64
The conditional Operator
Ternary operator requires three operands (as opposed to
the unary’s single and the binary’s double operand
requirement)
Syntax :-
variable = expression1? expression2 :expression3;
Example:
We know that each class contains variables and methods. To refer to the variables of
class member operator is used.
Syntax:
classname . variablename;
objectname . variablename;
classname . mehtodname;
objectname . mehtodname;
Control Statements
One-way if Statements
Java supports two selection statements: if and switch. These statements allow you to
control the flow of your program’s execution based upon conditions known only during
run time.
if (i > 0) { if (i > 0)
System.out.println("i is positive"); Equivalent System.out.println("i is positive");
}
(a) (b)
Note:
o The Boolean expression is enclosed in parentheses for all forms of the if
statement. Thus, the outer parentheses in the previous if statements are
required.
if (radius >= 0)
{
area = radius * radius * 3.14159;
(a) (b)
Multi-Way if-else Statements
Trace if-else statement
animation
This error often occurs when you use the next-line block style.
TIP
if (number % 2 == 0) Equivalent
even = true; boolean even
else = number % 2 == 0;
even = false;
(a) (b)
CAUTION
Equivalent if (even)
if (even == true)
System.out.println( System.out.println(
"It is even."); "It is even.");
(a) (b)
Switch Statements
switch(control variable)
{
case value1:
//Statements Sequence
break;
case value2:
//Statements Sequence
break;
.
.
case value N:
//Statements Sequence
break;
default:
//Statements Sequence
}
Switch Statements
• The expression must be of type byte, short, int, or char; each of the
values specified in the case statements must be of a type compatible
with the expression
• Each case value must be a unique literal. Duplicate case values are not
allowed.
• Note that this statement does not allow less than, greater than, etc.
ONLY the equality operator (==) is used with a switch statement.
• The value of the expression is compared with each of the literal values
in the case statements. If a match is found, the code sequence
following that case statement is executed.
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
// In a switch, break statements are optional.
class MissingBreak
{
public static void main(String args[])
{
for(int i=0; i<12;i++)
switch(i)
{
case 0:
case 1:
case 2:
case 3:
case 4: System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9: System.out.println("i is less than 10");
break;
default: System.out.println("i is 10 or more");
}}}
switch Statements
switch (status)
{
case 0:
compute taxes for single filers;
break;
case 1:
compute taxes for married file jointly;
break;
case 2:
compute taxes for married file separately;
break;
case 3:
compute taxes for head of household;
break;
default:
System.out.println("Errors: invalid status");
System.exit(1);
}
switch Statement Flow Chart
switch Statement Rules
The switch-expression
must yield a value of char, switch (switch-expression)
byte, short, or int type and {
must always be enclosed
in parentheses. case value1: statement(s)1;
break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the …
value of the switch-expression. case valueN: statement(s)N;
The resulting statements in the break;
case statement are executed when default: statement(s)-for-default;
the value in the case statement }
matches the value of the switch-
expression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.
switch Statement Rules
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
100
times …
…
…
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
Introducing while Loops(Entry Controlled)
int count = 0;
while (count < 100)
{
System.out.println("Welcome to Java");
count++;
}
Note
• Make sure that the loop-continuation-condition eventually
becomes false so that the program will terminate.
• A common programming error involves infinite loops.
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
System.out.println("Welcome to Java!");
Statement(s); count++;
} }
animation
Trace while Loop
Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop, cont.
(count < 2) is true
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop, cont.
Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop, cont.
Increase count by 1
int count = 0; count is 1 now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop, cont.
(count < 2) is still true since count
int count = 0; is 1
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop, cont.
Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop, cont.
Increase count by 1
int count = 0; count is 2 now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop, cont.
(count < 2) is false since count is 2
int count = 0; now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop
The loop exits. Execute the next
int count = 0; statement after the loop.
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Example
Syntax
do {
statement;
statement;
} while (condition);
statement
A for loop in (a) in the following figure can generally be converted into the
following while loop in (b) except in certain special cases (see Review Question
3.19 for one of them):
for (initial-action; initial-action;
loop-continuation-condition; Equivalent while (loop-continuation-condition) {
action-after-each-iteration) { // Loop body;
// Loop body; action-after-each-iteration;
} }
(a) (b)
Jumping Statements:
• Java supports three jump statements: break, continue, and return.
These statements transfer control to another part of your program.
class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<=100;i++)
If(i==10)
break;
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
output:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.
Using break as a Form of Goto:
• Java does not have a goto statement because it provides a way to branch
in an arbitrary and unstructured manner.
• Most often, label is the name of a label that identifies a block of code.
This can be a stand-alone block of code but it can also be a block that is
the target of another statement.
• When this form of break executes, control is transferred out of the named
block. The labeled block must enclose the break statement, but it does
not need to be the immediately enclosing block.
• To name a block, put a label at the start of it. A label is any valid Java
identifier followed by a colon. Once you have labeled a block, you can
then use this label as the target of a break statement.
// Using break as a civilized form of goto.
class Break
{
public static void main(String args[])
{
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
} // Third
System.out.println("This won't execute");
} // Second
System.out.println("This is after second block.");
} //First
}
}
OUTPUT:
Before the break.
This is after second block.
// Using break to exit from nested loops
class BreakLoop4
{
public static void main(String args[])
{
outer: for(int i=0; i<3;i++)
{
System.out.print("Pass " + i + ": ");
for(int j=0; j<100;j++)
{
if(j == 10)
break outer; // exit both loops
System.out.print(j + " ");
}
System.out.println("This will not print");
} //outer
System.out.println("Loops complete.");
}
}
Output:
Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.
Using continue:
• Continue is used inside a loop to repeat the next iteration of the loop.
• When continue is executed subsequent statements in the loop are not executed
and control of execution goes back to the next iteration of the loop
Syntax: continue;
// Demonstrate continue.
class DemoContinue
{
public static void main(String args[])
{
for(int i=10; i>=1;i--)
{
if (i>5) continue;
System.out.println(i+" ");
}
}
}
Output: 5 4 3 2 1
Note: As with the break statement, continue may specify a label to describe which
enclosing loop to continue.
Return:
• The last control statement is return. The return statement is used to explicitly
return from a method. That is, it causes program control to transfer back to
the caller of the method.
• At any time in a method the return statement can be used to cause execution
to branch back to the caller of the method.
• Thus, the return statement immediately terminates the method in which it is
executed.
public class Demo
{
public static void main(String args[])
{
int res=DemoReturn.myMethod(10);
System.out.println("Result is="+res);
}
}
Array
s
• An array is a group of liked-typed variables referred to
by a common name
• Individual variables accessed by their index.
• Arrays are:
1) declared
2) created
3) initialized
4) used
• Also, arrays can have one or several dimensions.
Array Declaration
• Array declaration involves:
1) declaring an array identifier
2) declaring the number of dimensions
3) declaring the data type of the array elements
class Array
{
public static void main(String args[])
{
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;
System.out.println("April has " + month_days[3] + " days.");
}
}
// An improved version of the previous program.
for(i=0; i<4;i++)
{
for(j=0; j<5;j++)
System.out.Print(twoD[i][j]+ ””);
System.out.println();
}
}
}
Class
• A class is a user defined datatype to define the properties. A class
contains variables and methods that operate on those variables.
• In fact, Objects are variables of the type class. Once a class has been
defined, we can create any number of objects belonging to that
class.
• Classes are data types based on which objects are created. Objects
with similar properties and methods are grouped together to form a
Class. Thus a Class represents a set of individual objects
• A class is thus a collection of objects of similar type .
for example: mango, apple, and orange are members of the class
fruit . ex: fruit mango; will create an object mango belonging to the
class fruit.
Syntax:
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}
Class:
A class is declared by use of the class keyword. Class name is the name of
the class we are declaring.
The data, or variables, defined within a class are called instance variables.
The code is contained within methods. Collectively methods and variables
defined inside a class are called members of the class.
Example:
class Box
{
double width;
double height;
double depth;
}
Where new data type is Box.
Creating an object:
Instance is an Object of a class which is an entity with its own attribute values and
methods.
class_name object_name=new class_name()
Example:
NULL
Box mybox ; Height
mybox== new Box(); Width
mybox Breadth
(OR)
Box mybox = new Box(); // create a Box object called mybox
-> Each time when an instance of a class is created, you are creating an
object that contains its own copy of each instance variable defined by the
class.
-> Thus, every Box object will contain its own copies of the instance variables
width, height, and depth.
-> To access these variables, you will use the dot (.) operator. The dot operator links
the name of the object with the name of an instance variable.
Example:
class Box
{
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();
double vol;
class Box
{
double width;
double height;
double depth;
}
class BoxDemo2
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
} Volume is 3000.0 Volume is 162.0
Methods:
classes usually consist of two things: instance variables and methods
We can add number of methods to class. This is the general form of a method:
type name(parameter-list)
{
// body of method
}
• Type specifies the type of data returned by the method. If the method does not return a
value, its return type must be void.
• If a method return type is other than void, then method return value to calling function by
using below statement.
return value;
Adding a Method to the Box Class: class BoxDemo3
{
// This program includes a method inside public static void main(String args[])
the box class. {
Box mybox1 = new Box();
class Box Box mybox2 = new Box();
{
double width; // assign values to mybox1's instance variables
double height; mybox1.width = 10;
double depth; mybox1.height = 20;
mybox1.depth = 15;
// display volume of a box
void volume() /* assign different values to mybox2's instance
{ variables */
System.out.print("Volume is "); mybox2.width = 3;
System.out.println(width * height * depth); mybox2.height = 6;
} mybox2.depth = 9;
}
// display volume of first box
mybox1.volume();
After the statements inside volume( ) have executed, control is returned to the calling
routine, and execution resumes with the line of code following the call.
Returning a Value:
what if another part of your program wanted to know the volume of a box, but not
display its value?
So it is better to implement volume( ) to compute the volume of the box and return the
result to the caller.
class Box
{ /* assign different values to mybox2's instance
double width; variables */
double height; mybox2.width = 3;
double depth; mybox2.height = 6;
mybox2.depth = 9;
// compute and return volume
double volume() Call 1
{ // get volume of first box
return width * height * depth; Return 1 vol = mybox1.volume();
} System.out.println("Volume is " + vol);
} Call 2
In the future, you can change the behavior of a method, but you can’t
change the behavior of an exposed instance variable.
// This program uses a parameterized class BoxDemo5
method. {
class Box public static void main(String args[])
{ {
double width; Box mybox1 = new Box();
double height; Box mybox2 = new Box();
double depth; double vol;
Box()
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
double volume()
{
return width * height * depth;
}
}
class BoxDemo6
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(); parentheses are needed after the
Box mybox2 = new Box(); class name because the constructor
for the class is being called.
double vol;
class Box
{
double width;
double height;
double depth;
double volume()
{
return width * height * depth;
}
class BoxDemo7
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
-> what if you want to be able to initialize a cube by specifying only one value that
would be used for all three dimensions?
-> What if you simply wanted a box and did not care (or know) what its initial dimensions
were?. As the Box class is currently written, these other options are not available to you.
Solution : simply overload the Box constructor so that it handles the situations just described
-> A class can have multiple constructors, all the constructors have the same name as
corresponding to the class name that they differ only in terms of their number of arguments
and order.
class Box
{
double width;
double height;
double depth;
In the above example, parameters (formal arguments) and instance variables are same.
So, we are using this keyword to distinguish local variable and instance variable.
Recursion:
Recursion is the process of defining something in terms of itself. A method that calls itself is
said to be recursive.
• When a method calls itself, new local variables and parameters are allocated storage
on the stack, and the method code is executed with these new variables from the start.
• As each recursive call returns, the old local variables and parameters are removed from
the stack, and execution resumes at the point of the call inside the method
• Recursive versions of programs execute a bit more slowly than the iterative equivalent
because of the added overhead of the additional function calls.
• The main advantage to recursive methods is that they can be used to create clearer
and simpler versions of several algorithms than can their iterative relatives
• Private fields or methods for a class only visible within that class.
Private members can not be inherited by subclass or they are not
accessible in subclasses.
• Protected members of a class are visible within the class, subclasses
and also within all classes that are in the same package as that class.
protected applies only when inheritance is involved.
/* This program demonstrates the difference between public and private. */
class Test
{
int a; // default access
public int b; // public access private
int c; // private access
// methods to access c
void setc(int i)
{
// set c's value
c = i;
}
int getc()
{
// get c's value
return c;
}
}
class AccessTest
{
public static void main(String args[])
{
Test ob = new Test();
Example:
days – {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY}
directions – {NORTH, SOUTH, EAST, and WEST)
season- {SPRING, SUMMER, WINTER, and AUTUMN or FALL}
colors – {RED, YELLOW, BLUE, GREEN, WHITE, and BLACK}
//main method
public static void main(String[] args)
{
To get the enum for a given integer, we simply have to call the valueOf method
Season s1=s
String Handling
• String is probably the most commonly used class in Java's class library. The
obvious reason for this is that strings are a very important part of
programming.
• The first thing to understand about strings is that every string you create
is actually an object of type String. Even string constants are actually
String objects.
• For example, in the statement System.out.println("This is a String, too");
the string "This is a String, too" is a String constant
Creating Strings:
String s;
S=“Hello”;
(or)
String s=“Hello”;
• The String class contains several methods that you can use. Here are a few.
String trim( )
Ex: String s = " Hello World ".trim();
• The startsWith( ) method determines whether a given String begins with a specified
string. Conversely, endsWith( ) determines whether the String in question ends with a
specified string.
boolean startsWith(String str)
boolean endsWith(String str)
WAP to design a String class that performs String methods (Equal, Reverse the string, and change
the case etc).
package project1;
public class StringDemo
{
public static void main(String[] args)
{
String str = "This is some sample String with some words that have been repeated
some times";
System.out.println("Total no. of characters : " + str.length());
System.out.println("To Upper Case : " + str.toUpperCase());
System.out.println("To Lower Case : " + str.toLowerCase());
System.out.println("Original String : " + str);
System.out.println(str.substring(8));
System.out.println(str.substring(8,19));
System.out.println(str.indexOf("some"));
String s = " " + str + " ";
System.out.println(s);
System.out.println("[" + s.trim() + "]");
System.out.println(str.replace("s","$$##"));
String sh = "parth is a good boy";
System.out.println(sh + " -> " + new StringBuffer(sh).reverse());
}
}
Garbage Collection
Objects are dynamically allocated by using the new operator, such objects are
destroyed automatically and their memory is released for later reallocation in
java. This techniques is called garbage collection.
• Finalize() is the method of Object class. This method is called just before an
object is garbage collected. finalize() method overrides to dispose system
resources, perform clean-up activities and minimize memory leaks.
Garbage Collection Example:
package sec4java;
Syntax: public class JavafinalizeExample1
{
protected void finalize() public static void main(String args[])
{ {
//finalization code JavafinalizeExample1 obj=new JavafinalizeExample1();
} //obj=null;
System.gc();
System.out.println("end of garbage collection");
}
//override
protected void finalize()
{
System.out.println("finalize method called");
}
Output:
end of garbage collection
finalize method called