ch2 Java Ischeme
ch2 Java Ischeme
Chapter 2 Marks-18
Derived Syntactical Constructs in Java
2.1 Constructor
It is easy and simple to initialize an object when it is created. Java supports a special type of
method called constructor.
Java allows objects to initialize themselves when they are created. This automatic initialization
is performed through the use of a constructor.
A constructor initializes an object immediately upon creation. It has the same name as the class
in which it resides.
Once defined, the constructor is automatically called immediately after the object is created.
They have no return type, not even void. This is because the implicit return type of a
constructor is the class type itself.
Syntax: classname (parameter-list)
{
//body of the constructor
}
Types of Constructor:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
Constructor without parameter is known as default constructor.
Constructor with parameter is known as parameterized constructor
Constructor with object as parameter is known as copy constructor.
For example:
class Student
{
int rollno;
String name;
Student (int r, String n) //constructor
{
rollno =r;
name =n;
}
}
{
rollno =1;
name =”Samarth”;
}
void display()
{
System.out.println("Roll no : "+ rollno); Output:
System.out.println("Name : "+ name);
} Roll no : 1
} Name : samarth
class StudentDemo
{
public static void main(String args[])
{
Student s = new Student(1,”Samarth”);
s.display();
}
}
Parameterized Constructor
Constructor which takes some arguments then it is called as parameterized constructor
class Student
{
int rollno;
String name;
Student (int r, String n) //parameterized constructor
{
rollno =r;
name =n;
}
void display()
{
System.out.println("Roll no : "+ rollno); Output:
System.out.println("Name : "+ name);
} Roll no : 1
} Name : samarth
class StudentDemo
{
public static void main(String args[])
{
Student s = new Student(1,”Samarth”);
s.display();
}
}
2
Java Programming(22412) Chapter-2
Copy Constructor
Constructor which takes object as parameter then it is called as copy constructor. It is special
form of parameterized constructor.
void display()
{
System.out.println("Roll no : "+ rollno); Output:
System.out.println("Name : "+ name);
} Roll no : 1
} Name : samarth
class StudentDemo
{
public static void main(String args[])
{
Student s = new Student(1,”Samarth”);
Student s1=new Student(s);
s1.display();
}
}
Constructor overloading
Overloading refers to the use of same name for different purposes.
A class can have more than one constructor but with different parameters. This is known as
constructor overloading.
The constructor which contains parameters is called as parameterized constructor else it is a
default constructor. A default constructor is called upon the creation of object.
3
Java Programming(22412) Chapter-2
Nesting of Methods
When a method in java calls another method in the same class, it is called Nesting of methods.
void display()
{
System.out.println(“Length:"+len);
System.out.println(“Breadth:"+bre);
}
void perimeter()
{
display(); //nested call
int pr = 2 * (len+ bre);
System.out.println("Perimeter:"+pr);
}
public static void main(String[] args)
{
NestMethod obj = new NestMethod(10,20);
obj.perimeter();
}
}
}
3) ‘this’ to call one constructor from another constructor:
‘this’ keyword is can be used to call one constructor from another constructor.
For example:
class Planet
{
long distance, satellite;
int oneDay;
Planet () //constructor1
{
satellite = 0;
oneDay = 24;
}
Planet (long x) //constructor2
{
this();
distance = x;
}
}
Methods overloading
In Java it is possible to define two or more methods within the same class that are having the
same name, but their parameter declarations are different. In the case, the methods are said to
be overloaded, and the process is referred to as method overloading.
Overloading is one of the ways of Java implementation of polymorphism.
When an overloaded method is called, Java uses the type and/or number of arguments to
determine which version of the overloaded method to actually call. Thus, overloaded methods
must differ in the type and/or number of their parameters.
When Java encounters a call to an overloaded method, it simply executes the version of the
method whose parameters match the arguments used in the call.
6
Java Programming(22412) Chapter-2
return(len * wid);
}
}
class Shape
{
public static void main(String args[])
{
Area s = new Area();
int x=s.area(10);
System.out.println ("Area of square : "+x);
int y=s.area(10,20);
System.out.println ("Area of rect: "+y);
float z = s.area(5.5f);
System.out.println ("Area of circle : "+z);
}
}
Garbage Collection
Garbage means unreferenced objects.
8
Java Programming(22412) Chapter-2
The process of removing unused objects from heap memory is known as Garbage
collection and this is a part of memory management in Java.
C/C++ don’t support automatic garbage collection.
But, in java it is performed automatically. So, java provides better memory management.
JVM performs garbage collection.
Objects are dynamically allocated by using the new operator.
It works like this: when no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be reclaimed.
The garbage collector runs periodically, checking for objects that are no longer referenced by
any running state.
We can request to JVM for garbage collection by calling System.gc() method
The Garbage collector of JVM collects only those objects that are created by new keyword.
Advantage of Garbage Collection
1. It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
2. It is automatically done by the garbage collector(a part of JVM)
When does java perform garbage collection?
1. When the object is no longer reachable
Book obj = new Book();
obj = null;
2. When one reference is copied to another reference
Book obj1 = new Book();
Book obj2 = new Book();
obj2 = obj1;
Example:
class A
{
int p;
A()
{
p = 0;
}
public static void main(String args[])
{
A a1= new A();
A a2= new A();
a2=a1; // deallocates the memory of object a1
}
}
9
Java Programming(22412) Chapter-2
Finalize() method:
It is a method used for Garbage Collection.
The finalize() method called by the garbage collector on an object when garbage collection
determines that there are no more reference to the object.
The finalize() method is invoked each time before the object is garbage collected
finalize() method is defined in Object class.
In order to free the resources hold by an object, finalize () method is called.
If we have created any object without new, we can use finalize method to perform cleanup
processing
It performs actions same as of destructor in c++.
General form of finalize() method
protected void finalize() throws Throwable
{
//finalization code
}
Object Class
Defined in java.lang package
It is the parent class of all the classes in java by default. It is the topmost class of java.
It is beneficial if we want to refer any object whose type we don't know.
Declaration for Object class foll. Constructor is used −
Object()
Methods of Object class
Method Description
returns the Class class object of this object. The Class class
public final Class getClass()
can further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws
creates and returns the exact copy (clone) of this object.
CloneNotSupportedException
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait()throws causes the current thread to wait, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).
10
Java Programming(22412) Chapter-2
protected void finalize()throws invoked by the garbage collector before object is being
Throwable garbage collected.
package p2;
import p1.*;
class B
{
public static void main(String args[])
11
Java Programming(22412) Chapter-2
{
A obj = new A;
obj.display();
}
}
2) Default access or friendly access
Also known as package access or friendly access
When no access modifier is specified for a class, method or data member – It is said to be
having the default access modifier by default.
They are accessible only within the same package
It is limited version of public access.
Difference between public and friendly access:
public modifier makes fields visible in all classes regardless of their package, while friendly
access makes fields visible only in the same package.
For example,
int val;
void display();
package p2;
import p1.*;
class Demo
{
public static void main(String args[])
{
A obj = new A ();
obj.display();
}
}
Accessing class A from package p1 into p2 gives compile time error.
3) protected access
12
Java Programming(22412) Chapter-2
package p2;
import p1.*; //importing all classes in package p1
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}
}
4) private access
Private access modifier is specified using the keyword private.
It provides highest degree of protection. They cannot be inherited by subclasses.
The methods or data members declared as private are accessible only within the class in
which they are declared.
Any other class of same package will not be able to access these members.
For example: private int val;
private void display();
{
System.out.println("Hello");
}
}
class B
{
public static void main(String args[])
{
A obj = new A();
obj.display(); //trying to access private method
}
}
5) private protected access
This modifier makes the fields visible in all subclasses regardless of package.
For example:
private protected int val;
private protected void display();
Access Modifier
Public Protected Default Private
Access Location
Same Class Yes Yes Yes Yes
Subclass in same
Yes Yes Yes No
package
Non Subclasses in
Yes Yes Yes No
same package
Subclass in other
Yes Yes No No
package
Non Subclasses in
Yes No No No
other package
Figure: Visibility Controls
2.3 Array, Strings and Vectors
Arrays
An array is a collection of homogeneous or contiguous or related data items that share a
common name. It offers the convenient means of grouping information.
In Java, arrays are objects. Arrays can be of primitive data types or reference types.
14
Java Programming(22412) Chapter-2
Here datatype declares the base type of the array. Thus datatype determines the type of the
data that the array can hold. ‘arrayname’ is the combined name given to the array.
The set of first empty square brackets specifies that the variable of type array is created
but actual memory is not allocated to it. In order to allocate the physical memory to the
array the new operator is used. The ‘size’ determines number of elements in the array.
The index number of the array always starts with 0.
15
Java Programming(22412) Chapter-2
For example:
int val[ ] = new int[5];
This declaration will create five int variables in a contiguous memory locations referred by
the common name ‘val’.
the compiler will reserve five storage memory locations of 4 bytes each for storing integer
variables as,
Individually, these memory locations are referred as a single variable name as,
val [0] = 36;
val [1] = 26;
val [2] = 78;
val [3] = 3;
val [4] = 95;
This would cause the array ‘val’ to store the values as shown below.
Array initialization
When an array is created, each element of the array is set to the default initial value for
its type. Putting the values inside the array is called as array initialization.
When we initialize the array inside the program known as compile time initialization
and when it is initialized by taking the values as input from keyboard it is called as run
time initialization.
Two ways:
1) Direct Initialization:
We can also initialize array automatically in the same way as the ordinary variables
when they are declared, as shown below:
For Example: int num[ ] = { 45, 12, 56, 10, 20, 86, 19, 46, 30 } ;
For example:
val [0] = 36;
val [1] = 26;
val [2] = 78;
val [3] = 3;
val [4] = 95;
Array length
All arrays store the allocated size in an attribute named length.
After the creation of the array, compiler will automatically decide the size of the array.
This size or length or number of elements of the array can be obtained using attribute
‘length’.
Syntax:
arrayname.length;
For example:
int arr[ ] = {8, 6, 2, 4, 9, 3, 1};
int size = arr.length;
The variable ‘size’ will contain value 7.
17
Java Programming(22412) Chapter-2
For example:
int table[ ][ ] = new int[3][4];
This will create total 12 storage locations for two dimensional arrays as,
Like one dimensional arrays, two dimensional arrays can also be initialized at compile time
as,
int table[2][2] = {8, 5, 9, 6};
It will initialize the array as shown below,
String class
In Java a string is a sequence of characters. Java implements strings as objects of type String.
When you create a String object, you are creating a string that cannot be changed. That is
Strings are immutable. Modifiable strings are using StringBuffer class.
Implementing strings as built-in objects allows Java to provide convenient string handling.
For example, Java has methods to compare two strings, search for a substring, concatenate two
strings, and change the case of letters within a string.
String class is defined in java.lang package.
2)Using constructor:
i)String()
creates empty string
ex: String str=new String();
iv)Sring(StringBuffer buffer) :
Initializes a new string from the string in buffer.
ex: StringBuffer buffer = new StringBuffer(“Java");
String s = new String(buffer);
v) Sring(String s) :
Initializes a new string from the string
ex: String s= new String(“Java");
19
Java Programming(22412) Chapter-2
String s1 = “First”;
String s2 = “Second”;
String s3=s1.concat (s2);
The contents of the string ‘s3’ will be “FirstSecond” after the execution of these statements.
The operator + can also be used to join two strings together. We have used this operator
several times in program for the same purpose.
For example:
String s = “How ” + “are ” + “you ?”;
String x = “Number = ” + 2;
3) charAt( )
This method extracts a single character from the string.
Syntax:
char charAt(int index)
It extracts the character of invoking String from position specified by ‘index’.
For Example:
String s = “Indian”;
char ch = s.charAt(2); //ch will be ‘d’ after this
4) toCharArray()
It converts all the characters of the string into the character array.
Syntax:
char[ ] toCharArray( )
For example , String s = “Programming”;
char ch[ ] = s.toCharArray();
5) equals()
It is used to check two strings for equality and returns the boolean value true if they are
equal else false.
The equals( ) is case sensitive.
Syntax:
boolean equals(String str)
Example:
String a = “Hello”;
String b = “HELLO”;
boolean res=a. equals(b); //false
The result will be false because both strings are not equals in case.
6) equalsIgnoreCase()
It is used to check two strings for equality and returns the boolean value true if they are
equal else false.
The equalsIgnoreCase( ) is not case sensitive method.
20
Java Programming(22412) Chapter-2
Syntax:
boolean equalsIgnoreCase(String str)
Example:
String a = “Hello”;
String b = “HELLO”;
boolean res=a. equalsIgnoreCase(b) ; //true
The result will be true because both strings are equals in characters
7) compareTo( ) and compareToIgnoreCase( )
It is used to check whether one string is greater than, less than or equal to another string or
not.
In such cases the compareTo( ) or compareToIgnoreCase() method can be used.
compareTo( ) is case-sensitive and compareToIgnoreCase( ) is case insensitive.
Syntax:
int compareTo(String str)
int compareToIgnoreCase(String str)
It will return an integer value. When,
value < 0 then invoking string is less than str
8) indexOf()
If we want to search a particular character or substring in the string then this method can be
used. This method returns the index of the particular character or sting which is searched.
It can be used in different ways.
1) int indexOf(char ch)
2) int indexOf(String str)
First method searches first occurrence of the character from the string. Second method
searches first occurrence of the substring from another string.
1) int indexOf(char ch, int startIndex)
2) int indexOf(String str, int startIndex)
21
Java Programming(22412) Chapter-2
9) lastIndexOf()
If we want to search a last index of particular character or substring in the string then this
method can be used. This method returns the last index of the particular character or sting
which is searched.
It can be used in different ways.
1) int lastIndexOf(char ch)
2) int lastIndexOf(String str)
First method searches last occurrence of the character from the string. Second method
searches last occurrence of the substring from another string.
Example:
String s = “Maharashtra”;
int nn = s.lastIndexOf(‘a’); //nn will be 10
int mn = s.lastIndexOf(“ra”); //mn will be 9
10) substring( )
It is used to extract a substring from the string. It has two different forms:
1) String substring(int start)
2) String substring(int start, int end)
The first form extracts substring from ‘start’ to end of the string. Second form extracts the
substring from position ‘start’ to the position ‘end’ of the invoking string.
Example:
String str = “Are you a Marathi guy”;
String s = s.substring (10); //s will be “Marathi guy”
String t = s.substring (10,16); //t will be “Marathi”
11) replace()
This method is used to replace all the occurrences of a character with another character of
the string.
Syntax:
String replace(char original, char replacement)
Here ‘original’ is character to be replaced and ‘replacement’ is new character exchanged
instead of that.
Example:
22
Java Programming(22412) Chapter-2
StringBuffer class
Using String class we cannot change the characters form string but using StringBuffer class we
can modify the characters of the string.
We can insert new characters, modify them delete them at any location of string of can append
another string to other end. So StringBuffer provides the flexible string that can be modified in
any way.
StringBuffer represents growable and writeable character sequences.
StringBuffer will automatically grow to make room for such additions and allocates more
characters than actually needed.
Creating StringBuffer
StringBuffer class defines three different constructors:
1) StringBuffer()
2) StringBuffer(int size)
3) StringBuffer(String str)
The first form i.e. default constructor reserves room for 16 characters without reallocation.
The second form accepts an integer argument that explicitly sets the size of the buffer with
given value.
The third form accepts a String argument that sets the initial contents of the StringBuffer object
and reserves room for 16 more characters without reallocation.
24
Java Programming(22412) Chapter-2
2) capacity( )
The total allocated capacity can be found through the capacity ( ) method.
Syntax:
int capacity( )
Example:
StringBuffer sb = new StringBuffer("India");
int cap = sb.capacity()); //cap will be 21
Here the variable cap will contain capacity 21 i.e. actual length + additional room for 16
characters.
3) setLength( )
It is used to set the length of the buffer within a StringBuffer object.
Syntax:
void setLength(int len)
Here, len specifies the length of the buffer. This value must be nonnegative.
When we increase the size of the buffer, null characters are added to the end of the existing
buffer.
If we call setLength( ) with a value less than the current value returned by length( ), then
the characters stored beyond the new length will be lost.
Example:
StringBuffer sb=new StringBuffer(“Solapur”);
sb.setLength(3); // now sb object contains only 3 chars
4) setCharAt( )
If we want to set the character at certain index in the StringBuffer with specified value, this
method can be used.
Syntax:
void setCharAt(int index, char ch)
Here, ‘index’ is the position within StringBuffer whose value is to be set with value ‘ch’.
Example:
StringBuffer sb = new StringBuffer(“Kolkata”);
sb.setCharAt(0,‘C’);
After execution of these statements, ‘sb’ will be “Colkata”.
5) append( )
The append( ) method concatenates the string representation of any other type of data to the
end of the invoking StringBuffer object.
25
Java Programming(22412) Chapter-2
Syntax:
StringBuffer append(datatype var)
Example:
StringBuffer sb = new StringBuffer("cricket");
int x = 52;
StringBuffer a = sb.append(x); //a will be “cricket52”
6) insert( )
This method is used to insert one string, character or object into another string.
Syntax:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
Here the ‘index’ specifies the index position at which point the string will be inserted into
the invoking StringBuffer object.
Example:
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "love ");
After this, the contents of ‘sb’ will be “I love Java!”
7) reverse( )
We can reverse the characters inside the StringBuffer using reverse( ) method.
Syntax:
StringBuffer reverse()
This method returns the reversed object upon which it is called.
Example:
StringBuffer s = new StringBuffer(“Yellow”);
s.reverse(); //s will be “wolleY”
8) delete() and deleteCharAt( )
These methods are used to delete a single character or a sequence of characters from the
StringBuffer.
Syntax:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
The delete( ) method deletes a sequence of characters from the invoking object. It deletes
character from ‘startIndex’ to ‘endIndex’–1.
The deleteCharAt( ) method deletes the character at the index specified by ‘loc’.
Example:
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7); //sb will be “This a test”
sb.deleteCharAt(0); //sb will be “his a test”
26
Java Programming(22412) Chapter-2
The first form creates a default vector, which has an initial size of 10. The second form creates
a vector whose initial capacity is specified by ‘size’ and the third form creates a vector whose
initial capacity is specified by ‘size’ and whose increment is specified by ‘incr’.
The increment specifies the number of elements to allocate each time when new elements are
added in the vector.
A vector without size can accommodate an unknown number of items.
Example:
Vector v=new Vector (5);
Above statement creates vector with initial capacity 5.
Advantages of vector over arrays:
1. It is convenient to use vectors to store objects.
27
Java Programming(22412) Chapter-2
2. A vector can be used to store a list of objects that may vary in size.
3. We can add and delete objects from the list as when required.
4. The objects do not have to be homogeneous.
5. Vector implements dynamic array.
6. Dynamically grows or shrinks as required
Disadvantages of vector :
1) A vector is an object, memory consumption is more.
Vector operations and methods
Method Description
Adds the item specified to the vector list at the end.
void addElement(Object item) Ex: v.addElement(10);
v.addElement(10.6);
Returns the object stored at specified index.
Object elementAt(int index)
Ex: Object ob=v.elementAt(4);
Returns the number of elements currently in the vector.
int size()
Ex: int s=v.size();
Returns the capacity of the vector.
int capacity()
Ex: int c=v.capacity();
void removeElement(Object Removes the specified item from the vector.
item) Ex: v.removeElement(10);
Removes the item stored at the specified index position
void removeElementAt(int
from the vector.
index)
Ex: v.removeElementAt(2);
Remove all the elements from the vector.
void removeAllElements()
Ex: v.removeAllElement();
Copies all the elements from vector to array.
void copyInto(datatype array[])
Ex: v.copyInto(array);
void insertElementAt(Object Inserts the element in vector at specified index position.
item, int index) Ex: v.insertElementAt(20,2);
Returns the first element of the vector.
Object firstElement()
Ex: Object f=v.firstElement();
Object lastElement() Returns the last element of the vector.
28
Java Programming(22412) Chapter-2
29
Java Programming(22412) Chapter-2
The following two statements illustrate the difference between a primitive data type and an
object of a wrapper class.
int x = 25;
Integer y = new Integer(33);
30
Java Programming(22412) Chapter-2
The first statement declares an int variable named x and initializes it with the value 25. The
second statement instantiates an Integer object. The object is initialized with the value 33 and a
reference to the object is assigned to the object variable y.
}
}
}
33
Java Programming(22412) Chapter-2
Write a program to create a class Circle and calculates area and perimeter of
circle.
import java.util.Scanner;
class Circle
{ Output:
int radius;
float perimeter; Enter radius: 5
float area; Perimeter: 31.400002
} Area: 78.5
class MyCircle
{
public static void main(String args[])
{
final float pi = 3.14f;
Circle c = new Circle ();
Scanner in = new Scanner (System. in);
System.out.println ("Enter radius: ");
c.radius = in.nextInt ();
c.perimeter = 2 * pi * c.radius;
c.area = pi * c.radius * c.radius;
System.out.println ("Perimeter: "+c.perimeter);
System.out.println ("Area: "+c.area);
}
}
Write a program to create a vector with seven elements as (10, 30, 50, 20, 40,
10, 20). Remove element at 3rd and 4th position. Insert new element at 3rd
position. Display the original and current size of vector.
import java.util.*;
public class VectorDemo
{
public static void main(String args[])
{
Vector v = new Vector();
v.addElement(10);
v.addElement(20));
v.addElement(30);
v.addElement(40);
v.addElement(10);
v.addElement(20);
System.out println(v.size()); // display original size
34
Java Programming(22412) Chapter-2
Define a class ‘employee’ with data members empid, name and salary. Accept
data for five objects using Array of objects and print it.
import java.util.*;
class Employee
{
int empid;
String name;
double salary;
void getdata()
{
Scanner sc=new Scanner(System.in);
Write a program to accept a number as command line argument and print the
number is even or odd.
class EvenOdd
{
public static void main(String args[])
{
int no=Integer.parseInt(args[0]);
if (no%2==0)
{
System.out.println("Even Number");
}
else
{
System.out.println("Odd Number");
}
}
}
Write a program to accept a number as command line argument and print the
square
class Square
{
public static void main(String args[])
{
int no=Integer.parseInt(args[0]);
System.out.println("Square="+(no*no));
}
}
6) List various wrapper classes. Give any four methods of Integer wrapper class.
7) What is difference between array and vector ? Explain elementAt ( ) and
addElement ( ) method.
8) Write a program to accept number from user and convert into binary by using wrapper
class methods
9) Write a program to accept a number as command line argument and print the number is
even or odd.
10) Write a program to accept a number as command line argument and print the square
11) Write a program to create a vector with seven elements as (10, 30, 50, 20, 40, 10, 20).
Remove element at 3rd and 4th position. Insert new element at 3rd position. Display the
original and current size of vector.
12) Define a class item having data member code and price. Accept data for one object and
display it.
13) Define a class person with data member as Aadharno, name, Panno implement concept
of constructor overloading. Accept data for one object and print it.
14) Define wrapper class. Give the following wrapper class methods with syntax and use:
1) To convert integer number to string.
2) To convert numeric string to integer number.
3) To convert object numbers to primitive numbers using typevalue() method.
15) Write a program to demonstrate the following
i) to convert lower case string to upper case. ii) to compare two strings.
37