Course II_BCA NEP Syllabus Krupanidhi College
Unit - 2 Objects and Classes:
OBJECT IN JAVA
An entity that has state and behavior is known as an object
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.
Example of an object: Person
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.
Narasimha Murthy G K Page 1
Course II_BCA NEP Syllabus Krupanidhi College
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.
• fields are used to store data
• methods are used to perform some operations
//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;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
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);
}
}
Narasimha Murthy G K Page 2
Course II_BCA NEP Syllabus Krupanidhi College
CONSTRUCTOR IN JAVA
A constructor in Java is a special method having same name as the class and is
used to initialize objects.
The constructor is called when an object of a class is created. It can be used to
set initial values for object attributes.
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
If a constructor does not accept any parameters, it is known as a no-argument
constructor.
Narasimha Murthy G K Page 3
Course II_BCA NEP Syllabus Krupanidhi College
PARAMETERIZED CONSTRUCTOR
A constructor which has a specific number of parameters is called a parameterized
constructor.
Narasimha Murthy G K Page 4
Course II_BCA NEP Syllabus Krupanidhi College
FINALIZE METHOD
Finalize method in Java is an Object Class method that is used to perform cleanup
activity before destroying any object. It is called by Garbage collector before
destroying the object from memory. Finalize() method is called by default for every
object before its deletion.
The garbage collector is a part of Java Virtual Machine(JVM). Garbage collector checks
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.
Narasimha Murthy G K Page 5
Course II_BCA NEP Syllabus Krupanidhi College
STRING IN JAVA
Generally, String is a sequence of characters. But in Java, string is an object that
represents a sequence of characters.
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:
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
Narasimha Murthy G K Page 6
Course II_BCA NEP Syllabus Krupanidhi College
2) BY NEW KEYWORD
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory
Java String compare
There are three ways to compare String in Java:
1. By Using equals() Method
2. By Using == Operator
3. By compareTo() Method
1) By Using equals() Method
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
}
}
Narasimha Murthy G K Page 7
Course II_BCA NEP Syllabus Krupanidhi College
2) By Using == operator
The == operator compares references not values.
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) By Using compareTo() method
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.
Suppose s1 and s2 are two String objects. If:
s1 == s2 : The method returns 0.
s1 > s2 : The method returns a positive value.
s1 < s2 : The method returns a negative value.
class Teststringcomparison4
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
Narasimha Murthy G K Page 8
Course II_BCA NEP Syllabus Krupanidhi College
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 )
}
}
Java String class methods
The java.lang.String class provides many useful methods to perform operations on
sequence of char values.
Narasimha Murthy G K Page 9
Course II_BCA NEP Syllabus Krupanidhi College
CHARACTER CLASS IN JAVA
Java provides a wrapper class Character in java.lang package. An object of type
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.
CREATING A CHARACTER OBJECT:
Character ch = new Character('a');
The above statement creates a Character object which contains ‘a’ of type char.
Narasimha Murthy G K Page 10
Course II_BCA NEP Syllabus Krupanidhi College
Example Program
class CharecterDemo
{
public static void main(String args[])
{
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
}
Narasimha Murthy G K Page 11
Course II_BCA NEP Syllabus Krupanidhi College
StringBuffer Class
String in general is a sequence of characters that is immutable in nature. But java
provides a class called String Buffer using which programmer can create a string that is
mutable ( i.e. it can be changed. )in natu
Constructors of StringBuffer Class
Narasimha Murthy G K Page 12
Course II_BCA NEP Syllabus Krupanidhi College
Methods of StringBuffer class
Narasimha Murthy G K Page 13
Course II_BCA NEP Syllabus Krupanidhi College
Java File Class
The File class of the java.io package is used to perform various operations on files and
directories.
Create a Java File Object
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");
Java create files
To create a new file, we can use the createNewFile() method. It returns
• true if a new file is created.
•false if the file already exists in the specified location.
Narasimha Murthy G K Page 14
Course II_BCA NEP Syllabus Krupanidhi College
Example: Create a new File
// importing the File class
import java.io.File;
class Main {
public static void main(String[] args) {
// create a file object for the current location
File file = new File("newFile.txt");
try {
// trying to create a file based on the object
boolean value = file.createNewFile();
if (value) {
System.out.println("The new file is created.");
else {
System.out.println("The file already exists.");
catch(Exception e) {
Narasimha Murthy G K Page 15
Course II_BCA NEP Syllabus Krupanidhi College
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
Narasimha Murthy G K Page 16
Course II_BCA NEP Syllabus Krupanidhi College
#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.
Narasimha Murthy G K Page 17
Course II_BCA NEP Syllabus Krupanidhi College
THIS REFERENCE
In Java, this is a reference variable that refers to the current object.
this can also be used to:
Invoke current class constructor
Invoke current class method
Return the current class object
Pass an argument in the method call
Pass an argument in the constructor call
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);
Narasimha Murthy G K Page 18
Course II_BCA NEP Syllabus Krupanidhi College
s1.display();
s2.display();
}
}
Output:
111 ankit 5000.0
112 sumit 6000.0
2)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.
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
Narasimha Murthy G K Page 19
Course II_BCA NEP Syllabus Krupanidhi College
STATIC KEYWORD IN JAVA
The static keyword in Java is mainly used for memory management.
The static keyword is a non-access modifier in Java that is applicable for the
following:
1. Variables
2. Blocks
3. Methods
STATIC VARIABLES
If you declare any variable as static, it is known as a static variable.
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.
//Java Program to demonstrate the use of an instance variable
//which get memory each time when we create an object of the clas
s.
class Counter{
int count=0;//will get memory each time when the instance is creat
ed
Counter(){
count++;//incrementing value
System.out.println(count);
}
public static void main(String args[]){
//Creating objects
Narasimha Murthy G K Page 20
Course II_BCA NEP Syllabus Krupanidhi College
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
STATIC BLOCK
o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.
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;
}
Narasimha Murthy G K Page 21
Course II_BCA NEP Syllabus Krupanidhi College
public static void main(String args[])
{
int result=Calculate.cube(5);
System.out.println(result);
}
}
Narasimha Murthy G K Page 22