Unit 1
Unit 1
THROUGH JAVA
A.Sree Lakshmi
Professor & HOD,
Dept of CSE
Course Outcomes (COs):
After completion of the course, student would be able to
CO1: Use concepts of OOPs such as data abstraction, inheritance, polymorphism,
encapsulation and method overloading principles in structuring computer
applications for solving problems.
CO2: Identify classes, objects, members of a class and relationships among them
needed for a specific problem.
CO3: Use Java Collection of Application Programming Interface (API) as well as
the Java standard class library with necessary exception handling mechanisms in
constructing computer applications.
CO4: Develop java programs using multi-threading, files and database
concepts and their connectivity.
CO5: Design and develop Graphical User Interface applications using Abstract
Window Toolkit (AWT), Swings and Applets.
History of Java
3
Year Progress
2. Secure
3. Object Oriented
4. Robust
5. Platform Independent
6. Multi Threaded
7. Architectural Neutral
8. Portable
9. High Performance
6
Java Features
b)Exception handling concept: The concept of exception handling enables Java to capture
a series of errors that helps developers to get rid of risk of crashing the system.
c) Byte code is another thing that makes Java more secure:-
Every time when a user compiles the Java program, the Java compiler creates a class file
with Byte code, which are tested by the JVM at the time of program execution for viruses
and other malicious files
d)Garbage collection mechanism:-
Garbage collection(gc()) mechanism aids more to the security measures of Java. It provides
a transparent storage allocation and recovering unutilized memory rather than deallocating
memory through manual action. It will help developers to ensure the integrity of the
program during its execution and avoids any JVM crash due to incorrect freeing of
memory.
7
Java Features
4) Robust:-Java makes an effort to eliminate error level codes by highlight mainly on compile
time error checking and runtime checking. But the main areas which Java improved were
Memory Management and mishandled Exceptions by introducing automatic Garbage
Collector and Exception Handling.
5) Platform Independent:- All programming languages such as C, C++ etc which are
compiled into platform specific machines. Java is guaranteed to be write-once, run-anywhere
language.
A Java program is compiled into byte code. This byte code is platform independent and can
be run on any machine, plus this byte code format also provide security. Any machine with Java
Runtime Environment can run Java Programs.
Java Features
6) Multi Threaded
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to
execute multiple threads at the same time, like While typing, grammatical errors are checked
along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer architecture,
hence a Java program is easy to interpret on any machine.
8) Portable
Java Byte code can be carried to any platform. Java code is compiled into intermediate format
(bytecode), which can be executed on any systems for which Java virtual machine is ported. That
means you can write a Java program once and run it on Windows, Mac, Linux or Solaris without
re-compiling. Thus the slogan “Write once, run anywhere” of Java.
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or C++.
9
But, Java enables high performance with the use of just-in-time compiler.
Interpreter Compiler
❖Classes
❖ Objects
❖ Abstraction
❖ Encapsulation
❖ Inheritance
❖Polymorphism
Procedure Oriented Programming/
Structured Programming
In structured programming , a complex programming is broken into sets of
smaller, understandable tasks, however the drawbacks of structured
programming soon became clear.
The data and task independently were too hard to maintain
Programmers were reinventing new solutions to old problems
As the length of the program increases , its complexity increases making
it difficult to maintain a very large program
The functions have unrestricted access to global data
They provide poor mapping to real world
Object Oriented Programming(OOP)
This provides a technique for managing huge complexity , achieving
reuse of software components and coupling data with the tasks that
manipulate data
OOP deals with things called objects.
Objects are just extremely functional way of organizing information.
In the complex real world we have objects which has some attributes
and behavior. WE deal with similar objects in OOP
Objects are defined by their unique identity, state and behavior.
The state of an object is identified by the value of its attributes and
behavior by methods
Object-Oriented Programming Concepts
Class:-
A class is a set of objects with similar properties (attributes), common
behavior (operations), and common link to other objects.
The complete set of data and code of an object can be made a user defined
data type with the help of class.
The objects are variable of type class. A class is a collection of objects of
similar type.
A class defines the structure and behavior that will be shared by a set of
objects. Once the class has been defined, we can make any number of objects
belonging to that class. Each object of a given class contains the structure and
behavior defined by the class.
The classification of objects into various classes is based on its properties
(States) and behavior (methods). The important thing about the class is to
identify the properties and procedures and applicability to its instances.
Object-Oriented Programming Concepts
Abstraction:-
Abstraction is a process where you show only “relevant” data and “hide”
unnecessary details of an object from the user.
It refers to the act of representing important description without including the
background details or explanations.
Ex: person driving a car need not know the internal working of the car
OOP Concepts
Encapsulation:-
Data Encapsulation means wrapping of data and functions into a single unit (i.e. class). It is
most useful feature of class.
It provides us the power to restrict anyone from directly altering the data. An access to the data
has to be through the methods of the class. This insulation of data from direct access by the
program is called as Data hiding. It prevents users from seeing the internal working of an object.
Java basic unit of encapsulation is class. The code and data that constitute a class are called
members of the class. Specifically the data defined by the class are referred to as members
variables or instance variables. The code that operates on that data is referred to as member
methods.
Benefits of Encapsulation
Improves program readability
Reduces maintenance
Lends reusability
Facilitates information hiding
Improves modularity
Makes coding easier
OOP Concepts
Inheritance: It is a way to adopt the characteristics of one class into another class,
called the child or derived class. When a class inherits another class, it has all the
properties of the base class and it adds some new properties of its own.
The principle of dividing a class into subclass is that each subclass shares common
characteristics with the class from where they are inherited or derived.
Inheritance can reduce the amount of coding by letting any derived class use the base
class’s functionality when it needs to, thus simplifying implementation of similar
classes and structures.
Benefits of inheritance:
1. Increased productivity
2. Reduced maintenance
3. Standardization
4. reusability
OOP Concepts
Polymorphism:
‘HAVING MANY FORMS is know as Polymorphism. It can be defined as same
thing being used in different forms. It refers to the ability of an object to respond
differently to the same message.
Behavior of an object can be varied depending on the message passed to it
without worrying about the way the kind of message was passed.
Object can exhibit different behaviors in different situations. The behavior
depends on the data types and number of parameters used in the operation.
Polymorphism is achieved in java using method overloading and method
overriding
Procedure Oriented Programming (POP) Object Oriented Programming (OOP)
1 Decompose the main problem in small parts called Decompose the main problem in small parts called
functions. objects.
2 Employs top-down approach for designing programs. Employs bottom-up approach for designing.
5 Appropriate & effective techniques are unavailable to Data security can be obtained using different access
secure the data. specifiers.
6 Modification of a completed program is very difficult Modifications are easy as objects stay independent to
and it may affect the whole program. declare and define.
7 In large programs, it is very difficult to find what data As data and functions stay close, it is easy to identify
has been used by which function. data.
9 Languages like C, FORTRAN, COBOL etc. use POP. Languages like C++, JAVA etc. use OOP.
Compiling the program
To compile a java program we execute the compiler javac, specifying the name of
the source file.
javac << java file name>>
ex: javac test.java
Javac compiler creates a class file that contains the byte code.(This byte code can
execute on any machine of any architecture and any platform)
To run the program , we use java interpreter called java
java <<class file that contains main method>> <<command line arguments if
required>>
ex: java test
java test sai // passing one command line argument
java test sai siva // passing two command line arguments
Note: If eclipse IDE is used all these steps are done internally by IDE itself. We need to
just click on run. We can specify command line arguments using Run Configurations.
Data types
24
Literals
A constant value in java is created by using a literal representation of it.
Ex: “my java prog”, 10, ‘s’, 16.5
Integer Literal: Any whole number is a integer literal. These are all decimal
numbers with base 10. There are other bases which can be used in integer
literals, octal(base 8) and hexadecimal (base 16). Octal values are denoted by
a leading zero. Hexadecimal constants are denoted with leading zero-x(0x, or
0X)
Examples:
❖ int i=5
❖ Int i= 012 // considers as octal and with value of 10
❖ Int i= 09 // error as 9 is out of range of octal( only 0-7)
❖ int i=0X11; // considers as hexadecimal with value of 17
❖ Int i=0XA1 ; // considers as hexadecimal with value of 161
Literals
When a integer literal value is assigned to byte or short variable , no
error is generated if the literal value is within the range of the target
type.
byte b=10;
byte b=128 // error as 128 is out of range of byte
short s=278;
By default, integer literals are of type int. If you want to specify a
long literal, append an l or an L. For example, 12 is an int, but 12Lis a
long
long l=1098765353545L
Literals
Floating-point literal:
By default double data type is considered for a decimal number with a
fractional component.
double d=10.5;
float f=10.5; // error as it is narrowing conversion from double literal
to // float variable
To specify a float literal, append an F or f to the constant. For example,
10.19F is of type float.
float f=10.5F
Literals
Boolean literals: literals true or false
boolean b=true;
Character literals: Uses unicode, expressed in single codes. Escape sequences
can also be used
char c=‘a’ //’a’ is char literal
char c=‘\n’
String literals:
String S=“hello”
String s1=“Hello \n World”
Character Escape sequences
Variables
Variables: Variables can be defined for all the data types and can be assigned with
appropriate literal. Variable name cannot start with a number:
Scope and Lifetime of Variables in Java:-
❖ The scope of a variable defines the section of the code in which the variable is visible. As
a general rule, variables that are defined within a block are not accessible outside that
block. The lifetime of a variable refers to how long the variable exists before it is
destroyed.
❖ Java allows variables to be declared within any block. A block defines scope.
❖ Java allows another category of scope called as class scope(---Will be dealt later---)
Type conversion and casting:-
Java Automatic Conversions: When one type of data is assigned to
another type of variable, an automatic type conversion takes place if
the following two conditions are met.
❖ The two types are compatible
❖ The destination type is larger than the source type
Automatic type conversion is called as Widening
Narrowing conversions can be done only by typecasting
(target-type) variable
Type conversion and casting:-Assigning a value of one type to a variable of another type is known
as Type Casting.
Eg:- int x = 10;
byte y = (byte)x;
Type casting is classified into two types
1. Widening Casting(Implicit)
2. Narrowing Casting(Explicitly done)
1. Widening Casting(Implicit) :-It is also called Automatic Type casting in this type the target type is
larger than the source type.
32
public class Testcasting1
{
public static void main(String[] args)
{
int i = 25;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}}
OUTPUT:-
java Testcasting1
Int value 25
Long value 25
Float value 25.0
33
2. Narrowing Casting(Explicitly done) :- larger type value to a variable of smaller type is called explicit type
casting.
byte b=50;
b=b*2; // error as b is promoted to int by default and cannot fit into byte
b=(byte) b*2 // need to explicitly type cast
Operators:- Operator in java is a symbol that is used to perform special operations. For example: +, -, *, / etc.
There are basically two types of Operators
1) Unary Operator
2)Binary Operator
1)Unary Operator:- This operator perform operation on single operand (Variable);
eg:-a++;
2) Binary Operator:- This operator perform operation on more than ne operands
Eg:- c=a+b;
36
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Shift operators
General form
Value<< num-bits
Value>> num-bits
Value>>> num-bits
Conditional Operator ( ? : )
Syntax:
variable x = (expression) ? value if true : value if false
Example:
System.out.print(ar[0]);
System.out.print(ar[1]);
System.out.print(ar[2]);
System.out.print(ar[3]);
}}
OUTPUT:-
C:\java Cmd Geethanjali College of Engineering
LOOPS
❖ while Loop
❖ do...while Loop
❖ for Loop
Conditional statements
❖ If statements
❖ Switch statements
❖ Break
❖ Continue
For each loop
Syntax:
for (type var : array)
{
statements using var;
}
Break with Label
public class LabelledBreak
{
public static void main(String args[])
{
loop2:
for(int i=0;i<5;i++)
for(int k=0;k<5;k++)
{
if(k==2) Output:
break loop2; i=0
System.out.println("i = "+i); k=0
System.out.println(“k = "+k); i=0
} k= 1
System.out.println("Out of the loop"); Out of the loop
} //main method ends
} //class ends
Continue with Label
public class LabelledContinue
{
public static void main(String args[]) Output:
{ i=0
loop2: k=0
for(int i=0;i<3;i++) i=0
for(int k=0;k<3;k++) k=1
{ i=1
if(k==2) k=0
continue loop2; i=1
System.out.println("i = "+i); k=1
System.out.println(“k = “+k); i=2
} k=0
System.out.println("Out of the loop"); i=2
} //main method ends k=1
} //class ends Out of the loop
If-else Statement:- if statement is used to test the condition. It checks boolean condition: true or false. There
are various types of if statement in java.
1)if statement 2) if-else statement 3) nested if statement
IF Statement:- The Java if statement tests the condition.
It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
Example:-
class Con1
{
public static void main(String args[])
{
int n;
n=10;
if(n%5==0)
{
System.out.println("the number "+n+"is divided by 5");
}
51
}}
IF-else Statement:- The Java if-else statement also tests the condition.
It executes the if block if condition is true otherwise else block is
executed.
Syntax:
if(condition){ //code if condition is true }
else{ //code if condition is false }
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Note: For versions of Java prior to JDK 7 , the expression controlling the switch must be of type byte,
short, int, char or an enumeration . From JKD 7 , expression can also be of type String.
55
56
Arrays:- “An array is a Indexed collection of fixed number of homogenous data elements”.
An array can be either primitive or reference type. It gets memory in heap area. Index of array starts from zero
to size-1.
Example :
int[ ] a ; Declares an array variable but no array actually exists. It
int b[ ] ; is set to null i.e. An array with no value
Initialization of Array:-
Initialization of Array:-
int[ ][ ] arr = new int[size-m][size-n];
60
class Twoarray
{
public static void main(String args[]){
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<4;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}}
OUTPUT:-
C:\praveen>java Twoarray
1234
61
11 12 14 15
14 24 34 44
Irregular arrays
When defining an multidimensional array we need to specify the memory for
the first(leftmost dimension). The remaining dimensions can be allocated
separately
int a[][]=new int[3][];
a[0]=new int[4];
a[1]=new int[4];
a[2]=new int[4];
We can also have different dimensions
int a[][]=new int[3][];
a[0]=new int[4];
a[1]=new int[3];
a[2]=new int[2];
int b[][]={{1,2,3,4},{5,6,7},8,9}};// array initialized with different dimensions
Assigning Array references
When one array reference variable is assigned to another , it does not cause a
copy of the array nor the contents of one array is copied to the other, but the
object that the variable refers to is changed. This is because arrays are
treated as objects in java.
int a[][]={{1,2,3},{4,5},{6,7},{7,3,5}}
System.out.println(a.length) // prints 4 as a has 4 rows
System.out.println(a[0].length) // prints 3 as row 0 has 3 cols
System.out.println(a[1].length) // prints 2 as row 1 has 2 cols
System.out.println(a[2].length) // prints 2 as row 2 has 2 cols
System.out.println(a[3].length) // prints 3 as row 3 has 3 cols
Enhanced for loop: for-each loop
Enhanced for loop (for-each) can be used to access each element sequentially
from a collection like array.
Syntax:
for(type itr-var:collection) statement block
❖ type specifies the type of the elements stored in the collection
❖ itr-var is the iteration variable that receives values from collection one at a
time from beginning to endexample
Example 1: to find sum of all elements in array
int[] num={1,2,3,4,5,6,7,8,9}
int sum=0
for(int x:nums) sum+=x;
Example2:
double [] num={1.5,2.6,3.8,4.2,5.7,6.0}
for(float x:nums) System.out.println(x);
Assignment
Write a program to perform linear search and display the element position
Write a program to perform binary search and display the element position
Write a program to read two matrices and perform matrix addition
67
OUTPUT:-
C:\java Matadd
enter no of rows matrix A
2
enter no of cols matrix A
2
enter no of rows matrix B
2
enter no of cols matrix B
2
enter elements in to matrix A
2 2 2 2
enter elements in to matrix B
22 2 2
sum matrix is:
4 4
4 4
68
Classes and Objects
Class:- A class is a collection of fields (data members) and methods (procedure or
function) that operate on that data.
(or)
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity.
A class in Java can contain:
fields
methods
constructors
blocks
nested class and interface
Syntax to declare a class:
class ClassName [extends SuperClassName]
{
[fields declaration]
[methods declaration]
}
70
Classes and Objects
class <classname>>
{
//declare instance variables
<<type>> var1;
<<type>> var2;
// declare methods
<<return type>> method1(<<parameters>>)
{
// body of the method
}
<<return type>> method1(<<parameters>>)
{
// body of the method
}
}
Classes and Objects
Creating an object
<<classname>> <<obj var>>=new <<classname>>()
To access the members we use ‘.’ operator
Object.member
Classes and Objects
class Student class test
{ {
int sno; public static void main(String args[])
String name; {
void set(int r,String n) Student s1 = new Student();
{ Student s2 = new Student();
sno = r; s1.set(1201,“sai");
name = n; s2.set(1202,“siva");
} s1.display();
void display () s2.display();
{ }
System.out.println(sno+" "+name); }
}
}
class Rectangle Class Rectdemo
{ public static void main(String args[])
int length; {
int breadth; Rectangle r1=new Rectangle();
void setSize(int l,int b) r1.setSize(10,20);
{ r1.dispSize();
length=l; r1.printArea();
breadth=b; Rectangle r2=new Rectangle();
} r2.setSize(15,25);
void dispSize() r2.dispSize();
{ r2.printArea();
System.out.println("Length of the rect="+ length); }
System.out.println("Breadth of the rect="+ breadth); }
}
void printArea() Output:
{ Length of the rect=10
System.out.println(“Area of the Breadth of the rect=20
rect=“+(length*breadth)); Area of the rect=200
} Length of the rect=15
} Breadth of the rect =25
Area of the rect =375
Constructor :- Constructor is a special type of method , method name is same as class name is called
constructor. It is used to initialize memory to the method at object creation. Java constructor is invoked at the
time of object creation.
It constructs the values i.e. provides data for the object that is why it is known as constructor.
75
Default Constructor:- A constructor that have no parameter is known as default constructor.
Syntax:-
<classname>
{
……
}
Eg:- class exp()
{
int a,b;
exp()
{ }
parameterized constructor:- A constructor that have parameters is known as parameterized constructor.
Syntax:-
<classname>
{
……
}
Eg:- class exp()
{
int a,b;
exp(int i, int b)
{
76
a= i; b=j;
}
class Rectangle
class test
{
{
int len;
public static void main(String args[])
int bred;
{
Rectangle(int l,int b)// parameterised construtor
Rectangle r1=new Rectangle(10,20);
{
r1.printArea();
len=l;
r1.getPerimeter();
bred=b;
Rectangle r2=new Rectangle(5,10);
}
r2.printArea();
void printArea()
r2.getPerimeter();
{
Rectangle r3=new Rectangle()// gives error
System.out.println("Area="+(len*bred));
}
}
}
void getPerimeter()
{
System.out.println("Perimeter="+(2*(len+bred)));
}
}
A class can be written with multiple constructors differentiating in number of parameters
passed.
Ex:
➢ Rectangle(){---}// default constructor
➢ Rectangle(int l){---}// parameterized constructor with one parameter
➢ Rectangle(int l,int b){---}// parameterized constructor with two parameters
If no constructor is written in a class, JVM provides a default constructor which initializes
data members to default values. But if any constructor is written in a class JVM does not
provide default constructor.
In the previous example the third object creation gives an error as it is invoking a default
constructor and Rectangle class is written with only parameterized constructor.
Rectangle r3=new Rectangle()// gives error
(Note: If no constructor is written then it does not give error as JVM provides a default
constructor for every class with no constructors written)
Constructor Overloading
class Rectangle Void getPerimeter()
{ {
int len; System.out.println("Perimeter="+(2*(len+bred)));
int bred; }
Rectangle() }
{ class ConstOverload
len=1; {
bred=1; public static void main(String args[])
} {
Rectangle(int l) Rectangle r1=new Rectangle(10,20);
{ r1.getArea();
len=l; r1.getPerimeter();
bred=l;} Rectangle r2=new Rectangle(5);
Rectangle(int l,int b) r2.getArea();
{ r2.getPerimeter();
len=l; Rectangle r3=new Rectangle();
bred=b;} r3.getArea();
Void getArea() r3.getPerimeter();
{ }
System.out.println("Area="+(len*bred)); }
}
this keyword
91
Output:
Static variable Obj1: count is=1
Obj2: count is=1
Obj1: count is=2
class staticdemo Obj2: count is=2
{
static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
staticdemo obj1=new staticdemo();
staticdemo obj2=new staticdemo();
obj1.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
Static variable (example2)
class staticdemo
{ Output:
static int a=0; obj1:a=1 obj2.a=1
int b=0; obj1:b=1 obj2.b=0
public void increment()
{
a++;
b++;
}
public static void main(String args[])
{
staticdemo obj1=new staticdemo();
staticdemo obj2=new staticdemo();
obj1.increment();
System.out.println(“obj1:a="+obj1.a+"\t"+"obj2.a="+obj2.a);
System.out.println(“obj1:b="+obj1.b+"\t"+"obj2.b="+obj2.b);
}
}
Static methods
Static Methods:-
The static keyword is used to create methods that will exist independently of any
instances created for the class. Methods declared static are essentially global methods.
They are called independently of any object. Instead a static method is called through
its class name.
Class variables and methods can be accessed using the class name followed by a dot
and the name of the variable or method.
Static methods are particularly used for creating utility methods that perform useful
functions not related to a specific object . Ex: Math class has many static methods like
cos(), sin()……..
They have restrictions:
❖ Then can directly call only other static methods
❖ They can directly access only static data
❖ They do not have a this reference
Static methods
class demo class staticdemo
{ {
static int increment(int a) public static void main(String args[])
{ {
a++; int r;
return(a); r=demo.increment(10);// as increment is static can be directly accessed
} System.out.println("increment res="+r);
int decrement(int a) demo s=new demo();
{ r=s.decrement(10);// decrement can only be accessed using object
a--; System.out.println("decrement res="+r);
return(a); }
} }
}
Static methods
class demo public static void main(String args[])
{ {
static int increment(int a) int r;
{ r=increment(10);// as increment is static in same class can be directly
a++; //accessed inside main which is static
return(a); System.out.println("increment res="+r);
} demo s=new demo();
int decrement(int a) r=s.decrement(10);// decrement can only be accessed using object
{ System.out.println("decrement res="+r);
a--; }
return(a); }
}
}
Static blocks
Sometimes a class will require some type of initialization before it is ready to
create objects
(ex: it might need to establish a connection to a remote site, it might also
need to initialize certain static variables before any of the class static
methods are used)
A static block is executed only once when the class is first loaded. i.e. it is
executed before the class can be used for any other purpose.
Non-static variables can’t be accessed with in a Java static block.
A static initialization block is a normal block of code enclosed in braces { },
and preceded by the static keyword.
Syntax: static { // code for initialization goes here }
Static block
class StaticBlockDemo {
class STest { public static void main(String args[]) {
static int i; // though two objects are created static block is
executed only once.
int j; STest t1 = new STest();
static { STest t2 = new STest();
i = 10; }
}
//j=20;// gives error as j is non static
member
System.out.println("static block called ");
Output:
} static block called
STest(){ Constructor called
System.out.println("Constructor called"); i=10
j=0
System.out.println("i="+i);
Constructor called
System.out.println("j="+j); i=10
} j=0
}
Strings
➢ Series of characters treated as single unit
➢ May include letters, digits, etc.
➢ String class is present in java.lang package which is a default package imported to
every java class
➢ Like other classes, String has constructors and methods
➢ There are two ways to create String object:
1. By string literal
2. By new keyword
Strings
1) String Literal:-Java String literal is created by using double quotes.
Eg:- String s1=“Java”;
Each time we create a string literal, the JVM checks the string constant pool first.
If the string already exists in the pool, a reference to the pooled instance is
returned. If string doesn't exist in the pool, a new string instance is created and
placed in the pool.
2.By new keyword:-
String s=new String(“Java");
By using new keyword, JVM will create a new string object though Java literal
exists in pool
String literals
Strings are immutable i.e. we cannot manipulate a string instead a new string
will be created
finalize() method:-
The Java run-time system calls finalize( ) method whenever it is about to recycle an object
of that class. Inside the finalize( ) method, you will specify those actions that must be
performed before an object is destroyed. This method is defined in Object class as:
protected void finalize()
{ // finalize code here
}
We can also request JVM to run Garbage Collector. There are two ways to
do it :
1. Using System.gc() method : System class contain static method gc() for
requesting JVM to run Garbage Collector.
2. Using Runtime.getRuntime().gc() method : Runtime class allows the
application to interface with the JVM in which the application is running.
Hence by using its gc() method, we can request JVM to run Garbage
Collector.
class Demo {
Demo() {
System.out.println("Object created: Constructed invoked");
}
void sayHello() {
System.out.println("Hello java programmer");
}