Unit2 Java
Unit2 Java
OBJECT IN JAVA
An object consists of :
1. State: It is represented by attributes of an object. It also reflects the properties of
an object.
2. Behavior: It is represented by methods of an object. It also reflects the response of
an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact
with other objects.
CLASSES IN JAVA
A class is a user defined blueprint or prototype from which objects are created.
It represents the set of properties or methods that are common to all objects of one
type.
We can create a class in Java using the class keyword class
Class Name {
// fields
// methods
}
Here, fields (variables) and methods represent the state and behavior of the object
respectively.
CONSTRUCTOR IN JAVA
A constructor in Java is a special method having same name as the class and is
class Bike
{
Bike()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike b=new Bike();
}
There are three types of constructors:
1. No-arg constructor
2. Parameterized.
NO-ARGUMENT CONSTRUCTOR
PARAMETERIZED CONSTRUCTOR
FINALIZE METHOD
Finalize method in Java is an Object Class method that is used to perform cleanup
the heap memory, where all the objects are stored by JVM, looking for unreferenced
objects that are no more needed. And automatically destroys those objects. Garbage
collector calls finalize() method for clean up activity before destroying the object. Java
does garbage collection automatically; there is no need to do it explicitly, unlike other
programming languages.
The garbage collector in java can be called explicitly using the following method:
System.gc()
System.gc() is a method in java that invokes garbage collector which will destroy the
unreferenced objects. System.gc() calls finalize() method only once for each object.
STRING IN JAVA
1. By string literal
2. By new keyword
1) STRING LITERAL
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:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
2) BY NEW KEYWORD
In such case, JVM will create a new string object in normal (non-pool) heap memory
The String class equals() method compares the original content of the string. It
compares values of string for equality.
class Teststringcomparison1
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
2) By Using == operator
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)
}
}
The String class 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.
class Teststringcomparison4
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Character contains a single field, whose type is char. The Character class offers a
number of useful class (i.e., static) methods for manipulating characters.
Example Program
class CharecterDemo
{
System.out.println(Character.isLetter('7'));//false
System.out.println(Character.isDigit('7'));//true
System.out.println(Character.isWhitespace(' '));//true
System.out.println(Character.isWhitespace('a'));//false
System.out.println(Character.isUpperCase('D'));//true
System.out.println(Character.toUpperCase('n'));//N
}
StringBuffer Class
The File class of the java.io package is used to perform various operations on files and
directories.
A File object is created by passing in a string that represents the name of a file, a
String, or another File object
File a = new File("/usr/local/bin/geeks");
import java.io.File;
class Main {
try {
if (value) {
else {
catch(Exception e) {
e.getStackTrace();
ACCESS MODIFIERS
Access modifiers in Java allow us to set the scope or accessibility or visibility of a data
member be it a field, constructor, class, or method.
There are four access modifiers keywords in Java and they are:
#1) Default: Whenever a specific access level is not specified, then it is assumed to be
‘default’. The scope of the default level is within the package.
A default access modifier in Java has no specific keyword. Whenever the access modifier
is not specified, then it is assumed to be the default. The entities like classes, methods,
and variables can have a default access.
A default class is accessible inside the package but it is not accessible from outside the
package i.e. all the classes inside the package in which the default class is defined can
access this class.
Similarly a default method or variable is also accessible inside the package in which they
are defined and not outside the package
#2) Public: This is the most common access level and whenever the public access
specifier is used with an entity, that particular entity is accessible throughout from within
or outside the class, within or outside the package, etc.
#3) Protected: The protected access level has a scope that is within the package. A
protected entity is also accessible outside the package through inherited class or child
class.
The methods or data members declared as protected are accessible within the same
package or subclasses in different packages.
#4) Private: When an entity is private, then this entity cannot be accessed outside the
class. A private entity can only be accessible from within the class.
The methods and fields that are declared as private are not accessible outside the class.
They are accessible only within the class which has these private entities as its members.
Note that the private entities are not even visible to the subclasses of the class. A private
access modifier ensures encapsulation in Java.
THIS REFERENCE
Example Program
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();
}
}
Output:
The this() constructor call can be used to invoke the current class constructor. It is used
to reuse the constructor.
class A{
A()
{
System.out.println("hello a");
}
A(int x)
{
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[])
{
A a=new A(10);
}
}
Output:
hello a
10
The static keyword is a non-access modifier in Java that is applicable for the
following:
1. Variables
2. Blocks
3. Methods
STATIC VARIABLES
o 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.
o The static variable gets memory only once in the class area at the time of class
loading.
Counter(){
count++;//incrementing value
System.out.println(count);
}
}
}
STATIC BLOCK
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
STATIC METHOD
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a
class.
o A static method can access static data member and can change the value of it.
class Calculate{
static int cube(int x)
{
return x*x*x;
}