0% found this document useful (0 votes)
8 views

Unit - 2 Java Programming

Uploaded by

aavvv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit - 2 Java Programming

Uploaded by

aavvv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Constructors in Java

Constructor is a block of codes similar to the


method. It is called when an instance of the class is
created. At the time of calling constructor, memory
for the object is allocated in the memory.
It is a special type of method which is used to
initialize the object.
Every time an object is created using the new()
keyword, at least one constructor is called.
It calls a default constructor if there is no
constructor available in the class.
Java compiler provides a default constructor by
default
Rules for creating Java constructor
There are two rules defined for the
constructor.
Constructor name must be the same as its
class name
A Constructor must have no explicit return
type
A Java constructor cannot be abstract, static,
final, and synchronized
Types Of Constructors In Java
There are two types of constructors in Java:
Default constructor (no-arg constructor)
Parameterized constructor

Java Default Constructor

A constructor is called "Default Constructor" when it


doesn't have any parameter.

Syntax of default constructor:


<class_name>(){}
Example of default constructor
class Emp1{
//creating a default constructor
Emp1()
{
System.out.println(“employee account is created”);
}
//main method
public static void main(String args[])
{
//calling a default constructor
Emp1 e=new Emp1();
}
}

Output:

employee account is created


Example of default constructor that
displays the default values
class Student3
{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
} Output:
0 null
0 null Here 0 and null values are provided by default constructor.
Java Parameterized Constructor
A constructor which has a specific number of
parameters is called a parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide
different values to distinct objects. However, you
can provide the same values also.
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display()
{System.out.println(id+" "+name);}

public static void main(String args[])


{
//creating objects and passing values
Student4 s1 = new Student4(111,"Kani");
Student4 s2 = new Student4(222,"Arya");
//calling method to display the values of object
s1.display();
s2.display();
}
} output 111 kani
222 Arya
Constructor Overloading in Java
A constructor is just like a method but without
return type.
It can also be overloaded like Java methods.
Constructor overloading in Java is a technique
of having more than one constructor with
different parameter lists.
 They are arranged in a way that each
constructor performs a different task.
 They are differentiated by the compiler by the
number of parameters in the list and their
types.
//Java program to overload constructors

class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Kani");
Student5 s2 = new Student5(222,"Arya",25);
s1.display();
s2.display();
}
}
Output:
• 111 Kani 0
• 222 Arya 25
Difference between constructor and
method in Java
Difference between constructor and
method in Java
Java Copy Constructor
There is no copy constructor in Java. However,
we can copy the values from one object to
another like copy constructor in C++.
There are many ways to copy the values of
one object into another in Java. They are:
By constructor
By assigning the values of one object into
another
By clone() method of Object class
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i, String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s)
{
id = s.id;
name =s.name;
}

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Copying values without constructor
class Student7
{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student7 s1 = new Student7(111,"Kani”);
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Java static keyword
• The static keyword in Java is used for memory
management. We can apply static keyword
with variables, methods, blocks and nested
classes. The static keyword belongs to the class
than an instance of the class.
• The static can be:
• Variable (also known as a class variable)
• Method (also known as a class method)
• Block
• Nested class
Java Static Variable
• If you declare any variable as static, it is known as a
static variable.
• The static variable can be used to refer to the
common property of all objects (which is not
unique for each object).
• For example, the company name of employees,
college name of students, etc.
• The static variable gets memory only once in the
class area at the time of class loading.
• Advantages of static variable
• It makes your program memory efficient (i.e., it
saves memory).
Java static property is shared to all objects.
class Student{
int rollno;
String name;
String college=“SRMIST”;
}
 Suppose there are 500 students in my college, now all
instance data members will get memory each time
when the object is created.
 All students have its unique rollno and name, so
instance data member is good in such case.
 Here, "college" refers to the common property of
all objects. If we make it static, this field will get the
memory only once.
Example of static variable
• //Java Program to demonstrate the use of static variable

• class Student{
• int rollno;//instance variable
• String name;
• static String college =“SRMIST";//static variable
• //constructor
• Student(int r, String n){
• rollno = r;
• name = n;
• }
• //method to display the values
• void display (){System.out.println(rollno+" "+name+" "+college);}
• }
• //Test class to show the values of objects
• public class TestStaticVariable1{
• public static void main(String args[]){
• Student s1 = new Student(111,"Kani");
• Student s2 = new Student(222,"Arya");
• //we can change the college of all objects by the single line of code
• //Student.college="BBDIT";
• s1.display();
• s2.display();
• }
• }
• 111 Kani SRMIST
• 222 Arya SRMIST
2) Java static method
If you apply static keyword with any method,
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.
//Java Program to demonstrate the use of a static method.
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 TestStaticMethod{
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
this keyword in Java

• There can be a lot of


usage of Java this
keyword.
• In Java, this is
a reference
variable that refers to
the current object.
Usage of Java this keyword
• this can be used to refer current class instance
variable.
• this can be used to invoke current class method
(implicitly)
• this() can be used to invoke current class
constructor.
• this can be passed as an argument in the method
call.
• this can be passed as argument in the constructor
call.
• this can be used to return the current class
instance from the method.
• this: to refer current class instance variable

• The this keyword can be used to refer


current class instance variable. If there is
ambiguity between the instance variables
and parameters, this keyword resolves the
problem of ambiguity.
EXAMPLE
• class Student{
• int rollno;
• String name;
• float fee;
• Student(int rollno,String name,float fee){
• rollno=rollno;
• name=name;
• fee=fee;
• }
• void display(){System.out.println(rollno+" "+name+" "+fee);}
• }
• class TestThis1{
• public static void main(String args[]){
• Student s1=new Student(111,"ankit",5000f);
• Student s2=new Student(112,"sumit",6000f);
• s1.display();
• s2.display();
• }}
• 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.
EXAMPLE USING ‘this’
• class Student{
• int rollno;
• String name;
• float fee;
• Student(int rollno,String name,float fee){
• this.rollno=rollno;
• this.name=name;
• this.fee=fee;
• }
• void display(){System.out.println(rollno+" "+name+" "+fee);}
• }

• class TestThis2{
• public static void main(String args[]){
• Student s1=new Student(111,"ankit",5000f);
• Student s2=new Student(112,"sumit",6000f);
• s1.display();
• s2.display();
• }}
Java Object finalize() Method
• 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.
Syntax
protected void finalize() throws Throwable
Throwable - the Exception is raised by this method
public class JavafinalizeExample1 {
public static void main(String[] args)
{
JavafinalizeExample1 obj = new JavafinalizeExample1();
System.out.println(obj.hashCode());
obj = null;
// calling garbage collector
System.gc();
System.out.println("end of garbage collection");

}
@Override
protected void finalize()
{
System.out.println("finalize method called");
}
}
Final Keyword In Java
• The final keyword in java is used to restrict
the user. The java final keyword can be used in
many context. Final can be:
• variable
• method
• class
• Java final variable
• If you make any variable as final, you cannot
change the value of final variable(It will be
constant).
Example
• There is a final variable speedlimit, we are going to change the
value of this variable, but It can't be changed because final variable
once assigned a value can never be changed.

class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=200;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}
}//end of class
Java final method
If you make any method as final, you cannot override it.

class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Java final class
If you make any class as final, you cannot extend it.
final class Bike{}

class Honda1 extends Bike{


void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda1 honda= new Honda1();
honda.run();
}
}
• Is final method inherited?
• Ans) Yes, final method is inherited but you
cannot override it. For Example:
class Bike{
final void run(){System.out.println("running...")
;}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Garbage Collection- Finalize() method
In C and C++, it is the programmer’s responsibility to de-allocate the
dynamically allocated memory using the free() in c and delete() in C++function.
 In Java,JVM automatically de-allocates memory (Garbage Collection)

The process of removing unused objects from heap memory is known as Garbage
collection and this is a part of memory management in Java.
 Garbage collector is best example of Daemon thread as it is always running in
background.

• Advantage of Garbage Collection


It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
 It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts
26-10-2020 DEPARTMENT OF COMPUTER SCIENCE, SRM 36
IST - RAMAPURAM
Cont…
• gc() method
• The gc() method is used to invoke the garbage
collector to perform cleanup processing. The
gc() is found in System and Runtime classes.
• public static void gc(){}
EXAMPLE
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");
}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}

object is garbage collected


object is garbage collected
Java Inner Classes (Nested Classes)
 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.

Syntax of Inner class

class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Advantage of Java inner classes
• 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.
• Code Optimization: It requires less code to write.
Need of Java Inner class
• Sometimes users need to program a class in
such a way so that no other class can access it.
• Therefore, it would be better if you include it
within other classes.
• If all the class objects are a part of the outer
object then it is easier to nest that class inside
the outer class.
• That way all the outer class can access all the
objects of the inner class.
Types of Nested classes

• There are two types of nested classes non-


static and static nested classes. The non-static
nested classes are also known as inner classes.
• Non-static nested class (inner class)
– Member inner class
– Anonymous inner class
– Local inner class
Static nested class
Member inner class example
• A non-static class that is created inside a class but
outside a method is called member inner class. It is
also known as a regular inner class. It can be declared
with access modifiers like public, default, private, and
protected.
Syntax:
class Outer{
//code
class Inner{
//code
}
}

44
EXAMPLE
Java Member Inner Class Example
In this example, we are creating a msg() method in the member inner class
that is accessing the private data member of the outer class.
class TestMemberOuter1{
private int data=30;
class Inner
{
void msg()
{
System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}

45
2. Anonymous inner class
1. Java anonymous inner class is an inner class without a
name and for which only a single object is created.
2. An anonymous inner class can be useful when making
an instance of an object with certain "extras" such as
overloading methods of a class or interface, without
having to actually subclass a class.
3. In simple words, a class that has no name is known as
an anonymous inner class in Java.
4. 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:
 Class (may be abstract or concrete).
 Interface
46
2. Anonymous inner class
abstract class Person
{
abstract void eat();
}
class TestAnonymousInner
{
public static void main(String args[])
{
Person p=new Person(){
void eat()
{
System.out.println("nice fruits");}
};
p.eat();
}
}

47
3. LOCAL INNER CLASS
• A class i.e., created inside a method, is called local
inner class in java.
• Local Inner Classes are the inner classes that are
defined inside a block.
• Generally, this block is a method body. Sometimes this
block can be a for loop, or an if clause.
• Local Inner classes are not a member of any enclosing
classes.
• They belong to the block they are defined within, due
to which local inner classes cannot have any access
modifiers associated with them.
• However, they can be marked as final or abstract.
• These classes have access to the fields of the class
enclosing it.
48
EXAMPLE
public class localInner1{
private int data=30;//instance variable
void display()
{
class Local{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[])
{
localInner1 obj=new localInner1();
obj.display();
}
}

49
STATIC NESTED CLASS
 A static class i.e. created inside a class is called static nested
class in java.
 It cannot access non-static data members and methods.
 It can be accessed by outer class name.
- It can access static data members of outer class including
private.
- Static nested class cannot access non-static (instance)
data member or method.

50
STATIC NESTED CLASS EXAMPLE
class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Note: In this example, you need to create the instance of static nested class
because it has instance method msg(). But you don't need to create the
object of Outer class because nested class is static and static properties,
methods or classes can be accessed without object.

51
String class in java
Generally, String is a sequence of characters. But in Java, string is an object that
represents a sequence of characters. The java.lang.String class is used to create a
string object.
How to create a string object?
There are two ways to create String object:
By string literal
By new keyword
String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you 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 the string doesn't
exist in the pool, a new string instance is created and placed in the pool.
52
Example :
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
Note: String objects are stored in a special memory area known as the "string
constant pool
To make Java more memory efficient (because no new objects are
created if it exists already in the string constant pool).

53
2) By new keyword
String s=new String("Welcome");
In such case, JVM will create a new string object in normal (non-pool) heap memory,
and the literal "Welcome" will
be placed in the string constant pool. The variable s will refer to the object in a heap
(non-pool).
EXAMPLE
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");
//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3); 54
Immutable String in Java
• In java, string objects are immutable. Immutable simply means
unmodifiable or unchangeable.
• Once string object is created its data or state can't be changed but a new
string object is created.

class Testimmutablestring{
public static void main(String args[]){
String s=“Welcome";
s.concat(" Rohith");
//concat() method appends the string at the end
System.out.println(s);
//will print Welcome because strings are immutable objects
}
}

55
Immutable String
in Java

56
Java String class methods
No. Method Description
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 static String format(String format, Object... args) returns a formatted string.

4 static String format(Locale l, String format, Object... returns formatted string with given locale.
args)
5 String substring(int beginIndex) returns substring for given begin index.
6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end
index.
7 boolean contains(CharSequence s) returns true or false after matching the
sequence of char value.
8 static String join(CharSequence delimiter, returns a joined string.
CharSequence... elements)
9 static String join(CharSequence delimiter, returns a joined string.
Iterable<? extends CharSequence>
elements)
10 boolean equals(Object another) checks the equality of string with the given
object.
11 boolean isEmpty() checks if string is empty.
12 String concat(String str) concatenates the specified string.
57
Java String class methods
13 String replace(char old, char new) replaces all occurrences of the specified char
value.
14 String replace(CharSequence old, replaces all occurrences of the specified
CharSequence new) CharSequence.
15 static String compares another string. It doesn't check case.
equalsIgnoreCase(String another)
16 String[] split(String regex) returns a split string matching regex.
17 String[] split(String regex, int returns a split string matching regex and limit.
limit)
18 String intern() returns an interned string.
19 int indexOf(int ch) returns the specified char value index.
20 int indexOf(int ch, int fromIndex) returns the specified char value index starting
with given index.
21 int indexOf(String substring) returns the specified substring index.
22 int indexOf(String substring, int returns the specified substring index starting
fromIndex) with given index.
23 String toLowerCase() returns a string in lowercase.
24 String toLowerCase(Locale l) returns a string in lowercase using specified
locale.
25 String toUpperCase() returns a string in uppercase.
26 String toUpperCase(Locale l) returns a string in uppercase using specified
locale.
27 String trim() removes beginning and ending spaces of this 58
string.
Java String class Example
class strMethod
{
static String str="object";
public static void main(String arg[])
{

System.out.println("original string: "+str);


int str1=str.length ();
S y s t e m . o u t . p r i n t l n (" len g th o f string : "+ str1);
String str2=str+" Oriented";
System.out.println("Modified string: "+str2);
String str3=str2.toUpperCase();
System.out.println("String :"+str3);
c h a r c h ; c h = " a b c " .c h a r A t ( 2 );
System.out.println("CharAt :"+ch);
byte x[]={66,67,68,69,70};
String s 4 = n e w String(x);
System.out.println(s4);
String str4="Hello".replace('l','w');
System.out.println(str4);
String s1=”BCA”;
String s2=”bca”;
System.out.println(s1.equals(s2));
S y s t e m . o u t . p r i n t l n (s 1 . e q u a ls Ig n o re C a s e ( s 2 )); S t r i n g
s 5 = ” F o o t ball”; System.out.println(s5.startsWith(“foot”));
System.out.println(s5.endsWith(“ball”));
}}
59
Overloading methods in Java
Method Overloading is a feature that allows a class to have more
than one method having the same name, if their argument lists are
different.
It is similar to constructor overloading in Java, that allows a class
to have more than one
constructor having different argument lists.
 Overloading is an example of compiler time polymorphism or Static
Polymorphism
Three ways to overload a method
In order to overload a method, the argument lists of the methods must
differ in either of these:
1. Number of parameters.
For example:
add(int, int)
add(int, int, int)
2. Data type of parameters. 60
Example – Overloading method in java
public class MethodOverloading
{
void add(int a,int
b)
{
System.out.println(a+b);
}
void add(float a,float b)
{
System.out.println(a+b);
}
public static void main(String args[]){
MethodOverloading
obj=new
MethodOverloading();
obj.add(15f,15f); 61
Objects as Parameters
• A method can take an objects as a parameter.
• For example, in the following program, the
method setData( ) takes three parameter.
• The first parameter is an Data object.
• If you pass an object as an argument to a
method, the mechanism that applies is
called pass-by-reference, because a copy of
the reference contained in the variable is
transferred to the method, not a copy of the
object itself.
62
Example

63
Returning Objects
• Time add(Time tt2)
{
//Add two times and display information in Time Temp = new Time();
Temp.secs = secs + tt2.secs ; //add seconds
proper time format Temp.mins = mins + tt2.mins; //add minutes
class Time Temp.hours = hours + tt2.hours; //add hours
if(Temp.secs > 59) //seconds overflow check
{ {
Temp.secs = Temp.secs - 60; //adjustment of
private int hours, mins,secs; minutes
Temp.hours++; //carry hour
Time() //Constructor with no }
return Temp;
parameter
{ }
void display()
hours = mins = secs = 0; {
System.out.println(hours + " : "+ mins +" : "+ secs);
} }
}
Time(int hh, int m, int ss) class ReturningObjectsfromMethods
{
//Constructor with 3 parameters public static void main(String[] args)
{
{
hours = hh; Time t1 = new Time(4,58,55);
Time t2 = new Time(3,20,10);
mins = m; Time t3;
t3 = t1.add(t2);
secs = ss; System.out.print("Time after addition (hh:min:ss) ---->");
t3.display();
} }
}

64

You might also like