Unit 2 (Objects and Classes)
Unit 2 (Objects and Classes)
1. By reference variable
2. By method
3. By constructor
• Initialization through reference
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student(); //reference variable s1
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);
//printing members with a white space
}
}
• Initialization through method
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation()
{System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
Example class Employee{
int id; String name; float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display()
{System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e1.display();
e2.display();
}
}
Different ways to create an object
in Java
Anonymous object
• new Calculation(); //anonymous object
• Calculation c=new Calculation(); // Calling method through a reference
c.fact(5)
• new Calculation().fact(5); //Calling method through an anonymous object
Creating multiple objects by one type only
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//
creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Method
• A method is a block of code or collection of statements or a set of code
grouped together to perform a certain task or operation. The method is
executed only when we call or invoke it.
• The method declaration provides information about method attributes,
such as visibility, return-type, name, and arguments.
Access Specifier: Access specifier or modifier is the access type of the
method and specifies the visibility of the method. Java
provides four types of access specifier:
• Two types:
Default constructor (no-arg constructor)
Parameterized constructor
Default vs Parameterized Constructor
class A2{
static{System.out.println("static block is invo
ked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
this reference
1) this: to refer current class instance variable
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 TestThis{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
2) this: to invoke current class method
3) this() : to invoke current class constructor
Calling default constructor from parameterized
constructor
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis{
public static void main(String args[]){
A a=new A(10);
}}
Calling parameterized constructor from default
constructor
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis{
public static void main(String args[]){
A a=new A();
}}
4) this: to pass as an argument in the
method
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
5) this: to pass as argument in the
constructor call
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//
using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
6) this keyword can be used to return
current class instance
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
final keyword
1) final with Variables: The value of variable cannot be changed once
initialized. if we modify it then we get Compile Time Error.
(2) final with Method: Whenever we declare any method as final, then it
means that we can’t override that method.
(3) final with Class: Whenever we declare any class as final, it means that
we can’t extend that class or we can’t make subclass of that class.
Program to illustrate final keyword
final class G {
// by default it is final.
void h() {}
is same as:
String s="javaprogram";
Two ways to create String object:
1. By string literal
String s="welcome";
String s1="Welcome";
String s2="Welcome"; //It doesn't create a new instance
2. By new keyword
String s=new String("Welcome"); //creates two objects and one reference variable
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);
}}
Java String class methods
Method Description
char charAt(int index) It returns char value for the particular index
int length() It returns string length
static String format(String format, It returns a formatted string.
Object... args)
static String format(Locale l, String It returns formatted string with given locale.
format, Object... args)
String substring(int beginIndex) It returns substring for given begin index.
String substring(int beginIndex, int It returns substring for given begin index and
endIndex) end index.
boolean contains(CharSequence s) It returns true or false after matching the
sequence of char value.
static String join(CharSequence It returns a joined string.
delimiter, CharSequence... elements)
boolean equals(Object another) It checks the equality of string with the given
Method Description
boolean isEmpty() It checks if string is empty.
String concat(String str) It concatenates the specified string.
String replace(char old, char new) It replaces all occurrences of the specified
char value.
String replace(CharSequence old, It replaces all occurrences of the specified
CharSequence new) CharSequence.
static String equalsIgnoreCase(String It compares another string. It doesn't check
another) case.
String[] split(String regex) It returns a split string matching regex.
String[] split(String regex, int limit) It returns a split string matching regex and
limit.
String intern() It returns an interned string.
int indexOf(int ch) It returns the specified char value index.
int indexOf(int ch, int fromIndex) It returns the specified char value index
starting with given index.
Method Description
int indexOf(String substring) It returns the specified substring index.
int indexOf(String substring, It returns the specified substring index starting with
int fromIndex) given index.
String toLowerCase() It returns a string in lowercase.
String toLowerCase(Locale l) It returns a string in lowercase using specified locale.
String toUpperCase() It returns a string in uppercase.
String toUpperCase(Locale l) It returns a string in uppercase using specified locale.
String trim() It removes beginning and ending spaces of this string.
static String valueOf(int It converts given type into string. It is an overloaded
value) method.
int indexOf(String substring) It returns the specified substring index.
int indexOf(String substring, It returns the specified substring index starting with
int fromIndex) given index.
• java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.
Method Description
append(String s) It is used to append the specified string with this string.
The append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.
insert(int offset, String It is used to insert the specified string with this string at
s) the specified position. The insert() method is overloaded
like insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
replace(int startIndex, It is used to replace the string from specified startIndex
int endIndex, String str) and endIndex.
delete(int startIndex, int It is used to delete the string from specified startIndex and
endIndex) endIndex.
reverse() is used to reverse the string.
capacity() It is used to return the current capacity.
Table: Important Methods of StringBuffer Class (cont.)
Method Description
ensureCapacity(int It is used to ensure the capacity at least equal
minimumCapacity) to the given minimum.
charAt(int index) It is used to return the character at the
specified position.
length() It is used to return the length of the string i.e.
total number of characters.
substring(int beginIndex) It is used to return the substring from the
specified beginIndex.
substring(int beginIndex, int It is used to return the substring from the
endIndex) specified beginIndex and endIndex.
StringBuffer Class append() Method
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");
//now original string is changed
System.out.println(sb); //prints Hello Java
}
}
StringBuffer insert() Method
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");
//now original string is changed
System.out.println(sb); //prints HJavaello
}
}
StringBuffer replace() Method
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb); //prints HJavalo
}
}
StringBuffer delete() Method
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb); //prints Hlo
}
}
StringBuffer reverse() Method
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); //prints olleH
}
}
StringBuffer capacity() Method
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity()); //default 16
sb.append("Hello");
System.out.println(sb.capacity()); //now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());
//now (16*2)+2=34 i.e (oldcapacity*2)+2
StringBuffer ensureCapacity() method
class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
} }
3) Java StringBuilder Class
Table: Important Constructors of StringBuilder Class
Table: Important Methods of StringBuilder Class
Method Description
append(String s) It is used to append the specified string with this string. The
append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double)
etc.
insert(int offset, String It is used to insert the specified string with this string at the
s) specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
replace(int startIndex, It is used to replace the string from specified startIndex and
int endIndex, String str) endIndex.
delete(int startIndex, It is used to delete the string from specified startIndex and
int endIndex) endIndex.
reverse() It is used to reverse the string.
Method Description
ensureCapacity(int It is used to ensure the capacity at least equal to the
minimumCapacity) given minimum.
charAt(int index) It is used to return the character at the specified
position.
length() It is used to return the length of the string i.e. total
number of characters.
substring(int beginIndex) It is used to return the substring from the specified
beginIndex.
substring(int beginIndex, int It is used to return the substring from the specified
endIndex) beginIndex and endIndex.
Difference between StringBuffer
and StringBuilder
No. StringBuffer StringBuilder