Unit 2
Unit 2
Chapter-
Chapter-2
An object is a variable of class. The primary purpose to create an object of a class is to access the
members (data and methods) of class.
Example 1:
My name is abc
I am 20 years old
Example2:
class Student
{
String name;
int age;
void display()
{
System.out.println("My name is "+name);
System.out.println("I am "+ age+ " years old");
}
public static void main(String args[])
{
Student s=new Student();
s.name="xyz"; //accessing data using object
s.age=20;
s.display(); // accessing methods using object
}
}
Output:
My name is xyz
I am 20 years old
Example 3:
class Student
{
String name;
int age;
void accept(String n,int a)
{
name=n;
age=a;
Output:
My name is xyz
I am 20 years old
2. Constructor
A constructor initializes an object immediately upon the creation. This process is known as automatic
initialization of an object. Constructor is a special method that enables an object to initialize itself when it
is created
Properties of constructors:
Types of Constructor
1. Default constructor: A constructor without any argument is called default constructor. When user
does not write any constructor in program then all the objects are initialed by the data type with
default values.
2. Parameterized Constructor: A constructor with argument is called parameterized constructor.
class Rectangle
{
int length, width;
Rectangle() // default constructor
{
Output:
Area of Rectangle=200
class Rectangle
{
int length, width;
Rectangle(int a, int b) // parameterized constructor
{
length=a;
width=b;
}
int RectArea()
{
return(length*width);
}
public static void main (String args[])
{
Rectangle r1=new Rectangle(15,11); //calling parameterized constructor
int area1=R1.RectArea();
System.out.println(“Area1=”+area1);
}
}
Output:
Area of Rectangle=200
3. Nesting of methods:
Calling a method from another method is called as nesting of method. In following example max(int ,int)
is nested method as it is calling from display method.
class NestedDemo
{
int a=10;
int b=20;
void display()
{
System.out.println("Maximum is "+max(a,b));
}
int max( int a1,int b1)
{
if(a1>b1)
return(a1);
else
return(b1);
}
public static void main(String args[])
{
NestedDemo n=new NestedDemo ();
n.display();
}
}
Output:
Maximum is 20
4. This Keyword:
“this” keyword in Java is a special keyword which can be used to represent current object or instance of
any class in Java. “this” keyword can also call constructor of same class in Java and used to call
overloaded constructor. Here are few important points related to using this keyword in Java.
1) “this” keyword represent current instance of class: If member variable and local variable name
conflict than this can be used to refer member variable.
class Point
{
Here x,y are shadowed by a method or constructor parameter.But it could have been written like this:
class Point
{
int x = 0;
int y = 0;
Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local
copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.
2) “this” keyword can be used to call overloaded constructor in java. If used than it must be first statement
in constructor. Here is an example of using this() for constructor chaining:
class ThisDemo
{
int a;
int b;
ThisDemo()
{
this(10,20);
}
ThisDemo( int a,int b)
{
this.a=a;
this.b=b;
}
void display()
{
System.out.println("a=" +a+" "+"b="+b);
}
a=10 b=20
a=30 b=40
A command-line argument is the information that directly follows the program's name on the command
line when it is executed. Accessing the command-line arguments inside a Java program is quite easy.They
are stored as strings in the String array passed to main( ).
Example:
The following program displays all of the command-line arguments that it is called with:
Javac CommandLine.java
java CommandLine Hello how are you?
args[0]: Hello
args[1]: How
args[2]: are
args[3]: you?
import java.io.*;
public class Person
{
printf("%s", 50);
printf("%d %s %s", 250, "Hello", "World");
Varargs was added in Java 5 and the syntax includes three dots … (also called ellipses). Following is the
syntax of vararg method.
Notice the dots … in above code. That mark the last argument of the method as variable argument. Also
the vararg must be the last argument in the method.
Now let us check simple hello world varargs code.
Output:
Example2:
class VargsDemo
{
void display( String... args)
{
for(String a: args)
{
System.out.print( a + " ");
}
}
public static void main(String args[])
{
VargsDemo n1=new VargsDemo();
n1.display("hello","how","are","you?");
}
}
Output:
8. Finalize method
In java when class objects are created, the appropriate constructor is called but Java does not require a
destructor, because memory is not directly allocatable. However, class objects may still create conditions
that must be manually undone, such as closing files opened for I/O. In Java, classes may define a
method called finalize() . If finalize() exists for a class, it is called just before an instance of that class is
destroyed. The compiler generates a default finalize() method if a class does not provide one. Note that
the exact time that finalize() is called can never be predicted, simply because the exact time of garbage
collection (i.e., actual destruction of objects) cannot be predicted. Under some circumstances, such as
when the interpreter exits at the end of a program, it is possible that finalize() might never be called. Thus,
the programmer of a class should never rely on finalize()to do critical tasks. finalize() is only useful to
free system resources, such as open files and network connections. A finalizer method is declared by
naming it finalize() with no parameters and a void return value.
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. A subclass overrides the finalize method to
dispose of system resources or to perform other cleanup.
Syntax:
Following is the declaration for java.lang.Object.finalize() method
Example
The following example shows the usage of lang.Object.finalize() method.
Let us compile and run the above program, this will produce the following result:
9. Object Class
The Object class, in the java.lang package, sits at the top of the class hierarchy tree. Every class is a
descendant of the Object class. Every class you use or write inherits the instance methods of Object.
Following table is showing the methods of Object class. You need not use any of these methods, but, if
you choose to do so, you may need to override them with code that is specific to your class.
1 protected Object clone() This method creates and returns a copy of this object.
2 boolean equals(Object obj) This method indicates whether some other object is "equal to" this one.
3 protected void finalize() This method is called by the garbage collector on an object when
5 int hashCode() This method returns a hash code value for the object.
void notify() This method wakes up a single thread that is waiting on this object's
6
monitor.
void notifyAll() This method wakes up all threads that are waiting on this object's
7
monitor.
8 String toString() This method returns a string representation of the object.
void wait() This method causes the current thread to wait until another thread
9
invokes the notify() method or the notifyAll() method for this object.
This method causes the current thread to wait until either another
void wait(long timeout)
10 thread invokes the notify() method or the notifyAll() method for this
object, or a specified amount of time has elapsed.
This method causes the current thread to wait until another thread
void wait(long timeout, int
invokes the notify() method or the notifyAll() method for this object, or
11 nanos)
some other thread interrupts the current thread, or a certain amount of
real time has elapsed.
• The following table summarizes the visibility provided by various access modifiers.
11.Array
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the
same type. An array is used to store a collection of data, but it is often more useful to think of an array as
a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables.
To declare an array variable and initialize it to refer to a new instance, use the following syntax:
int[] data = new int [10];
or
The declaration of an array must include its type, but not its size. Arrays may be initialized with
conventional initialization syntax.
}
catch(Exception e)
{}
}
}
Output:
Example 2 : Accept and display data for array and display sum of array.
import java.io.*;
public class Person
{
}
}
Output:
import java.io.*;
public class Person
{
public static void main(String [] args)
{
int arr[][]=new int[2][2];
try
{
BufferedReader in=new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter elements of array");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
arr[i][j]=Integer.parseInt(in.readLine());
}
System.out.println("Elements are:");
for(int i=0;i<2;i++)
Output:
Enter elements of array
1
2
3
4
Elements are:
1
2
3
4
The Array Class:
The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing
arrays, and filling array elements. These methods are overloaded for all primitive types.
SN Methods Description
Searches the specified array of Object ( Byte, Int , double, etc.) for the
public static int
specified value using the binary search algorithm. The array must be
1 binarySearch(Object[] a,
sorted prior to making this call. This returns index of the search key, if
Object key)
it is contained in the list; otherwise, (-(insertion point + 1).
Returns true if the two specified arrays of longs are equal to one
another. Two arrays are considered equal if both arrays contain the
public static boolean same number of elements, and all corresponding pairs of elements in
2
equals(long[] a, long[] a2) the two arrays are equal. This returns true if the two arrays are equal.
Same method could be used by all other primitive data types (Byte,
short, Int, etc.)
3 public static void fill(int[] a, Assigns the specified int value to each element of the specified array of
int val) ints. Same method could be used by all other primitive data types
public static void Sorts the specified array of objects into ascending order, according to
4 sort(Object[] a) the natural ordering of its elements. Same method could be used by all
other primitive data types ( Byte, short, Int, etc.)
Example:
import java.util.Arrays;
class ArrayDemo
{
public static void main(String[] args)
{
int Arr[] = {2, 1, 9, 6, 4};
Arrays.sort(Arr);
int num = 4;
The String class represents character strings. All string literals in Java programs, such as "abc", are
implemented as instances of this class.
is equivalent to:
Constructor Description
String() Initializes a newly created String object so that it represents an empty
character sequence.
String(char[] value) Allocates a new String so that it represents the sequence of characters
currently contained in the character array argument.
String(String original) Initializes a newly created String object so that it represents the same
sequence of characters as the argument; in other words, the newly created
string is a copy of the argument string.
Following tables shows the methods of string class.Here s1 is object of sting class which is invoking the
built in methods of string class.
Example of toUpperCase()
class Example_UpperCase
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.println("Uppercase :"+str.toUpperCase());
}
}
Output:
Uppercase :HELLO
Example of toLowerCase()
class Example_LowerCase
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.println("LowerCase: "+str.toLowerCase());
}
}
Output:
Lowercase :hello
Example of trim()
class Example_Trim
{
public static void main(String args[])
{
String str=new String(" Hello Java");
System.out.println("Trimed String :"+str.trim());
}
Example of charAt)
class Example_CharAt
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.println("Char At 3:"+str.charAt(3));
}
}
Output:
Char At 3:l
Example of equals()
class Example_Equal
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.println("Are Hello & hello equal :"+str.equals("hello"));
}
}
Output:
Are Hello & hello equal :false
Example of equalsIgnoreCase()
class Example_EqualIgnoreCase
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.println("Are Hello & hello equal :"+str.equalsIgnoreCase("hello"));
}
}
Output:
Are Hello & hello equal : true
Example of Length()
class Example_Length
Example of replace()
class Example_Replace
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.prinitln("Replaced String:"+str.replace('H','C');
}
}
Output:
Replaced String:Cello
Example of compareTo()
class Example_CompareTo
{
public static void main(String args[])
{
String str=new String("Hello");
if(str.compareTo("hello")>0)
System.out.println("Hello is greater than hello");
else if(str.compareTo("hello")<0)
System.out.println("hello is greater than Hello");
else
System.out.println("Both are equal");
}
}
Output:
hello is greater than Hello
Example of concat()
class Example_Concat
{
public static void main(String args[])
Output:
Example of IndexOf()
class Example_IndexOf
{
public static void main(String args[])
{
String str=new String("Attitude");
System.out.println("Index Of 't' with 1 parameter: "+str.indexOf('t'));
System.out.println("Index Of 't' With 2 parameter :"+str.indexOf('t',3));
}
}
output:
Index Of 't' with 1 parameter:1
Index Of 't' With 2 parameter :4
Example of substring()
class Example_Substring
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.println("Substring with 1 parameter :"+str.substring(2));
System.out.println("Substring with 2 parameter :"+str.substring(2,4));
}
}
output:
StringBuffer Constructors:
Following tables shows the methods of StringBuffer class. Here s1 is object of sting class which is
invoking the built in methods of String class.
Example of setCharAt()
class Example_setCharAt
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Object_Language");
str.setCharAt(6,' ');
System.out.println("String="+str);
}
}
Output:
String=Object Language
Example of append()
class Example_Append
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Object Language");
System.out.println("AppendedString="+str.append(" is secure"));
}
}
Output: AppendedString= Object Language is secure
Example of Insert()
Output:
New String=Object Oriented Language
Example of setLength()
class Example_setlength
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Object");
System.out.println("Length="+str.length());
str.setLength(10);
System.out.println("Length="+str.length());
}
}
Output:
Length=6
Length=10
Example of Reverse()
class Example_reverse
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Hello");
System.out.println("String after reverse="+str.reverse());
}
}
Output:
String after reverse =olleH
Example of Replace()
class Example_replace
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Hello!!!");
System.out.println("String after replace="+str.replace(5,8,”***”));
}
Vectors are implemented with an array, and when that array is full and an additional element is added,
a new array must be allocated. Because it takes time to create a bigger array and copy the elements from
the old array to the new array, it is a little faster to create a Vector with a size that it will commonly be
when full. Of course, if you knew the final size, you could simply use an array. However, for non-critical
sections of code programmers typically don't specify an initial size. You must import either import
java.util.Vector; or import java.util.*;Following table shows the difference between array and vector.
Example1
import java.util.*;
class VectorDemo1
{
public static void main(String args[])
{
Vector v=new Vector();
int length=args.length;
for(int i=0;i<length;i++)
{
v.addElement(args[i]); //adding command line arguments
}
v.insertElementAt("COBOL",2);
Enumeration venum=v.elements();
System.out.println("Elements are");
while(venum.hasMoreElements())
System.out.println(venum.nextElement()+" ");
}
}
Example2:
import java.util.*;
class VectorDemo2
{
public static void main(String args[])
{
Vector v=new Vector();
v.addElement(new Integer (10)); //Adding elements at the end of vector
v.addElement(new Float (10.75));
v.addElement(new Character('a'));
v.addElement(new String("Hello"));
v.addElement(new String("Welcome"));
v.removeElementAt(1); //removing 2nd object
if(v.contains(new Integer(10))); //searching for an object
System.out.println("Found the object");
System.out.println("First and Last element of vector are:");
System.out.println(v.firstElement()); //showing first object
System.out.println(v.lastElement()); //showing last object
System.out.println("Elements of vector are:");
Enumeration venum=v.elements(); //showing all objects
while(venum.hasMoreElements())
System.out.println(venum.nextElement()+" ");
}
}
Output:
Found the object
First and Last element of Vector are:
10
Welcome
Elements of vector are:
10
a
Hello
Welcome
Initial size:0
Initial capacity:3
Capacity after four additions: 8
Capacity after one additions:8
Capacity after two additions:8
Capacity after one additions:8
Capacity after three additions:13
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12
import java.util.*;
}
}
Output:
1
2
3
4
In the above code, Integer class is known as a wrapper class (because it wraps around int data type to
give it an impression of object). To wrap (or to convert) each primitive data type, there comes a wrapper
class. Eight wrapper classes exist in java.lang package that represent 8 data types. Following list gives.
The image part with relationship ID rId14 was not found in the file.
All the 8 wrapper classes are placed in java.lang package so that they are implicitly imported and made
available to the programmer. As you can observe in the above hierarchy, the super class of all numeric
wrapper classes is Number and the super class for Character and Boolean is Object. All the wrapper
classes are defined as final and thus designers prevented them from inheritance.
int i=Integer.parseInt(str)
double d=Double.parseDouble(str)
Example(Day day)
{
this.day = day;
}
17. Inheritance
It is process of deriving a new class from derived class. A class that is derived from another class is called
a subclass (also a derived class, extended class, or child class). The class from which the subclass is
derived is called a superclass (also a base class or a parent class). When you want to create a new class
and there is already a class that includes some of the code that you want, you can derive your new class
from the existing class. In doing this, you can reuse the fields and methods of the existing class without
having to write them yourself.
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors
are not members, so they are not inherited by subclasses, but the constructor of the superclass can be
invoked from the subclass.
Single Level Inheritance
When there is one base class and one derived class the inheritance is called single level inheritance.
Following is the example of single level inheritance.
Person
name,age
Employee
designation,salary
class Person
{
String name;
int age;
Person(String n,int a)
{
name=n;
age=a;
}
void display()
{
System.out.println("Name="+name);
System.out.println("Age="+age);
}
}
class Employee extends Person
{
String emp_designation;
float emp_salary;
Employee(String p,int q,String r,float s)
{
super(p,q);
emp_designation=r;
emp_salary=s;
}
void display1()
{
display();
System.out.println("Employee Designation="+emp_designation);
System.out.println("Employee Salary="+emp_salary);
}
public static void main(String args[])
{
Employee e=new Employee("Akshay",18,"Manager",25000);
e.display1();
}
}
Output:
Name= Akshay
Age=18
Employee Designation= Manager
Employee Salary=25000
Account
cust_name,acc_no
Saving_acc
saving_bal,min_bal
Account_detail
Withdrawal,deposit
import java.io.*;
class Account
{
String cust_name;
int acc_no;
Account(String n,int no)
{
acc_no=no;
cust_name=n;
}
void display()
{
System.out.println(" Customer name = "+cust_name);
System.out.println(" Account number = "+acc_no);
}
}
class Saving_acc extends Account
{
int saving_bal;
int min_bal;
Saving_acc(String n,int no,int sbal,int mbal)
{
super(n,no);
saving_bal=sbal;
min_bal=mbal;
In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and
D inherits the same class A. A is parent class (or base class) of B,C & D.
Examples:
Class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
Class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
Class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
Class MyClass
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA()
obj1.methodB();
obj2.methodA()
obj2.methodC();
To create an overloaded method, provide different method definitions in a class, all with the same name,
but with the different parameter list. The difference may either be in the number or type of arguments,
that is each parameter list must be unique. The method's return type is not so much important as it does
not play any role in this.
when an overloaded method is called, Java first looks for a match between the arguments used to call the
method and the method's parameters.
Example
class person
{
String name;
int age;
void accept()
{
name="abc";
age=20;
}
void accept(String n,int a)
{
name=n;
age=a;
}
void display()
{
System.out.println("Name="+name);
System.out.println("Age="+age);
Output:
Area=200
Area=144
For eg: Demonstrates the concept of method overriding,the display() method is overridden.
class base
{
int a;
base(int a)
{
this.a=a;
}
void display() //method defined
{
System.out.println(“Base a=”+a);
}
}
class derived extends base
{
int y;
derived(int x,int y)
{
super(x);
this.y=y;
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run
time, rather than compile time. Dynamic Method Dispatch is related to a principle that states that an super
class reference can store the reference of subclass object. However, it can't call any of the newly added
methods by the subclass but a call to an overridden methods results in calling a method of that object
whose reference is stored in the super class reference.It simply means that which method would be
executed, simply depends on the object reference stored in super class object.
import java.io.*;
class Demo
{
void display() //method defined
{
System.out.println("Printing from Demo class");
}
}
class Example extends Demo
{
void display() //method defined again
{
Output:
Printing from Demo class
Printing from Example class
Printing from Example class
While method overriding is one of Java’s most powerful features, there will be times when you will want
to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at
the start of its declaration. Methods declared as final cannot be overridden. The following fragment
illustrates final:
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth() //Here error will occured
{
System.out.println("Illegal!");
}
}
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-time
error will result.
final class A
{
// ...
}
class B extends A //this will create error
{
//….
}
• The first calls the superclass’ constructor or to pass values to base class constructor.
• The second is used to access a member of the superclass that has been hidden by a member of a
subclass.
A subclass can call a constructor method defined by its superclass by using following form of super:
super(parameter-list);
Here, parameter-list specifies any parameters needed by the constructor in the superclass. super( ) must
always be the first statement executed inside a subclass’ constructor.
The second form of super acts somewhat like this, except that it always refers to the superclass of the
subclass in which it is used. This usage has the following general form:
super.member
This second form of super is most applicable to situations in which member names of a subclass hide
members by the same name in the superclass.
Following example is showing the use of super keyword for both purposes.
class base
{
int a;
base(int a)
{
Abstract class can have simple methods as well as abstract methods. Abstract methods are those methods
which are preceded by abstract keyword and user will declare them in abstract class the definition of
abstract method will be carried out in sub class.
Following table depicts the difference between class and abstract class
} }
Example:
public display()
{
System.out.println(“x=”+x);
}
}
Output:
x=10
Syntax:
static data_type variable_name;
Example:
class test
{
static int count;
void increase()
{
count++;
}
void display()
{
System.out.println("Count="+count);
}
public static void main(String array[])
{
test t1=new test();
t1.increase();
t1.display();
test t2=new test();
t2.increase();
t2.display();
}
}
Output:
Count=1
Count=2
One of commonly used static member function in java is main ().Static methods belong to entire class and
not a part of any objects of class. User can create a static function by precede the method definition with
static keyword. A static member function is invoked with class name rather than any object.
Synatx
static return_type function_name(argument list)
Example:
class Shape
{
static int length;
static int breath;
static double are;
static void area(int l)
Output:
Area of square:81.0
Area of rectangle:45.0