Professional Documents
Culture Documents
Object Oriented Programming-E&TC - 3 - 1709188812039
Object Oriented Programming-E&TC - 3 - 1709188812039
Object Definitions:
•An object is a real-world entity.
•An object is a runtime entity.
•The object is an entity which has state and
behavior.
•The object is an instance of a class.
class in Java
A class is a group of objects which have common
properties. It is a template or blueprint from which objects
are created.
•Syntax
class <class_name>{
field;
method;
}
Instance variable in Java
• A variable which is created inside the class but outside
the method is known as an instance variable.
• Instance variable doesn't get memory at compile time.
• It gets memory at runtime when an object or instance is
created.
Method in Java
In Java, a method is like a function which is used to expose
the behavior of an object.
Advantage of Method
1)Code Reusability 2)Code Optimization
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main
method
class TestStudent1
{ public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:
0
null
We can have multiple classes in different Java files or single Java file. If you define
multiple classes in a single Java source file, it is a good idea to save the file name
with the class name which has main() method.
3 Ways to initialize object
Output:
111 Karan
222 Aryan
2) Object and Class Example: Initialization through method
3) Object and Class Example: Initialization through a constructor
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Rules for creating Java constructor
Output:
0 null
0 null
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.
1. //Java Program to demonstrate the use of the parameterized constructor.
2. class Student4{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student4(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display()
12. {
13. System.out.println(id+" "+name);}
14.
15. public static void main(String args[]){
16. //creating objects and passing values
17. Student4 s1 = new Student4(111,"Karan");
18. Student4 s2 = new Student4(222,"Aryan");
19. //calling method to display the values of object
20. s1.display();
21. s2.display();
22. }
23. }
Test it Now
Output:
111 Karan
222 Aryan
Constructor overloading in java
A constructor must not have a return A method must have a return type.
type.
The Java compiler provides a default The method is not provided by the compiler
constructor if you don't have any in any case.
constructor in a class.
The constructor name must be same as The method name may or may not be same
the class name. as the class name.
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
Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the
method
1) 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.
Understanding the problem without this keyword
class Student{ class TestThis1{
int rollno; public static void main(String args[])
String name; {
float fee; Student s1=new Student(111,"ankit",5000f);
Student(int rollno,String name,float fee) Student s2=new Student(112,"sumit",6000f);
{ s1.display();
rollno=rollno; s2.display();
name=name; }
fee=fee; }
}
void display()
{ Output:
System.out.println(rollno+" "+name+" "+fee); 0 null 0.0
} 0 null 0.0
}
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.
Solution of the above problem by this keyword class TestThis2{
class Student{ public static void main(String args[]){
int rollno; Student s1=new Student(111,"ankit",50
String name; 00f);
float fee; Student s2=new Student(112,"sumit",60
Student(int rollno,String name,float fee){ 00f);
this.rollno=rollno; s1.display();
this.name=name; s2.display();
this.fee=fee; }}
}
void display() Output:
{System.out.println(rollno+" "+name+" "+ 111 ankit 5000
fee);} 112 sumit 6000
}
If local variables(formal arguments) and instance variables are different, there is no need
to use this keyword like in the following program:
Program where this keyword is not required
It is better approach to use meaningful names for variables. So we use same name for
instance variables and parameters in real time, and always use this keyword.
2) this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you
don't use the this keyword, compiler automatically adds this keyword while
invoking the method. Let's see the example
1. class A{
2. void m(){System.out.println("hello m");}
3. void n(){
4. System.out.println("hello n");
5. //m();//same as this.m()
6. this.m();
7. }
8. }
9. class TestThis4{
10. public static void main(String args[]){
11. A a=new A();
12. a.n();
13. }}
Output:
hello n
hello m
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used to
reuse the constructor. In other words, it is used for constructor chaining.
Calling default constructor from parameterized constructor:
1. class A{
2. A(){System.out.println("hello a");}
3. A(int x){
4. this();
5. System.out.println(x);
6. }
7. }
8. class TestThis5{
9. public static void main(String args[]){
10. A a=new A(10);
11. }}
Output:
hello a
10
Calling parameterized constructor from default constructor:
1. class A{
2. A(){
3. this(5);
4. System.out.println("hello a");
5. }
6. A(int x){
7. System.out.println(x);
8. }
9. }
10. class TestThis6{
11. public static void main(String args[]){
12. A a=new A();
13. }}
Output:
5
hello a
Using Objects as parameter:
Class Data{
int data1; int data2;
}
Class setData{
Void setData(Data Da, int d1, int d2)
{
da.data1=d1; da.data2=d2;
}
Void getData(Data Da)
{
System.out.println(“data1:” +Da.data1);
System.out.println(“data2:” +Da.data2);
}
}
Public class Javaapp
{
Public static void main(Strings args[]){
Data da=new Data();
setData sd = new setData();
sd.setData(da,50,100);
sd.getData(da);
}
}
Running Objects-Method can return object also
Class Test
{
Int x;
Test(int i)
{ x=i;}
Test inc()
{Test temp=new Test(x+200);
return temp;}
}
Public class Example{
Public static void main(Strings args[]){
Test a= new Test(135);
Test b;
b=a.inc();
System.out.println(“a.x:” +a.x);
System.out.println(“b.x:” +b.x);
b=b.inc();
System.out.println(“b.x: after second increment” +b.x);
}}
Java String
In Java, string is basically an object that represents sequence of
char values. An array of characters works same as Java string. For
example:
1.char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2.String s=new String(ch);
is same as:
String s="javatpoint";
2) By new keyword
1.String s=new String("Welcome");//
creates two objects and one reference variable
By equals() method
By = = operator
By compareTo() method
1) String compare by equals() method
The String equals() method compares the original content of the string. It compares values
of string for equality. String class provides two methods:
public boolean equals(Object another) compares this string to the specified object.
public boolean equalsIgnoreCase(String another) compares this String to another string,
ignoring case.
1.class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11.}
Output:true
true
false
1.Class Teststringcomparison2{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="SACHIN";
5.
6. System.out.println(s1.equals(s2));//false
7. System.out.println(s1.equalsIgnoreCase(s2));//true
8. }
9.}
output:
false
true
2) String compare by == operator
The = = operator compares references not values.
== operator compares two object references to check whether
they refers to same instance of string.
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
3) String compare by compareTo() method
The String compareTo() method compares values lexicographically
and returns an integer value that describes if first string is less
than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
•s1 == s2 :0
•s1 > s2 :positive value
•s1 < s2 :negative value
1.class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
9. }
10.} Output:0
1
-1
String Concatenation in Java
In java, string concatenation forms a new string that is the
combination of multiple strings. There are two ways to concat string
in java:
1.By + (string concatenation) operator
2.By concat() method
1) String Concatenation by + (string concatenation) operator
Java string concatenation operator (+) is used to add strings.
For Example:
1.class TestStringConcatenation1{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. System.out.println(s);//Sachin Tendulkar
5. }
6.}
Output:Sachin Tendulkar
The Java compiler transforms above code to this:
String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();
2) String Concatenation by concat() method
The String concat() method concatenates the specified string to the
end of current string. Syntax:
1.public String concat(String another)
1.class TestStringConcatenation3{
2. public static void main(String args[]){
3. String s1="Sachin ";
4. String s2="Tendulkar";
5. String s3=s1.concat(s2);
6. System.out.println(s3);//Sachin Tendulkar
7. }
8.}
Sachin Tendulkar
Java String class methods
The java.lang.String class provides a lot of methods to
work on string. By the help of these methods, we can
perform operations on string such as trimming,
concatenating, converting, comparing, replacing strings
etc.
Java String toUpperCase() and toLowerCase() method
The java string toUpperCase() method converts this string into
uppercase letter and string toLowerCase() method into
lowercase letter.
1.String s="Sachin";
2.System.out.println(s.toUpperCase());//SACHIN
3.System.out.println(s.toLowerCase());//sachin
4.System.out.println(s);//Sachin(no change in original)
Output
SACHIN
sachin
Sachin
Java String valueOf() method
The string valueOf() method coverts given type such as int,
long, float, double, boolean, char and char array into string.
1.int a=10;
2.String s=String.valueOf(a);
3.System.out.println(s+10);
Output
1010
Java String replace() method
The string replace() method replaces all occurrence of first
sequence of character with second sequence of character.
1.String s1="Java is a programming language. Java is a platform. J
ava is an Island.";
2.String replaceString=s1.replace("Java","Kava");//
replaces all occurrences of "Java" to "Kava"
3.System.out.println(replaceString);
Output-
Kava is a programming language. Kava is a platform. Kava is an Island.
Java String trim() method
The string trim() method eliminates white spaces before and after
string.
1.String s=" Sachin ";
2.System.out.println(s);// Sachin
3.System.out.println(s.trim());//Sachin
Output
Sachin
Sachin
Example of java substring
1.public class TestSubstring{
2. public static void main(String args[]){
3. String s="SachinTendulkar";
4. System.out.println(s.substring(6));//Tendulkar
5. System.out.println(s.substring(0,6));//Sachin
6. }
7.}
Java StringBuffer class
Java StringBuffer class is used to create mutable (modifiable)
string. The StringBuffer class in java is same as String class except
it is mutable i.e. it can be changed.
1.class StringBufferExample2{
2.public static void main(String args[]){
3.StringBuffer sb=new StringBuffer("Hello ");
4.sb.insert(1,"Java");//now original string is changed
5.System.out.println(sb);//prints HJavaello
6.}
}
3) StringBuffer replace() method
The replace() method replaces the given string from the
specified beginIndex and endIndex
1.class StringBufferExample3{
2.public static void main(String args[]){
3.StringBuffer sb=new StringBuffer("Hello");
4.sb.replace(1,3,"Java");
5.System.out.println(sb);//prints HJavalo
6.}
7.}
4) StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from
the specified beginIndex to endIndex.
1.lass StringBufferExample4{
2.public static void main(String args[]){
3.StringBuffer sb=new StringBuffer("Hello");
4.sb.delete(1,3);
5.System.out.println(sb);//prints Hlo
6.}
7.}
5) StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current
string.
1.class StringBufferExample5{
2.public static void main(String args[]){
3.StringBuffer sb=new StringBuffer("Hello");
4.sb.reverse();
5.System.out.println(sb);//prints olleH
6.}
7.}
6) StringBuffer capacity() method
The capacity() method of StringBuffer class returns the current
capacity of the buffer. The default capacity of the buffer is 16. If
the number of character increases from its current capacity, it
increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.
1.class StringBufferExample6{
2.public static void main(String args[]){
3.StringBuffer sb=new StringBuffer();
4.System.out.println(sb.capacity());//default 16
5.sb.append("Hello");
6.System.out.println(sb.capacity());//now 16
7.sb.append("java is my favourite language");
8.System.out.println(sb.capacity());//
now (16*2)+2=34 i.e (oldcapacity*2)+2
9.}
10.}
Recursion
Class FactClass{
Int fun(int x)
{
int res;
if (x==1) return 1;
res=fun(x-1)*x;
return res;
}}
Public class RecursionExapmle
{
public static void main(String args[])
{
FactClass f= new FactClass();
System.out.println(“Factorial of 7 is” +f.fun(7));
}
}
Static
• Generally class member should be accessed using objects only.
• With static ,it is possible to create number which can be used directly without
any object.
• It is possible by preceding the member with static keyword.
• Variables and method can be declared static;
from m1
Static blocks
If you need to do computation in order to initialize your static variables, you
can declare a static block that gets executed exactly once, when the class is
first loaded. Consider the following java program demonstrating use of static
blocks.
class staticEx2
{
// static variable
static int a = 10;
static int b;
// static block
static {
System.out.println("Static block initialized.");
b = a * 4;
} Output:
public static void main(String[] args)
{ Static block initialized.
System.out.println("from main"); from main
System.out.println("Value of a : "+a); Value of a : 10
System.out.println("Value of b : "+b); Value of b : 40
}
}
Static variables
When a variable is declared as static, then a single copy of variable is created
and shared among all objects at class level. Static variables are, essentially,
global variables. All instances of the class share the same static variable.
Important points for static variables :-
•We can create static variables at class-level only.
•static block and static variables are executed in order they are present in a
program.
final keyword is used in different contexts. First of all, final is a
non-access modifier applicable only to a variable, a method or a
class.Following are different contexts where final is used.
1.class FinalkeywordEx {
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. FinalkeywordEx obj=new FinalkeywordEx();
8. obj.run();
9. }
10.}//end of class
finalize() method in Java
The finalize() method of Object class is a method that the Garbage Collector always
calls just before the deletion/destroying the object which is eligible for Garbage
Collection, so as to perform clean-up activity.
Clean-up activity means closing the resources associated with that object like Database
Connection, Network Connection or we can say resource de-allocation. Remember it is
not a reserved keyword. Once the finalize method completes immediately Garbage
Collector destroy that object.
Since Object class contains the finalize method hence finalize method is available for
every java class since Object is the superclass of all java classes. Since it is available for
every java class hence Garbage Collector can call the finalize method on any java
object.
}
Access Modifiers in Java
The access modifiers in Java specifies the accessibility or
scope of a field, method, constructor, or class. We can
change the access level of fields, constructors, methods, and
class by applying the access modifier on it.
1.Private: The access level of a private modifier is only within
the class. It cannot be accessed from outside the class.
2.Default: The access level of a default modifier is only within
the package. It cannot be accessed from outside the package.
If you do not specify any access level, it will be the default.
3.Protected: The access level of a protected modifier is within
the package and outside the package through child class. If you
do not make the child class, it cannot be accessed from outside
the package.
4.Public: The access level of a public modifier is everywhere.
It can be accessed from within the class, outside the class,
within the package and outside the package.
ccess within class within outside outside
Modifier package package by package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Java Command Line Arguments
The java command-line argument is an argument i.e. passed at
the time of running the java program.
The arguments passed from the console can be received in the
java program and it can be used as an input.
}
1.compile by > javac CommandLineExample.java
2.run by > java CommandLineExample sonoo
1.class CommandLineExample2{
2.public static void main(String args[]){
3.System.out.println("Your first argument is: "+args[0]);
for(int i=0;i<args.length;i++)
4.System.out.println(args[i]);
}
}