0% found this document useful (0 votes)
16 views37 pages

ch2 Java Ischeme

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views37 pages

ch2 Java Ischeme

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Java Programming(22412) Chapter-2

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

Write a program to illustrate the use of constructor


class Student
{
int rollno;
String name;
Student () //Default constructor
1
Java Programming(22412) Chapter-2

{
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

Write a program to illustrate the use of 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.

Write a program to illustrate the use of copy constructor


class Student
{
int rollno;
String name;
Student (int r, String n) //parameterized constructor
{
rollno =r;
name =n;
}
Student (Student s) //copy constructor
{
rollno =s.rollno;
name =s.name;
}

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

 Write a program to illustrate constructor overloading


class Rectangle
{
int length, breadth;
Rectangle () //default constructor
{
length=5;
breadth=5;
}
Rectangle (int l, int b) //parameterized constructor
{
length=l;
breadth=b;
}
void display()
{ Output:
System.out.println ("\nLength="+length);
System.out.println ("Breadth="+breadth); Length=5
} Breadth=5
}
class ConstructorDemo Length=10
{
Breadth=20
public static void main(String args[])
{
Rectangle r1=new Rectangle (); //invokes default constructor
Rectangle r2=new Rectangle (10, 20); //invokes parameterized constructor
r1.display ();
r2.display ();
}
}

Nesting of Methods
 When a method in java calls another method in the same class, it is called Nesting of methods.

 Write a program to illustrate nesting of methods


class NestMethod
{
int len,bre;
NestMethod(int l, int b)
{
len=l;
bre=b;
}
4
Java Programming(22412) Chapter-2

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

The ‘this’ keyword


 Many times it is necessary to refer to its own object in a method or a constructor. To allow this
Java defines the ‘this’ keyword.
 Uses of this keyword:
1) ‘this’ can be used inside any method to refer to the current object.
 For example:
Box(double w, double h, double d)
{
this. width = w;
this. height = h;
this. depth = d;
}
Inside Box( ), this will always refer to the invoking object.

2) ‘this’ to resolve instance variable hiding :


 ‘this’ keyword is used to differentiate between instance and local variables. This
concept is also referred as ‘Instance variable hiding’. When a local variable has the
same name as an instance variable, the local variable hides the instance variable.
 Example
Box(double width, double height, double depth)
{
this. width = width;
this. height = height;
this. depth = depth;
5
Java Programming(22412) Chapter-2

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

 Write a program to illustrate method overloading


class Area
{
int area(int side) //area of a square
{ Output:
return(side * side);
} Area of square : 100
float area(float radius) //area of circle Area of rect: 200
{ Area of circle : 94.985
return(3.14f * radius * radius);
}
int area(int len, int wid) //area of rectangle
{

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

Command Line Arguments


 The command line argument is the argument passed to a program at the time of running the
java program. The command-line argument inside a java program is quite easy.
 They are stored as string in String array passed to the main () method.
 There is no restriction on the number of command line arguments. We can specify any number
of arguments.
 It can be used to specify configuration information while launching your application.
 Example While running a class Demo, we can specify command line arguments as
java Demo arg1 arg2 arg3 …

 Write a program to illustrate command-line arguments


class Cmd
{
public static void main(String[] args)
{
for(int i=0;i< args.length;i++)
{
System.out.println(args[i]);
}
}
}
Output:
javac Cmd.java
java Cmd Solapur 10 20 Mumbai
Solapur
10 7
20
Mumbai
Java Programming(22412) Chapter-2

Varargs (Variable-Length Arguments:


 Java allows us to create methods that need to take a variable number of arguments. This feature
is called varargs and it is short-form for variable-length arguments.
 A method that takes a variable number of arguments is a varargs method.
 The varags allows the method to accept zero or muliple arguments. Before varargs either we
use overloaded method or take an array as the method parameter.
 If we don't know how many argument we will have to pass in the method, varargs is the better
approach. We don't have to provide overloaded methods so less code.
 Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type.
return_type method_name(data_type... variableName)
{
//method body
}
 Rules for varargs:
1. There can be only one variable argument in the method.
2. Variable argument (varargs) must be the last argument.
class Varargs
{
void display(int num, String... values)
{
System.out.println("number is "+num);
for(String s:values)
{
System.out.println(s);
}
}
public static void main(String args[])
{
Varargs var=new Varargs();
var.display(500,"hello");//one argument
var.display(1000,"my","name","is","varargs");//four arguments
}
}

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.

2.2 Visibility Control


 Sometimes it is necessary to restrict the access to certain variables and methods from outside
the class.
 We can achieve this by applying visibility modifiers to the instance variable and methods. It is
also known as access modifiers.
 They tells us the Scope of class, constructor , variable , method where they would be used
 There are four types of modifiers:
1) default
2) public
3) private
4) public
1) public access:
 The public access modifier is specified using the keyword public.
 The public access modifier has the widest scope among all other access modifiers. There is
no restriction on the scope of a public data members
 Classes, methods or data members which are declared as public are accessible to the entire
class and visible to all the classes outside the class.
 It can be accessed from outside package also.
 It is accessible everywhere.
 For example,
public int val;
public void display();

Program on public Access Modifier


package p1;
public class A
{
public void display()
{
System.out.println(“Hello");
}
}

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();

Program on Default Access Modifier


package p1;
class A
{
void display()
{
System.out.println("Hello");
}
}

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

 The protected access modifier is specified using the keyword protected.


 The methods or data members declared as protected are accessible within same package
or sub classes in different package.
 For example,
protected int val;
protected void display();
Program on protected Access Modifier
package p1;
public class A
{
protected void display()
{
System.out.println("GeeksforGeeks");
}
}

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();

Program on private Access Modifier


package p1;
class A
{
private void display()
13
Java Programming(22412) Chapter-2

{
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

 A position in the array is indicated by a non-negative integer value called as index.


 An element at the given position is accessed by using this index. The size of array is fixed and
cannot increase to accommodate more elements.
 The first element is always at index 0 and the last element at index n-1, where n is the size of
the array.
 Advantages of f Arrays:
1) An array supports efficient random access to the members.
2) It is easy to sort an array.
3) They are more appropriate for storing fixed number of elements
 Disadvantages of Arrays:
1) Insertion and Deletion operation is difficult.
2) Size of array is fixed.
3) Dynamic creation of arrays is not possible.
4) Multiple data types cannot be stored.
 Types of array:
1) One dimensional array
2) Two dimensional array
1) One dimensional array
 One dimensional array is essentially, a list of same-typed variables.
 A list of items can be given one variable name using only one subscript.
 The creating one dimensional array takes two steps,
1) Declaring the array.
Size of array is not mentioned in the declaration.
datatype arrayname [ ] ;
2) Creating memory location (Instantiation of Array).
After declaration of an array, the array must be created in the memory. The array is created
using the new operator.
arrayname = new datatype[size];

Or Combining declaration and memory allocation


datatype arrayname[ ] = new datatype[size];

 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:

datatype arrayname[ ] = {list of values separated by commas};

For Example: int num[ ] = { 45, 12, 56, 10, 20, 86, 19, 46, 30 } ;

2) Initialization using index:


The individual element can be initialized as,
arrayname[index] = value;
16
Java Programming(22412) Chapter-2

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.

 Find minimum and maximum number from array


class Find
{ Output:
public static void main(String args[]) Array is : 8, 4, 6, 2, 9,
{ 3, 11, 5, 1,
int x[] = {8,4,6,2,0,3,11,5,1}; //array defined
Maximum is 11
int max = x[0]; //consider first no. as max Minimum is 1
int min = x[0]; //consider first no. as min
System.out.print ("Array is : ");
for(int i=0;i<x.length;i++) //print array
System.out.print (x[i]+", ");
for(int i=1;i<x.length;i++)
{
if(x[i] > max) //check each no. with max
max = x[i];
if(x[i] < min) //check each no. with min
min = x[i];
}
System.out.println ("Maximum is "+max);
System.out.println ("Minimum is "+min);
}

17
Java Programming(22412) Chapter-2

2) Two dimensional array


 It is also called as array of arrays. Many times it is required to manipulate the data in table
format or in matrix format which contains rows and columns. In these cases, we have to
give two dimensions to the array.
 A table of 3 rows and 4 columns can be referred as, table[3][4]
 The first dimension 3 is number of rows and second dimension 4 is number of columns.
 Syntax to create two dimensional arrays :

datatype arrayname[ ][ ] = new datatype[row][column];

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

 Creating the Strings

Creating strings: two ways:


1) Direct initialization:
String s=“Hello”;
18
Java Programming(22412) Chapter-2

2)Using constructor:
i)String()
creates empty string
ex: String str=new String();

ii)String (char ch[]) :


Initializes a new String from the given Character array.
ex: char ch[]={‘j’,’a’,’v’,’a’};
String s1=new String(ch);

iii)String (char ch[],int startindex,int count) :


Allocates a String from a given character array but choose count characters from the
start_index.
ex: char ch[]={‘J’,’a’,’v’,’a’};
String s1=new String(ch,2,2);

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

 String operations and methods


1) length()
 The length of a string is the number of characters that it contains. To obtain this value, call
the length ( ) method.
 Syntax:
int length()
 Example:
String s = “abc”;
int len = s.length();
 This will print the value 3 which is the length of string‘s’.
2) concat( )
 This is used to join two strings.
 Syntax:
String concat(String str)
 Example:

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

value > 0 then invoking string is greater than str

value = 0 then both the strings are equal


 Example:
String str1 = “catch”;
String str2 = “match”;
if(str1.compareTo(str2)<0) //true
System.out.println(“str2 is greater”);
else
System.out.println(“str1 is greater”);

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

Here the ‘startIndex’ specifies the index at which search begins.


Example:
String s = “Maharashtra”;
String t = “Tamilnadu”;
int in = s.indexOf(‘a’); //in will be 1
int mn = t.indexOf(‘a’, 2); //mn will be 6
int x = s.indexOf(“tra”); //x will be 8

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

 String s = “mama”. replace(‘m’,’k’);


 It will initialize the string‘s’ with value “kaka”.
12) trim()
 It is used to remove the leading and trailing white spaces from the string. It does not remove
the spaces in between the characters of the string.
 Syntax:
String trim()
 Example:
String s = “ What is this? “;
String k = s.trim();
 After this, the string ‘k’ will contain “What is this?”

13) toLowerCase( ) and toUpperCase( )


 These methods will convert the strings into lower case and upper case respectively. Non-
alphabetical characters such as digits and symbols are unaffected.
 Syntax:
String toLowerCase( )
String toUpperCase( )
 Example:
String s = “Solapur and Pune”;
String t = s.toUpperCase();
String u = s.toLowerCase();
After execution of these statements, the value of t will be “SOLAPUR AND PUNE” and u
will be “solapur and pune”.
14) startsWith()
Tests if string starts with the specified string str.
Syntax: boolean startsWith(String str)
Ex: String s1=“JPR-TH”;
boolean b=s1.startsWith(“TH”); // returns false
15) endsWith()
Tests if string ends with the specified string str.
Syntax: boolean endsWith(String str)
Ex: String s1=“JPR-TH”;
boolean b=s1.endsWith(“TH”); // returns true

 Write a program to illustrate the use of String class


class StringDemo
{
23 Output:
Lower case=solapur
Upper case=SOLAPUR
Java Programming(22412) Chapter-2

public static void main(String args[])


{
String str=new String("Solapur");
System.out.println("Lower case="+str.toLowerCase());
System.out.println("Upper case="+str.toUpperCase());
System.out.println("Length="+str.length());
System.out.println("indexOf(l)="+str.indexOf('l'));
System.out.println("concat="+str.concat(" City"));
System.out.println("replace="+str.replace('l','n'));
}
}

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.

 StringBuffer operations and methods


1) length( )
 The ‘length( )’ finds total number of characters that a StringBuffer is having in it.
 Syntax: int length( )
 Example:
StringBuffer sb = new StringBuffer("India");

24
Java Programming(22412) Chapter-2

int len = sb.length()); //len will be 5


 Here the variable len will contain total number of characters i.e. 5

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

 Write a program to illustrate the use of StringBuffer class


class StringBufferDemo
Output:
{
Length=7
public static void main(String args[]) capacity=23
{ append=Solapur city
StringBuffer sb=new StringBuffer("Solapur"); insert=My Solapur city
System.out.println("Length="+sb.length()); reverse=
System.out.println("capacity="+sb.capacity()); ytic rupaloS yM
System.out.println("append="+sb.append(" city"));
System.out.println("insert="+sb.insert(0,"My "));
System.out.println("reverse="+sb.reverse());
}
}
Vector
 Vector implements dynamic array that is growable array.
 It grows or shrinks as required.
 The package java.util contains the Vector class.
 Vector object is synchronized.
 Vector class can hold objects of any type and any number.
 The objects do not have to be homogeneous. It can store homogeneous as well as
heterogeneous elements.
 Arrays can be easily implemented as vectors.
 Capacity of the Vector can be increased automatically and dynamically.
 Creation of Vector
 Vector class defines three different constructors:
Vector() //creates a vector without sixe
Vector(size) //creates a vector with size
Vector(size, incr) //creates a vector with size and increment
Vector(Collection c) //Craetes a vector that contains elements of collection c.

 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

Ex: Object l=v.lastElement();

Returns true if the vector is empty, and returns false if it


boolean isEmpty() contains one or more elements.
Ex: boolean b=v.isEmpty();
Returns true if element is contained by the vector, and
boolean contains(Object item) returns false if it is not.
Ex: boolean b=v.contains(10);

 Write a program to illustrate the use of Vector


class VectorDemo Output:
{ Capacity of vector=10
public static void main(String args[]) Size of vector=0
{ Size of vector=7
Vector v=new Vector (); Capacity of vector=10
First element: 10
System.out.println ("Capacity of vector="+v.capacity ()); Last element: 20.5
System.out.println ("Size of vector="+v.size ());
v.addElement (10); Elements in vector:
10
v.addElement (Java"); Java
v.addElement (COBOL"); COBOL
v.addElement (20); 20
Java is secure.
v.addElement ("Java is secure."); 10.5
v.addElement (10.5); 20.5
v.addElement (20.5);
System.out.println ("Size of vector="+v.size ());
System.out.println ("capacity of vector="+v.capacity ());
System.out.println ("First element: " +v.firstElement ());
System.out.println ("Last element: " +v.lastElement ());
System.out.println ("\nElements in vector:");
for (int i=0;i<v.size();i++)
System.out.println (v.elementAt (i));
System.out.println ();
}
}

 Difference between Array and Vector


Sr.
No.
Array Vector
1 Array is the static memory allocation Vector is the dynamic memory allocation.
2 Array allocates the memory for the fixed Vector allocates the memory dynamically

29
Java Programming(22412) Chapter-2

size. means according to the requirement.


3 wastage of memory, No wastage of memory.
4 Array is not synchronized Vector is synchronized.
5 Array cannot be re-sized Vector can be re-sized.
6 Array can store primitive data types Vector stores objects.
Elements in the array cannot be deleted. Vector is efficient in insertion, deletion and to
7
increase the size.
Syntax : Syntax:
8
datatype[] arraname= new datatype[size]; Vector obj= new Vector();
Ex: int num[]={10,20,30,40,50}; Ex: Vector v=new Vector();
9
v.addElement(10);
Wrapper classes
 Java uses primitive types such as int, float or double to hold values of basic data types. These
data types cannot hold the objects of that type.
 Each of Java's eight primitive data types has a class dedicated to it. These are known as
wrapper classes, because they "wrap" the primitive data type into an object of that class.
 The wrapper classes are part of the java.lang package .
 Need:
 Primitive data types cannot hold the objects of that type. Primitive data types are always
passed by value and cannot be directly passes by reference.
To pass by reference, we need to create object representation of one of primitive data types.
 To provide mechanism to ‘wrap’ primitive values in an object so that primitives can do
activities reserved for the objects like being added to ArrayList, Hashset, HashMap etc.
collection.
 To provide an assortment of utility functions for primitives like converting primitive types
to and from string objects, converting to various bases like binary, octal or hexadecimal, or
comparing various objects.
 There are 8 wrapper classes in Java. All the wrapper classes are defined in package java.lang.

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

1) Integer Wrapper Class:


 An Integer object encapsulates a simple int value. Integer is a wrapper class for int.
Constructors Description
Integer(int a) The object is initialized with the value specified in variable ‘a’ and
reference to the object is assigned to the object variable.
Eg: Integer it1=new Integer(25);
Integer(String str) The object is initialized with the value specified in variable ‘str’
which is numeric representation of string and reference to the object
is assigned to the object variable.
Eg: Integer it2=new Integer(“25”);
 Methods of Integer Wrapper Class with example:
1) Converting String representation of a number into primitive types.
static int parseInt(String s) Returns a signed decimal integer value equivalent to string s.
Eg: int a=Integer.parseInt(“25”);
2) Converting numbers to String.
static String toString(int i) Returns a String object representing the specified integer.
Eg: String s=Integer.toString(25);
3) Converting objects into primitive types.
byte byteValue() Returns the value of this Integer as a byte.
Eg: Integer it1=new Integer(25);
byte b=it1.byteValue();
short shortValue() Returns the value of this Integer as a short.
Eg: Integer it1=new Integer(25);
short s=it1.shortValue();
int intValue() Returns the value of this Integer as an int.
Eg: Integer it1=new Integer(25);
Int i=it1.intValue();
long longValue() Returns the value of this Integer as a long.
Eg: Integer it1=new Integer(25);
long l=it1.longValue();
float floatValue() Returns the value of this Integer as a float.
Eg: Integer it1=new Integer(25);
float f=it1.floatValue();
double doubleValue() Returns the value of this Integer as a double.
Eg: Integer it1=new Integer(25);
double d=it1.doubleValue();
4) Converting objects into String
31
Java Programming(22412) Chapter-2

String toString() Returns a String object representing this Integer's value.


Eg: Integer it1=new Integer(25);
String s=it1.toString();

5) Converting decimal into binary, octal and hex.


static String toBinaryString(int i) Returns binary string of decimal i.
Eg:String s=Integer.toBinaryString(10);
static String toOctalString(int i) Returns octal string of decimal i.
Eg:String s=Integer.toOctalString(10);
static String toHexString(int i) Returns hexadecimal string of decimal i.
Eg:String s=Integer.toHexString(10);
6) Converting binary, octal and hex into decimal
Returns decimal from specified string when parsed with
specified base value.
Eg: 1) Convert binary into decimal
static Integer valueOf(String s, int int dec=Integer.valueOf(“1010”,2);
base) 2) Convert octal into decimal
int dec=Integer.valueOf(“10”,8);
3) Convert hex into decimal
int dec=Integer.valueOf(“a”,16);

 Write a program to illustrate the use of Integer Wrapper Class


class StringToInt
{ Output
public static void main(String args[]) 123
{
String s = "123";
int i = Integer.parseInt(s);
System.out.println(i);
}
}
}

 Write a program to illustrate the use of Integer Wrapper Class to convert


primitive int to Integer object
class ToInteger
{
public static void main(String args[])
{
int x=123;
Integer iob=Integer.valueOf(x); Output
System.out.println(“x=”+x+” iob=”+iob); x=123
32 iob=123
Java Programming(22412) Chapter-2

}
}
}

 Write a program to convert decimal into binary.


class ToBinary
{ Output
public static void main(String args[]) Into binary=1010
{
int dec=10;
System.out.println(“Into binary=”+Integer.toBinaryString(dec));
}
}
Enumerated Types
 Enumerated types are used to define collections constants.
 To define enumerated types enum keyword is used. It is defined as follows:
enum collectionname { list of elements separated by comma};

 It can be used in switch.


 It can be traversed
 It can have fields, methods as well as constructors.
 It can implement interface but cannot extends class because it internally extends Enum class.

 Write a program to demonstrate enumerated types


class EnumDemo
{
Output
enum color{Red,Green,Black,Yellow,White} Red
public static void main(String args[]) Green
{ Black
Yellow
for(color s:color.values()) White
{
System.out.println(s);
}
}
}

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

v.removeElementAt(2); // remove 3rd element


v.removeElementAt(3); // remove 4th element
v.insertElementAt(11,2) // new element inserted at 3rd position
System.out.println("Size of vector after insert delete operations: " + v.size());
}
}

 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);

System.out.print("Enter Emp number : ");


empid=sc.nextInt();

System.out.print("Enter Emp Name : ");


name=sc.next();

System.out.print("Enter Emp Salary : ");


salary=sc.nextFloat();
}
void show()
{
System.out.println("Emp ID : " + empid);
System.out.println(“Name : " + name);
System.out.println(“Salary : " + salary);
}
public static void main(String args[])
{
Employee e[] = new Employee[5];
for(int i=0; i<e.length; i++)
{
e[i] = new Employee();
e[i].getdata();
}
35
Java Programming(22412) Chapter-2

System.out.println(" Employee Details are : ");


for(int i=0; i<e.length; i++)
e[i].show();
}
}

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

Questions on 2nd Chapter


1) What is constructor? Demonstrate the use of parameterized constructor with a suitable
example.
2) What is garbage collection in java?
3) Define a class ‘employee’ with data members as empid, name and salary. Accept data
for 5 objects and print it.
4) Explain access modifiers with example.
5) Describe the following methods related to String
i) replace() ii) compareTo() iii) charAt() iv)substring()
36
Java Programming(22412) Chapter-2

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

You might also like