Java_notes
Java_notes
Content
2.1 Constructor and Methods, Types of constructors, nesting of methods, argument passing the ‘this’
keywords, varargs: variable length arguments, garbage collection, finalize () method, the object
class.
2.2 Visibility control public, Private, protected, default, friendly private protected access.
2.3 Arrays and strings: Types of array, creating an array, string, string classes and string buffer,
vectors, wrapper classes, enumerated types.
Constructor:
Constructors are used to assign initial value to instance variable of the class.
Properties:
• A constructor is a special member which initializes an object immediately upon creation.
• It has the same name as class name in which it resides and it is syntactically similar to any
method.
• When a constructor is not defined, java executes a default constructor which initializes all
numeric members to zero and other types to null or spaces.
• Once defined, constructor is automatically called immediately after the object is created before
new operator completes.
• Constructors do not have return value, not even ‘void’ because they return the instance if class.
• Constructor called by new operator.
Types of constructors are:
• Default constructor
• Parameterize constructor
• Copy constructor
Default Constructor
1
• By default, Java compiler, insert the code for a zero parameter constructor.
• Default constructor is the no arguments constructor automatically generated unless you define
another constructor.
• The default constructor automatically initializes all numeric members to zero and other types
to null or spaces.
For e.g.
class Rect
{
int length,
breadth;
Rect()
//constructo
r
{
len
gth
=4;
bre
adt
h=
5;
}
public static void main(String args[])
Parameterized
{ Constructor
Rect r = new Rect();
System.out.println(“Area : ” +(r.length*r.breadth));
} • Constructor which have arguments are known as parameterized constructor.
} • When constructor method is defined with parameters inside it, different value sets can be
Outputprovided
: Area :to20different constructor with the same name.
Example
class Rect
{
int length, breadth;
Rect(int l, int b) // parameterized constructor
{
length=l; breadth=b;
}
public static void main(String args[])
{
Rect r = new Rect(4,5); // constructor with
parametersRect r1 = new Rect(6,7);
System.out.println(“Area : ” +(r.length*r.breadth)); // o/p Area : 20
System.out.println(“Area : ” +(r1.length*r1.breadth)); // o/p Area : 42
}
}
2
Copy Constructor
• A copy constructor is a constructor that takes only one parameter which is same exact type as
the class in which the copy constructor is defined.
• A copy constructor is used to create another object that is copy of the object that it takes as
parameter.
For e.g.
class student
{
int id;
String name;
student(int i,
String n)
{
id=i;
name
=n;
}
student (student s)//copy constructor
{
id=s.id;
name=s.na
me;
}
void display()
{
System.out.println(id+“ ”+name)
}
public static void main(String args[])
student s1=new student(111, “ABC”);
s1.display();
student s2= new
student(s1);s2.display();
}
}
Output
111of Methods
Nesting
ABC
• 111
If theABC
method in Java calls method in same class, it is called as nesting of methods.
• When method calls the method in same the same class, (.) operator is not needed.
• A method can call more than one method in the same class.
For e.g.
3
class nest
{
int
x=10,y
=20;
void
display
();
System.out.println(“Value of
x”+x);
System.out.println(“Value of
y”+y);
}
void add()
{
display();
System.out.println(“x+y=”+(
x+y));
}
}
class method
{
public static void main(String arg[])
{
nest
Argument n=new passing the “this” keyword
nest();
• Then.add();
keyword this is useful when you need to refer to instance of the class from its method.
}
• This
} can be used inside any method to refer to the current object.
Output:
• ‘this’ is always a reference to the object on which method was invoked.
Value
of • You can use ‘this’ anywhere, a reference to an object of current class type is permitted. ‘this’
x=10
keyword helps us to avoid name conflict.
Value
of
For
x=20
e.g.
x+y=3
class
0
stude
nt
{
int id;
String name;
student(int id, String name)
{
this.id=id
;
this.name
=name;
}
void display()
System.out.println(id+“”+name);
}
public static void main(String 4
args[])student s1=new
student(1, “ram”);
student s2=new student(2, “shyam”);
s1.display();
s2.display();
}
}
O
u
t
p
Varargs:
u Variable Length Arguments
t
: • The varrags allows the method to accept zero or muliple arguments.
1 r • Before varargs either we use overloaded method or take an array as the method parameter but
a it was not considered good because it leads to the maintenance problem.
m
• If we don't know how many arguments we will have to pass in the method, varargs is the
2 shyam
betterapproach.
Syntax of varargs: The varargs uses ellipsis i.e. three dots after the data type.
return_type method_name(data_type... variableName)
{
//varargs code
}
Example:
public class VarArgs
{
public static void main(String[] args)
{
System.out.println("The sum of 5 and 10 is " + sum(5, 10));
System.out.println("The sum of 23, 78, and 56 is " + sum(23, 78, 56));
System.out.println("The sum when no parameter is passed is " + sum());
int[] numbers = { 23, 45, 89, 34, 92, 36, 90, 60 };
System.out.println("The sum of array is " + sum(numbers));
}
static int sum(int... list)
{
int total = 0;
Example:
public class A
{
int
p, q;
A(
)
{
p = 10;
p = 20;
}
}
class Test
{
public static void main(String args[])
{
A a1= new
A();A a2=
new A();
a1=a2; // it deallocates the memory of object a1
Finalize() }
method
}
• Sometime an object will need to perform some specific task before it is destroyed such as
closing an open connection or releasing any resources held. To handle such situation finalize
() method is used.
• Finalize () method is called by garbage collection thread before collecting object. Its the last
chance for any object to perform cleanup utility.
6
• The garbage collector runs periodically, checking for objects that are no longer referenced by
any running state or indirectly through other referenced objects. Right before an asset is freed,
the java run time calls the finalize () method on the object.
A finalizer in Java is the opposite of a constructor. While a constructor method performs initialization for an
object, a finalizer method performs finalization for the object.
Garbage collection automatically frees up the memory resources used by objects, but objects can hold other
kinds of resources, such as open files and network connections.
The garbage collector cannot free these resources for you, so you need to write a finalizer method for any
object that needs to perform such tasks as closing files, terminating network connections, deleting temporary
files, and so on.
A finalizer is an instance method that takes no arguments and returns no value. There can be only one
finalizer per class, and it must be named finalize() .
Example:
public class Test_gc
{
t=null;
System.gc(); //explicitely
}
public void finalize()
{
System.out.println("Garbage Collected");
}
}
7
The object class
Class:
• A class is user defined data type which groups data members and its associated function
together.
• Once a new data type is defined using a class, it can be used to create objects of that types.
• Classes create objects and objects use methods to communicate between them.
Structure of program
class classname[extends superclassname]
{
[field declaration]
[method declaration]
}
8
Field Declaration
• A class declaration typically includes one or more field that declares data of various types. Tha data or
variable define inside the class are called as instance variable.
• The declaration of instance variable is similar to declaration of local variables.
• For e.g.
class cat
{
String name;
int age;
float salary;
}
Method Declaration
• Only data fields in the class have no. of files. The objects created by such a class cannot respond to any
messages.
• Methods are necessary for manipulating the data contain in a class.
• Syntax:-
type methodname (parameter _list)
{
Method body;
}
• For e.g:-
void getdata(int x, int y){
length=x;
breadth=y;
}
Creating Object
• An object in Java is essentially a block of memory that contains space to store all the instance variables.
Action Statement Result
Declare Rectangle rect;
Null
Null
9
Steps for creating object: -
Declaring an object: -
• Declaring a variable to hold an object is just like declaring variable to hold a value of primitive
type.
• Declaration does not create new object. It is simply a variable that can refer to an object.
• For e.g. Rectangle rect;
Instantiating: -
• Creating an object is also referred to as instantiating an object.
• Object in Java are created using new operator. The new operator creates an object of the
specified class and return reference to that object.
• For e.g. rect=new Rectangle();
It assigns object reference to the variables. Variable rect is now object of the class.
Initializing an object:-
• A Class provides constructor methods to initialize a new object of that type.
• A may provide multiple constructor o perform different kind of initialization of new object.
• For e.g. Rectangle rect = new Rectangle(10,20)
10
rect.width=20;
rectangle x1=new rectangle();
x1.getdata(10,20);
Public:
Public Specifiers achieves the highest level of accessibility. Classes, methods, and fields
declared as public can be accessed from any class in the Java program, whether these classes
are in the same package or in another package.
Example: public int number;
Public void sum() {-------------}
Private:
Private Specifiers achieves the lowest level of accessibility. private methods and fields can
only be accessed within the same class to which the methods and fields belong. private
methods and fields are not visible within subclasses and are not inherited by subclasses. So, the
private access specifier is opposite to the public access specifier. Using Private Specifier, we
can achieve encapsulation and hide data from the outside world.
11
Default (Friendly Access):
When no access modifier is specified, the member defaults to a limited version of public
accessibility known as “friendly” level of access. Using default specifier, we can access class,
method, or field which belongs to same package, but not from outside this package.
Protected:
The visibility level of a “protected” field lies in between the public access and friendly access.
Methods and fields declared as protected can only be accessed by the subclasses in other
package or any class within the package of the protected members' class. Note that non sub
classes in other packages cannot access the “protected” members.
Private Protected:
12
Access Level
Modifier Same Subclass Other classes Sub class Non sub class
class In Same In same In other In other
package package classes classes
Private Yes No No No No
Arrays
• It is collection of related data item that share a certain name. the complete set of values is
referred as an array and individual values are called as elements.
• Array can be of any variable type.
Types of array:
1. One Dimensional Array
A list of item can be given one variable name using only one subscript and such
variable is called as single subscripted variable or one dimensional array.
Creation of Array
type array_name[]; or
type []array_name;
For e.g.:-
int number[]; or
float []price;
Initialization of array: -
To put values into the array is known as initialization. Once an array is
instantiated its size cannot be changed.
Syntax:-
type array_name[]=value;
For e.g.:-
13
int number[]={ 10, 20, 30, 40, 50};
Java allows us to create array using new operator
type array_name=new type[size];
For e.g.:-int number[]= new int[5];
Program 1:
class array_simple_example
{
public static void main (String[] args)
{
// declares an Array of integers.
// int arr[];
//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Program 2:
class array_simple_example2
{
public static void main (String[] args)
{
// declares an Array of integers.
// int arr[];
14
// initialize the first elements of the array
int arr[]={4,2,3,5,7};
equals(array1, array2): This method checks if both the arrays are equal or not.
import java.util.Arrays;
sort(originalArray, fromIndex, endIndex): This method sorts the specified //range of array in
ascending order.
import java.util.Arrays;
public class arr_sort
{
public static void main(String[] args)
{
// Get the Array
int intArr[] = { 10, 20, 15, 22, 35 };
15
binarySearch(intArr, intKey):This methods searches for the specified element in the array with the
help of Binary Search algorithm.
import java.util.*;
public class arr_bin_search
{
public static void main(String[] args)
{
// Get the Array
int intArr[] = { 40,10, 20, 15, 22, 35 };
Arrays.sort(intArr);
int intKey = 15;
System.out.println(intKey + " found at index = " + Arrays.binarySearch(intArr, intKey));
}
}
import java.util.Arrays;
public class arr_tostring
{
public static void main(String[] args)
{
// Get the Array
int intArr[] = { 10, 20, 15, 22, 35 };
// To print the elements in one line
System.out.println("Integer Array: "
+ Arrays.toString(intArr));
}
}
// printing 2D array
for (int i=0; i< 3 ; i++)
{
16
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Array of Object:
class Student
{
public int roll_no;
public String name;
Student(int roll_no, String name)
17
{
this.roll_no = roll_no;
this.name = name;
}
}
// Elements of the array are objects of a class Student.
public class array_stud_example
{
public static void main (String[] args)
{
// declares an Array of integers.
Student[] arr;
// allocating memory for 5 objects of type Student.
arr = new Student[5];
// initialize the first elements of the array
arr[0] = new Student(1,"Prince");
// initialize the second elements of the array
arr[1] = new Student(2,"Hasan");
arr[2] = new Student(3,"Amman");
arr[3] = new Student(4,"Chirag");
arr[4] = new Student(5,"Shreyas");
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : " +
arr[i].roll_no +" "+ arr[i].name);
}
}
Strings
• The string class is commonly used for holding and manipulating strings of texts in Java
program.
• Strings are class object and implemented using two classes i.e. String and StringBuffer.
• A Java string is an instantiated object of the string class.
• A Java string is not a character array and is not null terminated.
18
Declaration of String
String String_name;
String_name= new String(“String”);
For E.g.
String name;
name= new String(“ABCD”); or String name= new String(“ABCD”);
1. toLowerCase():
Converts all of the characters in this String to lower case.
Syntax: s1. toLowerCase()
Example: String s="Sachin";
System.out.println(s.toLowerCase());
Output: sachin
2. toUpperCase():
Converts all of the characters in this String to upper case
Syntax: s1.toUpperCase()
Example: String s="Sachin";
System.out.println(s.toUpperCase());
Output: SACHIN
3. trim():
Returns a copy of the string, with leading and trailing whitespace omitted.
Syntax: s1.trim()
Example: String s=" Sachin ";
System.out.println(s.trim());
Output:Sachin
19
4. replace():
Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.
Syntax: s1.replace(‘x’,’y’)
Example: String s1="Java is a programming language. Java is a platform.";
String s2=s1.replace("Ja","Ka");//replaces all occurrences of "Ja" to "Ka"
System.out.println(s2);
Output: Kava is a programming language. Kava is a platform.
5. charAt():
Returns the character at the specified index.
Syntax: s1.CharAt(n)
Example: String s="Sachin";
System.out.println(s.charAt(0));
System.out.println(s.charAt(3));
Output:
S
H
6. equals():
The String equals() method compares the original content of the string. It compares values of
string for equality.
Syntax: s1.equals(s2)
Example: String s1="Sachin";
String s2="Sachin";
String s3="Saurav"
System.out.println(s1.equals(s2)); //true
System.out.println(s1.equals(s3)); //false
Output:
True
False
7. equalsIgnoreCase():
comparing two Strings by ignoring case.
Syntax: s1.equalsIgnoreCase(s2)
Example: String s1="Sachin";
20
String s2="SACHIN";
System.out.println(s1.equals(s2)); //false
System.out.println(s1.equalsIgnoreCase(s3)); //true
Output:
False
True
8. compareTo():
The String compareTo() method compares values lexicographically and returns an integer
value that describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
s1 == s2 :0
s1 > s2 : positive value
s1 < s2 : negative value
Syntax: s1.compareTo(s2)
Example: String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2)); //0
System.out.println(s1.compareTo(s3)); //1(because s1>s3)
System.out.println(s3.compareTo(s1)); //-1(because s3 < s1 )
9. length():
The string length() method returns length of the string.
Syntax: s1.length()
Example: String s="Sachin";
System.out.println(s.length());
Output: 6
10. concat():
string concatenation forms a new string that is the combination of multiple strings.
Syntax: s1.concat(s2)
Example: String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
21
System.out.println(s3);
Output: Sachin Tendulkar
11. Substring():
A part of string is called substring. In other words, substring is a subset of another string.
Syntax: s1.substring(n)
Example: String s="Sachin Tendulkar";
System.out.println(s.substring(6));
Output: Tendulkar
12. substring(n,m):
Gives substring starting from nth character up to mth .
Syntax: s1.substring(n,m)
String s="Sachin Tendulkar";
System.out.println(s.substring(0,6));
Output: Sachin
13. indexOf():
Gives the position of the first occurrence of ‘x’ in the string s1.
Syntax: s1.indexOf(‘x’)
Example: String s1=”sachin”;
s1.indexOf(‘a’);
Output: 1
14. indexOf(‘x’,n):
Gives the position of ‘x’ that occurs after nth position in the string s1.
Example: String s1=”sanjay”; s1.indexOf(‘a’,2);
Output: 4
15. valueOf():
The string valueOf() method coverts given type such as int, long, float, double, boolean, char
and char array into string.
Syntax: String.ValueOf(p)
Example: int a=10;
String s=String.valueOf(a);
System.out.println(s+10);
22
Output: 1010
16. endsWith():
This method tests if this string ends with the specified suffix.
Syntax: endsWith(String suffix)
Example: String Str = new String("This is really not immutable!!");
boolean retVal;
retVal = Str.endsWith( "immutable!!" );
System.out.println("Returned Value = " + retVal );
retVal = Str.endsWith( "immu" );
System.out.println("Returned Value = " + retVal );
Output:
Returned Value = true
Returned Value = false
17. startsWith():
This method has two variants and tests if a string starts with the specified prefix beginning a
specified index or by default at the beginning.
Syntax: startsWith(String prefix) or startsWith(String prefix, int toffset)
Example: String Str = new String("Welcome to Tutorialspoint.com");
System.out.print("Return Value :" );
System.out.println(Str.startsWith("Welcome") );
System.out.print("Return Value :" );
System.out.println(Str.startsWith("Tutorials") );
Output:
Return Value : true
Return Value : false
String S1="sachin";
String S2="nikita";
23
System.out.println(S1.toLowerCase());
System.out.println(S1.toUpperCase());
String S3=S2.replace("nikita","ratan");
System.out.println(S3);
System.out.println(S1.charAt(0));
System.out.println(S1.charAt(3));
String S4="nikita";
String S5="nikita";
String S6="omkars";
System.out.println(S4.equals(S5));
System.out.println(S4.equals(S6));
String S7="nikita";
String S8="NIKITA";
System.out.println(S7.equals(S8));
System.out.println(S7.equalsIgnoreCase(S8));
System.out.println(S1.length());
String S9="nikita";
String S10="kumthekar";
String S11=S9.concat(S10);
System.out.println("String S11="+S11);
String S12="SachinTendulkar";
System.out.println(S12.substring(6));
System.out.println(S12.substring(0,6));
System.out.println(S12.substring(5,9));
String S13="samreen";
System.out.println(S13.indexOf('a'));
String S14="Sanjay";
System.out.println(S14.indexOf('a',4));
String S15="sachin";
String S16="sachin";
24
String S17="ratan";
System.out.println(S15.compareTo(S16));
System.out.println(S15.compareTo(S17));
System.out.println(S17.compareTo(S15));
1. Append():
The append() method concatenates the given argument with this string.
Syntax: s1.append(s2)
Example: StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java"); //now original string is changed
System.out.println(sb);
output: Hello Java
2. Insert():
The insert() method inserts the given string with this string at the given position.
Syntax: s1.insert(n,s2)
Example: StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java"); //now original string is changed
System.out.println(sb);
Outputs: HJavaello
25
3. Replace():
The replace() method replaces the given string from the specified beginIndex and
endIndex.
Syntax: replace(int start, int end, String str )
Example: StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);
Output: HJavao
4. delete():
The delete() method of StringBuffer class deletes the string from the specified beginIndex
toendIndex.
5. reverse():
The reverse() method of StringBuilder class reverses the current string.
Example: StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);
Output: olleH
6. setCharAt():
Modifies the nth character to x.
Example: StringBuffer s1= new StringBuffer(“vijay”);
s1.setCharAt(3,’e’);
Output: vijey
7. deleteCharAt():
This is the deleteCharAt() function which is used to delete the specific character fromthe
buffered string by mentioning that's position in the string.
Example: StrigBuffer s1 = new StringBuffer("vijay");
26
s1.deleteCharAt(2);
Output: viay
8. setLength():
This method sets the length of the character sequence. Sets the length of the string s1 to n.
if n<s1.length() s1 is truncated. If n>s1.length() zeros are added to s1.
Syntax: s1.setLength(n)
Example:
class method
System.out.println(s1.append(s2));
System.out.println(s3.insert(2,s4));
s3.replace(1,3,"Java");
System.out.println(s5);
s6.delete(1,3);
System.out.println(s6);
27
StringBuffer s7=new StringBuffer("Java");
s7.reverse();
System.out.println(s7);
s8.setCharAt(3,'e');
System.out.println(s8);
s9.deleteCharAt(2);
System.out.println(s9);
System.out.println(s10+"\nlength=" + s10.length());
s10.setLength(4);
System.out.println(s10+"\nlength=" + s10.length());
Object can be created by assigning String Objects can be created by calling constructor of
constants enclosed in double quotes. StringBuffer class using “new”
Ex:- String s=”abc”‖; Ex:- StringBuffer s=new StringBuffer (“abc”);
Vector
Vector Methods
remove(int index) Removes the element at the specified position in this vector.
removeElementAt(n) Removes the item stored in the nth position of the list.
removeElement(item) Removes the specified item from the list.
removeRange(int fromIndex, int This method removes from this List all of the elements whose index is
toIndex) between fromIndex, inclusive and toIndex, exclusive.
removeAllElements() Removes all the elements in the list.
copyInto(array) Copies all items from list of array.
insertElementAt(item, n) Inserts the item at nth position.
boolean contains(Object elem) Tests if the specified object is a component in this vector.
elements() It returns an enumeration of the element.
hasMoreElements() It checks if this enumeration contains more elements or not.
nextElement() It checks the next element of the enumeration.
int indexOf(Object o) This method returns the index of the first occurrence of the specified
element in this vector, or -1 if this vector does not contain the element.
This method returns the index of the first occurrence of the specified
int indexOf(Object o, int index) element in this vector, searching forwards from index, or returns -1 if
the element is not found.
29
int lastIndexOf(Object o) This method returns the index of the last occurrence of the specified
element in this vector, or -1 if this vector does not contain the element.
Array is unsynchronized i.e. automatically Vector is synchronized i.e. when the size will be
increase the size when the initialized size will be exceeding at the time; vector size will increase
exceed. double of initial size.
Declaration of an array : Declaration of Vector:
int arr[] = new int [10]; Vector list = new Vector(3);
Array is the static memory allocation. Vector is the dynamic memory allocation.
Array allocates the memory for the fixed size ,in Vector allocates the memory dynamically means
array there is wastage of memory. according to the requirement no wastage of
memory.
No methods are provided for adding and Vector provides methods for adding and
removing elements. removing elements.
In array wrapper classes are not used. Wrapper classes are used in vector.
Array is not a class. Vector is a class.
30
Q. Write a program to implement a vector class and its method for adding and
removingelements. After remove display remaining list.
import java.io.*;
import java.lang.*;
import java.util.*;
class vector2
{
public static void main(String args[])
{
vector v=new vector();
Integer s1=new Integer(1);
Integer s2=new Integer(2);
String s3=new String("fy");
String s4=new String("sy");
Character s5=new Character('a');
Character s6=new Character('b');
Float s7=new Float(1.1f);
Float s8=new Float(1.2f);
v.addElement(s1);
v.addElement(s2);
v.addElement(s3);
v.addElement(s4);
v.addElement(s5);
v.addElement(s6);
v.addElement(s7);
v.addElement(s8);
System.out.println(v);
v.removeElement(s2);
v.removeElementAt(4);
System.out.println(v);
}
}
Q. 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(new Integer(10));
v.addElement(new Integer(20));
v.addElement(new Integer(50));
v.addElement(new Integer(20));
v.addElement(new Integer(40));
31
v.addElement(new Integer(10));
v.addElement(new Integer(20));
System.out println(v.size()); // display original size
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());
}
}
Q. Write a program to implement vector class and its method for adding and
removingelements. (6 Marks)
import java.util.*;
public class VectorDemo
{
public static void main(String args[])
{
Vector v = new Vector();
v.addElement(new Integer(1));
v.addElement(new Double(2523));
v.addElement(new Float(3.55f));
v.addElement(“java”);
System.out.println("Size of vector after four additions: " + v.size());
v.removeElementAt(2);
v.removeElementAt(1);
System.out.println("Size of vector after removed : " + v.size()); System.out.println("\nElements in
vector:"); System.out.println(v);
}
}
Output:-
Size of vector after four additions:4
Size of vector after removed :2
1 java
32
Q. Write a program to implement vector that accept 5 elements from command line
arguments and store them in a vector & display the object stores in the vector.
import java.util.*;
class vectordemo
{
public static void main(String arg[])
{
Vector v=new Vector();
String name;
for(int i=0; i<arg.length;i++)
{
name=arg[i];
v.addElement(arg[i]);
}
33
Wrapper Class
• Vectors cannot handle primitive data types like int, float, long, char and double.
• Primitive data types may be converted into object types by using the wrapper classes.
• The wrapper classes for numeric primitives have the capability to convert any valid number in
string format into its corresponding primitive object.
• For example “10" can be converted into an Integer by using:
Integer intVal = new Integer("10");
A Wrapper class is a class whose object wraps or contains primitive data types. When we create an object to
a wrapper class, it contains a variable and in this variable, we can store primitive data types. In other words,
we can wrap a primitive value into a wrapper class object.
Need of Wrapper Classes
1. They convert primitive data types into objects. Objects are needed if we wish to modify the arguments
passed into a method (because primitive types are passed by value).
2. The classes in java.util package handles only objects and hence wrapper classes help in this case also.
34
Simple data types and their corresponding wrapper class types are as follows:
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Wrapper classes have number of unique methods for handling primitive data types and object which
are listed below: -
1. Converting primitive numbers to object numbers using constructor methods
35
3. Converting numbers to Strings using to String() method
Example:
class wrapperdemo
{
public static void main(String args[])
{
//Convert string value into integer Wrapper class object
String str = "23";
Integer i = Integer.valueOf(str);
System.out.println("Convert string value into integer wrapper class object");
System.out.println("The integer value: "+i);
Float f=Float.valueOf(str);
System.out.println("The float value: "+f);
//convert integer object value into primitive data types byte, short and double
System.out.println("Convert integer object value into primitive data types");
Integer itr = new Integer(10);
36
System.out.println("byte value: "+itr.byteValue());
System.out.println("double value: "+itr.doubleValue());
System.out.println("float value: "+itr.floatValue());
System.out.println("short value: "+itr.shortValue());
Output:
Example:
int i = 0; //p
i = new Integer(5); // auto-unboxing
Integer i2 = 5; // autoboxing
37
{
public static void main(String a[])
{
String str = Integer.toString(5);
System.out.println("String value of i "+str );
}
}
Q. What is the use of wrapper classes in Java? Explain float wrapper with its methods.
• Java provides several primitive data types. These include int (integer values), char (character),
double (doubles/decimal values), and byte (single-byte values).
• Sometimes the primitive data type isn't enough and we may have to work with an integer
object.
• Wrapper class in java provides the mechanism to convert primitive into object and object into
38
primitive.
• Float wrapper Class: Float wrapper class is used to wrap primitive data type float value in an
object.
Methods:
1. floatValue( ) method:
It is used to return value of calling object as float.
2. parseFloat( ) method:
It is used to return float of a number in a string in radix 10.
3. toString(float f ) method:
It is used to find the string equivalent of a calling object.
4. valueOf(String s) method:
It is used to return Float object that has value specified by str.
5. compare(float f1, float f2) method: It is used to compare values of two numbers.
If it returns a negative value, then, n1<n2.
If it returns a positive value, then, n1>n2.
If it returns 0, then both the numbers are equal.
6. compareTo (float f1) method:
is used to check whether two numbers are equal, or less than or greater than each other.
If the value returned is less than 0 then, calling number is less than x.
If the value returned is greater than 0 then, calling number is greater than x.
If value returned is 0, then both numbers are equal.
7. equals(Object obj) method:
It is used to check whether two objects are equal. It returns true if objects are equal,otherwise
false.
Q. Write a program to accept number from user & convert it into binary by using
wrapperclass method
import java.io.*;
public class MyIntegerToBinary
{
public static void main(String args[])throws IOException
{
int i;
BufferedReader obj = new BufferedReader (new InputStreamReader(System.in));
System.out.print("Enter number that you want to convert to binary: ");
i=Integer.parseInt(obj.readLine());
39
String binary = Integer.toBinaryString(i); //Converts integer to binary
System.out.println("Binary value: "+binary);
}
}
// error
// runs perfectly
In such cases, wrapper classes help us to use primitive data types as objects.
For example,
// generates an error
int a = null;
// runs perfectly
Integer a = null;
Enumerated Types
• Enum type is atype which consists of fixed set of constant fields. This keyword can be used
similar to the static final constants.
• Enumerations serve the purpose of representing a group of named constants in a
programming language.
• In Java (from 1.5), enums are represented using enum data type. Java enums are more
powerful than C/C++ enums . In Java, we can also add variables, methods and constructors
to it. The main objective of enum is to define our own data types(Enumerated Data Types).
40
Declaration of enum in java :
Enum declaration can be done outside a Class or inside a Class but not inside a Method.
Example:
enum Color
{
RED, GREEN, BLUE;
}
public class enum_demo
{
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
Every enum constant is always implicitly public static final. Since it is static, we can access it by
using enum Name. Since it is final, we can’t create child enums.
Advantages:
• Compile time type safety.
• We can use the enum keyword in switch statements.
Programs:
42
Q. Write a program to convert a decimal number to binary form and display the value
import java.lang.*;
import java.io.*;
class dtob
{
public static void main(String args[]) throws IOException
{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the decimal value=");
String hex=bf.readLine();
int i=Integer.parseInt(hex);
String bi=Integer.toBinaryString(i);
System.out.println("Binary number="+bi);
}
}
Output:
Enter the decimal value=12
Binary number=1100
Q. Define a class item having data member code and price. Accept data for one object and
display it.
import java.io.*;
class Item_details
{
int code;
float price;
Item_details()
{
code=0;
price=0;
}
Item_details(int e,float p)
{
code=e;
price=p;
}
void putdata()
{
System.out.println("Code of item :"+code);
System.out.println("Price of item:"+price);
}
public static void main(String args[]) throws IOException
{
Int co;
Float pr;
BufferedReaderbr=new BufferedReader (new InputStreamReader(System.in)); System.out.println("enter
code and price of item");
co=Integer.parseInt(br.readLine());
pr=Float.parseFloat(br.readLine());
Item_details obj=new Item_details(co,pr);
obj.putdata();
}
}
43
Q. Write a program to accept a number as command line argument and print the number is
even or odd
public class oe
{
public static void main(String key[])
{
int x=Integer.parseInt(key[0]);
if (x%2 ==0)
{
System.out.println("Even Number");
}
else
{
System.out.println("Odd Number");
}
}
}
Q. Define a class ‘employee’ with data members empid, name and salary. Accept data for
five objectsusing Array of objects and print it.
class employee
{
int empid;
String name;
double salary;
void getdata()
{
BufferedReader obj = new BufferedReader (new InputStreamReader(System.in)); System.out.print("Enter Emp
number : ");
empid=Integer.parseInt(obj.readLine());
System.out.print("Enter Emp Name : ");
name=obj.readLine();
System.out.print("Enter Emp Salary : ");
salary=Double.parseDouble(obj.readLine());
}
void show()
{
System.out.println("Emp ID : " + empid);
System.out.println(“Name : " + name);
System.out.println(“Salary : " + salary);
}
}
classEmpDetails
{
public static void main(String args[])
{
employee e[] = new employee[5];
for(inti=0; i<5; i++)
{
e[i] = new employee();
e[i].getdata();
}
System.out.println(" Employee Details are : ");
for(inti=0; i<5; i++)
e[i].show();
}
}
44
Q. Write a program to accept first name, middle name and surname in three different
strings and thenconcatenate the three strings to make full name.
import java.io.*;
class StringConcat
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str1,str2,str3,namestr="";
System.out.println("Enter first name:");
str1=br.readLine();
System.out.println("Enter middle name:");
str2=br.readLine();
System.out.println("Enter last name:");
str3=br.readLine();
namestr = namestr.concat(str1);
namestr = namestr + " ";
namestr = namestr.concat(str2);
namestr = namestr + " ";
namestr = namestr.concat(str3);
System.out.println("Your FULL NAME is : " + namestr);
}
}
class bubble
{
public static void main(String args[])
{
int a[]={10,25,5,20,50,45,40,30,35,55};
int i=0;
int j=0;
int temp=0;
int l=a.length;
for(i=0;i<l;i++)
{
for(j=(i+1);j<l;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println("Ascending order of numbers:");
for(i=0;i<l;i++)
System.out.println(""+a[i]);
}
}
45
Q. Write a program to check whether the given string is palindrome or not
import java.lang.*;
import java.io.*;
import java.util.*;
class palindrome
{
public static void main(String arg[ ]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter
String:");
String word=br.readLine( );
int len=word.length( )-1;
int l=0;
int flag=1;
int r=len;
while(l<=r)
{
if(word.charAt(l)==word.charAt(r))
{
l++;
r--;
}
else
{
flag=0; break;
}
}
if(flag==1)
{
System.out.println("palindrome");
}
else
{
System.out.println("not palindrome");
}
}
}
Q. Write a program to accept a password from the user and authenticate the user if password is
correct.
import java.io.*;
class test
{
public static void main(String a[]) throws Exception
{
String S1="Admin";
String S2="12345";
String username, userpwd;
try
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the user name");
username=b.readLine();
System.out.println("Enter the password");
userpwd= b.readLine();
if(S1.equals(username) && S2.equals(userpwd))
46
{
System.out.println("Welcome!! You are authenticated");
}
else
{
System.out.println("You have entered wrong information!!");
}
}
catch(Exception e)
{
System.out.println("I/O Error");
}
}
}
Output:
Enter the user name
Admin
Enter the password
12345
Welcome!! You are authenticated
Enter the user name
Admin
Enter the password
123
You have entered wrong information!!
47
More examples on Wrapper classes:
Program1)
import java.util.*;
class Autoboxing_unboxing
{
public static void main(String[] args)
{
char ch = 'I';
Program 2)
class Main_wrapper {
public static void main(String[] args)
{
Program 3)
48
class Main_wrapper_1
{
public static void main(String[] args)
{
Integer cObj = Integer.valueOf(2);
// converts into int type
int c = cObj;
class Main_wrapper_2
{
public static void main(String[] args)
{
Integer myInt = 100;
String myString = myInt.toString();
System.out.println(myString.length());
StringBuffer sb=new StringBuffer(myString);
System.out.println(sb.reverse());
}
}
49