Unit - 2 Java Programming
Unit - 2 Java Programming
Output:
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);}
• 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
}
@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");}
}
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.
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
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[])
{
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