You are on page 1of 75

UNIT III

Classes, Objects & Methods in Java

Class Fundamentals, Declaring Objects, Assigning Object


reference variables, Methods, Constructors, The This
keyword, Garbage collection, finalize method, Overloading
methods, using objects as parameters, Argument passing,
returning objects, Recursion, access control, static, final,
arrays, strings class, Command line arguments.
Class Fundamentals
An entity that has state and behavior is known as an object
An object is an instance of a class. A class is a
template or blueprint from which objects are
created. So, an object is the instance(result) of a
class.

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.

A class in Java can contain:


•Fields
•Methods
•Constructors
•Blocks
•Nested class and interface

•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

new keyword in Java


The new keyword is used to allocate memory at runtime. All
objects get memory in Heap memory area.
Object and Class Example: main within the class
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
public static void main(String args[]){
Student s1=new Student();//
creating an object of Student //Printing values of the object
System.out.println(s1.id);//
accessing member through reference variable
System.out.println(s1.name);
}
}
Output
0
null
Object and Class Example: main outside the class

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

There are 3 ways to initialize object in


Java.

1.By reference variable


2.By method
3.By constructor
1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object.
Class student Output:
{Int id; String name; Id=10
} Name=ABC
Class TestStudent1 Id=20
{Public static void main(string args[]){ Name=xyz
Student s1=new student();
Student s2=new students();
S1.id=10;
S1.name=’ABC’;
System.out.println(“id=”+s1.id);
System.out.println(“Name=”+s1.name);
S2.id=20;
s2.name=’xyz’;
System.out.println(“id=”+s2.id);
System.out.println(“Name=”+s2.name);
}}
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name=“TINU";
10. System.out.println(s1.id+ " " +s1.name);//printing
members with a white space
11. }
12. }
Output:
101 TINU
File: TestStudent3.java
Output:
1. class Student{ 101 Sonoo
2. int id; String name; } 102 Amit
5. class TestStudent3{
6. public static void main(String args[]){
7. //Creating objects
8. Student s1=new Student();
9. Student s2=new Student();
10. //Initializing objects
11. s1.id=101;
12. s1.name="Sonoo";
13. s2.id=102;
14. s2.name="Amit";
15. //Printing data
16. System.out.println(s1.id+" "+s1.name);

17. System.out.println(s2.id+" "+s2.name);


2) Object and Class Example: Initialization through method
File: TestStudent4.java

class Student class TestStudent4


{ {
int rollno; public static void main(String args[])
String name; {
void insertRecord(int r, String n) Student s1=new Student();
{ Student s2=new Student();
rollno=r; s1.insertRecord(111,"Karan");
name=n; s2.insertRecord(222,"Aryan");
} s1.displayInformation();
void displayInformation() s2.displayInformation();
{ }
System.out.println(rollno+" "+name); }
}
}

Output:
111 Karan
222 Aryan
2) Object and Class Example: Initialization through method
3) Object and Class Example: Initialization through a constructor

In Java, a 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. In such
case, Java compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Rules for creating Java constructor

1. Constructor name must be the same as its class name


2. A Constructor should not have return type

Types of Java constructors


There are two types of constructors in Java:
3. Default constructor (no-arg constructor)
4. Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
1. <class_name>(){}

1. //Java Program to create and call a default constructor


2. class Bike1{
3. //creating a default constructor
4. Bike1()
5. {
6. System.out.println("Bike is created");}
7. //main method
8. public static void main(String args[]){
9. //calling a default constructor
10. Bike1 b=new Bike1();
11.
12. }
13. }
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a
default constructor.
Example of default constructor that displays the default values
1. //Let us see another example of default constructor
2. //which displays the default values
3. class Student3{
4. int id;
5. String name;
6. Student3()
7. {
8. Id=0;name=null;
9. }
10. //method to display the value of id and name
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. //creating objects
15. Student3 s1=new Student3();
16. Student3 s2=new Student3();
17. //displaying values of the object
18. s1.display();
19. s2.display();
20. }
21. }

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

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.
Constructor Overloading
// void display()
Java program to overload constructors {
class Student5 System.out.println(id+" "+name+" "+age);
{ }
int id;
String name; }
int age; Class DemoTest
//creating two arg constructor {
Student5(int i,String n) public static void main(String args[])
{ {
id = i; Student5 s1 = new Student5(111,"Karan");
name = n; Student5 s3 = new Student5(111,30);
} Student5 s2 = new Student5(222,"Aryan",25);
Student5(int i,int a) s1.display();
{ s2.display();
Id=i; }
Age=a; }
}
//creating three arg constructor Output
Student5(int i,String n,int a) 111 Karan 0
{ 222 Aryan 25
id = i;
name = n;
age=a;
}
Method Overloading

Class student Class demo


{ {
Int id,marks; Student s1=new student();
String name; Public static void main(string args[])
Void getdata(int I,int mark) {
{ S1.getdata(2,’xyz’);
Id=I; S1.getdata(2,85);
Marks=mark S1.getdata(3,67,’abc’);
} }
Void getdata(int I,string s) }
{
Id=I;
Name=s;
}
Void getdata(int I,int mark,string s)
{
Id=I;
Marks=mark;
Name=s;
}
Difference between constructor and method in Java

Java Constructor Java Method


A constructor is used to initialize the A method is used to expose the behavior of
state of an object. an object.

A constructor must not have a return A method must have a return type.
type.

The constructor is invoked implicitly. The method is invoked explicitly.

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

class Student{ class TestThis3{


int rollno; public static void main(String args[]){
String name; Student s1=new Student(111,"ankit",5000f);
float fee; Student s2=new Student(112,"sumit",6000f);
Student(int r,String n,float f){
rollno=r; s1.display();
name=n; s2.display();
fee=f; }}
}
void display() Output:
{System.out.println(rollno+" "+name+" "+fee);} 111 ankit 5000
112 sumit 6000
}

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";

Java String class provides a lot of methods to perform operations


on strings such as compare(), concat(), equals(), split(), length(),
replace(), compareTo(), intern(), substring() etc.
The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces
.
CharSequence Interface
The CharSequence interface is used to represent the sequence of
characters. String, StringBuffer and StringBuilder classes
implement it. It means, we can create strings in java by using
these three classes.
The Java String is immutable which means it cannot be changed.
Whenever we change any string, a new instance is created. For
mutable strings, you can use StringBuffer and StringBuilder
classes.
What is String 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:
1.By string literal
2.By new keyword
1) String Literal
Java String literal is created by using
double quotes. For Example:
1.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.
For example:
2.String s1="Welcome";
3.String s2="Welcome";//
It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will
not find any string object with the value "Welcome" in string constant
pool, that is why it will create a new object. After that it will find the
string with the value "Welcome" in the pool, it will not create a new
object but will return the reference to the same instance.
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects
are created if it exists already in the string constant pool).

2) By new keyword
1.String s=new String("Welcome");//
creates two objects and one reference variable

1.public class StringExample{


2.public static void main(String args[]){
3.String s1="java";//creating string by java string literal
4.char ch[]={'s','t','r','i','n','g','s'};
5.String s2=new String(ch);//converting char array to string
6.String s3=new String("example");//
creating java string by new keyword
7.System.out.println(s1);
8.System.out.println(s2);
9.System.out.println(s3);
10.}}
11.OUTPUT
12. java
13.strings
14.example
Java String compare
java string comparison
We can compare string in java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo() method),


reference matching (by == operator) etc.

There are three ways to compare string in java:

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) StringBuffer append() method


1.class StringBufferExample{
2.public static void main(String args[]){
3.StringBuffer sb=new StringBuffer("Hello ");
4.sb.append("Java");//now original string is changed
5.System.out.println(sb);//prints Hello Java
6.}
7.}
Output
Hello Java
2) StringBuffer insert() method
The insert() method inserts the given string with this string at
the given position.

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;

1) 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 program to demonstrate that a static member
// can be accessed before instantiating a class
class staticEx
{
// static method
static void m1()
{
System.out.println("from m1");
}

public static void main(String[] args)


{
// calling m1 without creating
// any object of class Test
m1();
}
}
Output:

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.

Why finalize method is used()?


finalize() method releases system resources before the garbage collector runs for a
specific object. JVM allows finalize() to be invoked only once per object.
Java.lang.Object.finalize() Method
Description
The java.lang.Object.finalize() is called by the garbage collector on an object when
garbage collection determines that there are no more references to the object.
public class Finally {
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("This is finally example");
Finally s1= new Finally();
s1=null;
System.gc();
}

}
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.

So, it provides a convenient way to check the behavior of the


program for the different values. You can pass N (1,2,3 and so
on) numbers of arguments from the command prompt

public class CommandLineExample{

public static void main(String[] args) {


// TODO Auto-generated method stub
System.out.println("Your first argument is:" +args[0]);
}

}
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]);
}
}

1.compile by > javac CommandLineExample2.java


2.run by > java CommandLineExample sonoo 1 2 HI

You might also like