0% found this document useful (0 votes)
66 views20 pages

Unit - Ii

The lecture notes cover Java programming concepts, focusing on arrays, including single and multi-dimensional arrays, their creation, initialization, and traversal. It also discusses variable arguments (varargs) in Java, explaining their syntax and usage, along with the String class and its methods. Key topics include array properties, command line arguments, and exceptions related to array handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views20 pages

Unit - Ii

The lecture notes cover Java programming concepts, focusing on arrays, including single and multi-dimensional arrays, their creation, initialization, and traversal. It also discusses variable arguments (varargs) in Java, explaining their syntax and usage, along with the String class and its methods. Key topics include array properties, command line arguments, and exceptions related to array handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Lecture Notes

Course: MCA Academic Year: 2023-24


Name of the Subject: Java Programming (21MC202) Year / Semester: I / II
Name of the Staff: Mr. P. Vijay Bhaskar Reddy Department: MCA

MODULE – II
Declaration, Initialization and accessing values, One-Dimensional Arrays, Multi- dimensional arrays,
Alternative Array Declaration Syntax, var-arg methods, Wrapper Classes. String, StringBuffer and
StringBuilder classes.
-------------------------------------------------------------------------------------------------------------------------------
Arrays:
An array represents a group of elements of same data type. It can store a group of elements. So, we can store
a group of int values or a group of float values or a group of strings in the array. But we can not store some
int values and some float values in the array. In java, arrays are created on dynamic memory, i.e., allotted at
runtime by JVM.
Types of arrays: Arrays are generally categorized into 2 parts:
 Single dimensional arrays
 Multi-dimensional arrays
Single dimensional arrays (1D array): A one dimensional array represents a row or a column of elements.
For example, the marks obtained by a student in 5 different subjects can be represented by a 1D array,
because these marks can be written as a row or as a column.
Creating a single dimensional array: There are some ways of creating a single dimensional array
 We can declare a one dimensional array and directly store the elements at the time of its declaration,
as:
int marks[]={50, 60, 55, 84, 95};
 Another way of creating a one dimensional array is by declaring the array first and then allotting the
memory for it by using new operator.
int marks[];
marks=new int[5];
Here, we should understand that JVM allots memory for storing 5 integer elements into the array. But there
are no actual elements stored in the array so far. To store the elements into the array, we can use the
following statements:
marks[0]=50;
marks[1]=60;
marks[2]=55;
marks[3]=84;
marks[4]=95;
While writing a one dimensional array, we can write the pair of square braces before or after the array name,
as:
int marks[]={50, 60, 55, 84, 95};
int[] marks={50, 60, 55, 84, 95};
Or, we can pass the values from keyboard to the array by using a loop, as:

1
{
//read integer value from the keyboard and store into marks[i]
marks[i]=Integer.parseInt(br.readLine());
}
E.g.:
//Java Program to illustrate how to declare, instantiate, initialize and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

E.g.:
//Java Program to illustrate the use of declaration, instantiation, initialization of Java array in single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

E.g.:
//Java Program to print the array elements using for-each loop
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}

2
Multi dimensional arrays (2D, 3D, … arrays): Multi dimensional arrays represent 2D, 3D, …arrays which
are the combinations of several earlier types of arrays. For example, a two dimensional array is a
combination of 2 or more one dimensional arrays. Similarly a three dimensional array is a combination of 2
or more two dimensional arrays.
Two dimensional arrays (2D arrays): A two dimensional array represents several rows and columns of
data. For example, the marks obtained by a group of students in five different subjects can be represented by
a 2D array.
Creating a two dimensional array: There are some ways of creating a two dimensional array as:
 We can declare a dimensional array and directly store elements at the time of its declaration, as :
int marks[][]={{50, 60, 70, 80, 90},
{85, 65, 45, 96, 32},
{56, 89, 95, 100, 94}};
So, the JVM creates 3*5=15 blocks of memory as there are 15 elements being stored into the array.
 Another way of creating a two dimensional array is by declaring the array first and then allotting
memory for it by using new operator.
int marks[][];
marks=new int[3][5];
While writing a two dimensional array, we can write the two pairs of square braces before or after the array
name, as: int marks[][]=new int[3][5];
int[][] marks=new int[3][5];
Three dimensional arrays (3D array): We can consider a three dimensional array as a combination of
several two dimensional arrays. This concept is useful when we want to handle group of elements belonging
to another group. For example, a college has 3 departments: electronics, computers and civil. We want to
represent the marks obtained by the students of each department in 3 different subjects. To store all these
marks, department wise, we need a three dimensional array as:
int marks[][][]={{{50, 60, 70}, {85, 95, 75}},
{{70, 71, 72}, {85, 65, 75}},
{{85, 65, 75}, {84, 74, 94}}};
Other ways of creating three dimensional arrays: int marks[][][]=new int[3][2][3];
int[][][] marks=new int[3][2][3];
E.g.:
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
3
Array name .length: If we want to know the size of an array, we can use the property ‘length’ of an array.
Array name.length returns an integer number which represents the size of an array. For example, take the
array marks[] with size 10 and there are 3 elements in it, as:
int marks[]=new int[10]; //size is 10
marks[0]=50, marks[1]=60, marks[2]=80; //number of elements is 3
Now, marks.length gives 10. The array marks[] contained 3 elements, but length property does not give the
number of elements of the array. It gives only its size.
But, in case of a two or three dimensional array, ‘length’ property gives the number of rows of the array, as:
int marks[][]=new int[3][5];
int marks[][][]=new int[3][2][5];
In the preceding two cases, marks.length gives 3.
Command line arguments: command line arguments represent the values passed to main () method. To
catch and store these values, main () has a parameter, String args[] as :
public static void main(String args[])
Here, args[] is a one dimensional array of string type. So it can store a group of strings, passed to main ()
from outside by the user. The user should pass the values from outside, at the time of running the program at
command prompt, as:
c:\> java demo 24 01 1984 vbr
The four values passed to main() method at the time of running the program are 24, 01, 1984 and vbr. These
values are automatically stored in the main() method’s args[] in the form of strings. The JVM allot memory
for those 4 values only. If there are no command line arguments, then JVM will not allot any memory. So
the size of ‘args’ is same as the number of arguments passed to it.
E.g.:
class demo
{
public static void main(String args[])
{
int n=args.length;
System.out.println("The number of arguements="+n);
System.out.println("The arguements are:");
for(int i=0;i<n;i++)
System.out.println(args[i]);
}
}
O/P: J:\>javac command.java
J:\>java demo 24 01 1984 vbr
The number of arguements=4
The arguements are:
24
01
1984
Vbr

ArrayIndexOutOfBoundsException

The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in
negative, equal to the array size or greater than the array size while traversing the array.
4
//Java Program to demonstrate the case of ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}}

Variable Arguments (Varargs) in Java:


Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable
Arguments in Java simplifies the creation of methods that need to take a variable number of arguments.

Need of Java Varargs:


 Until JDK 4, we can’t declare a method with variable no. of arguments. If there is any change
in the number of arguments, we have to declare a new method. This approach increases the
length of the code and reduces readability.
 Before JDK 5, variable-length arguments could be handled in two ways. One uses an
overloaded method(one for each), and another puts the arguments into an array and then passes
this array to the method. Both of them are potentially error-prone and require more code.
 To resolve these problems, Variable Arguments (Varargs) were introduced in JDK 5. From
JDK 5 onwards, we can declare a method with a variable number of arguments. Such types of
methods are called Varargs methods. The varargs feature offers a simpler, better option.
Syntax of Varargs
Internally, the Varargs method is implemented by using the single dimensions arrays concept. Hence,
in the Varargs method, we can differentiate arguments by using Index. A variable-length argument is
specified by three periods or dots(…).
For Example,
public static void fun(int ... a)
{
// method body
}
This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here, a is
implicitly declared as an array of type int[].
// Java program to demonstrate varargs

class Test1 {
// A method that takes variable
// number of integer arguments.
static void fun(int... a)
{
System.out.println("Number of arguments: "
+ a.length);

// using for each loop to display contents of a


5
for (int i : a)
System.out.print(i + " ");
System.out.println();
}

// Driver code
public static void main(String args[])
{
// Calling the varargs method with
// different number of parameters

// one parameter
fun(100);

// four parameters
fun(1, 2, 3, 4);

// no parameter
fun();
}
}
Output:
Number of arguments: 1
100
Number of arguments: 4
1234
Number of arguments: 0
Explanation of the above program
 The … syntax tells the compiler that varargs have been used, and these arguments should be
stored in the array referred to by a.
 The variable a is operated on as an array. In this case, we have defined the data type of an array
‘a’ as int. So it can take only integer values. The number of arguments can be found out using
a.length, the way we find the length of an array in Java.
Note: A method can have variable length parameters with other parameters too, but one should ensure that
there exists only one varargs parameter that should be written last in the parameter list of the method
declaration. For example:
int nums(int a, float b, double … c)
In this case, the first two arguments are matched with the first two parameters, and the remaining
arguments belong to c.
// Java program to demonstrate
// varargs with normal arguments

class Test2 {
// Takes string as a argument followed by varargs
static void fun2(String str, int... a)
{
6
System.out.println("String: " + str);
System.out.println("Number of arguments is: "
+ a.length);

// using for each loop to display contents of a


for (int i : a)
System.out.print(i + " ");

System.out.println();
}

public static void main(String args[])


{
// Calling fun2() with different parameter
fun2("GeeksforGeeks", 100, 200);
fun2("CSPortal", 1, 2, 3, 4, 5);
fun2("forGeeks");
}
}
Output:
String: GeeksforGeeks
Number of arguments is: 2
100 200
String: CSPortal
Number of arguments is: 5
12345
String: forGeeks
Number of arguments is: 0
Strings in Java:
In C/C++ languages, a string represents an array of characters, where the last character will be ‘\0’ called
null character. This last character being ‘\0’ represents the end of the string. But this is not valid in java. In
java string is an object of String class. It is not a character array. Java soft people have created a class
separately with the name ‘String’ in java.lang (language) package with all necessary methods to work which
strings. Even though, String is a class, it is used often in the form of data type, as:
String s=”java”;
Creating strings:
How to create a string object?

There are two ways to create String object:

1. By string literal
2. By new keyword

7
1) String Literal

Java String literal is created by using double quotes. For Example:

String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already
exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not find any string object with the
value "Welcome" in string constant pool that is why it will create a new object. After that it will find the
string with the value "Welcome" in the pool, it will not create a new object but will return the reference to
the same instance.

2) By new keyword
String s=new String("Welcome"); //creates two objects and one reference variable

In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-
pool).

E.g.:

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
8
Java String class methods
The java.lang.String class provides many useful methods to perform operations on
sequence of char values.

String Methods in Java


1. int length()
Returns the number of characters in the String.
"GeeksforGeeks".length(); // returns 13
2. Char charAt(int i)
Returns the character at ith index.
"GeeksforGeeks".charAt(3); // returns ‘k’
3. String substring (int i)
Return the substring from the ith index character to end.
"GeeksforGeeks".substring(3); // returns “ksforGeeks”
4. String substring (int i, int j)
Returns the substring from i to j-1 index.
"GeeksforGeeks".substring(2, 5); // returns “eks”
5. String concat( String str)
Concatenates specified string to the end of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”
6. int indexOf (String s)
Returns the index within the string of the first occurrence of the specified string.
If String s is not present in input string then -1 is returned as the default value.
1. String s = ”Learn Share Learn”;
int output = s.indexOf(“Share”); // returns 6
2. String s = "Learn Share Learn"
int output = s.indexOf(“Play”); // return -1
7. int indexOf (String s, int i)
Returns the index within the string of the first occurrence of the specified string, starting at the specified
index.
String s = ”Learn Share Learn”;
int output = s.indexOf("ea",3);// returns 13
8. Int lastIndexOf( String s)
Returns the index within the string of the last occurrence of the specified string.
If String s is not present in input string then -1 is returned as the default value.
1. String s = ”Learn Share Learn”;
int output = s.lastIndexOf("a"); // returns 14
2. String s = "Learn Share Learn"
int output = s.indexOf(“Play”); // return -1
9. boolean equals( Object otherObj)
Compares this string to the specified object.
Boolean out = “Geeks”.equals(“Geeks”); // returns true
Boolean out = “Geeks”.equals(“geeks”); // returns false
10. boolean equalsIgnoreCase (String anotherString)
Compares string to another string, ignoring case considerations.
Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true

9
11. int compareTo( String anotherString)
Compares two string lexicographically.
int out = s1.compareTo(s2);
// where s1 and s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
12. int compareToIgnoreCase( String anotherString)
Compares two string lexicographically, ignoring case considerations.
int out = s1.compareToIgnoreCase(s2);
// where s1 and s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
Note: In this case, it will not consider case of a letter (it will ignore whether it is uppercase or lowercase).
13. String toLowerCase()
Converts all the characters in the String to lower case.
String word1 = “HeLLo”;
String word3 = word1.toLowerCase(); // returns “hello"
14. String toUpperCase()
Converts all the characters in the String to upper case.
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”
15. String trim()
Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the
middle.
String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn”
16. String replace (char oldChar, char newChar)
Returns new string by replacing all occurrences of oldChar with newChar.
String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // return “geeksforgeeks”
Note: s1 is still feeksforfeeks and s2 is geeksgorgeeks
17. boolean contains(string) :
Returns true if string contains contains the given string
String s1="geeksforgeeks";
String s2="geeks";
s1.contains(s2) // return true
18. Char[] toCharArray():
Converts this String to a new character array.
String s1="geeksforgeeks";
char []ch=s1.toCharArray(); // returns [ 'g', 'e' , 'e' , 'k' , 's' , 'f', 'o', 'r' , 'g' , 'e' , 'e' , 'k' ,'s' ]
19. boolean startsWith(string):
Return true if string starts with this prefix.
String s1="geeksforgeeks";
String s2="geeks";
s1.startsWith(s2) // return true

10
20. boolean endsWith(string):
Return true if string starts with this prefix.
String s1="geeksforgeeks";
String s2="geeks";
s1.endsWith(s2) // return true

E.g.:

class Test
{
// main function
public static void main (String[] args)
{
String s= "GeeksforGeeks";
// or String s= new String ("GeeksforGeeks");

// Returns the number of characters in the String.


System.out.println("String length = " + s.length());

// Returns the character at ith index.


System.out.println("Character at 3rd position = "+ s.charAt(3));

// Return the substring from the ith index character


// to end of string
System.out.println("Substring " + s.substring(3));

// Returns the substring from i to j-1 index.


System.out.println("Substring = " + s.substring(2,5));

// Concatenates string2 to the end of string1.


String s1 = "Geeks";
String s2 = "forGeeks";
System.out.println("Concatenated string = " +s1.concat(s2));

// Returns the index within the string


// of the first occurrence of the specified string.
String s4 = "Learn Share Learn";
System.out.println("Index of Share " + s4.indexOf("Share"));

// Returns the index within the string of the


// first occurrence of the specified string,
// starting at the specified index.
System.out.println("Index of a = " +s4.indexOf('a',3));

// Checking equality of Strings


Boolean out = "Geeks".equals("geeks");
System.out.println("Checking Equality " + out);
out = "Geeks".equals("Geeks");
System.out.println("Checking Equality " + out);

out = "Geeks".equalsIgnoreCase("gEeks ");


System.out.println("Checking Equality " + out);

11
//If ASCII difference is zero then the two strings are similar
int out1 = s1.compareTo(s2);
System.out.println("the difference between ASCII value is="+out1);
// Converting cases
String word1 = "GeeKyMe";
System.out.println("Changing to lower Case " +word1.toLowerCase());

// Converting cases
String word2 = "GeekyME";
System.out.println("Changing to UPPER Case " +word2.toUpperCase());

// Trimming the word


String word4 = " Learn Share Learn ";
System.out.println("Trim the word " + word4.trim());

// Replacing characters
String str1 = "feeksforfeeks";
System.out.println("Original String " + str1);
String str2 = "feeksforfeeks".replace('f' ,'g') ;
System.out.println("Replaced f with g -> " + str2);
}
}

Output
String length = 13
Character at 3rd position = k
Substring ksforGeeks
Substring = eks
Concatenated string = GeeksforGeeks
Index of Share 6
Index of a = 8
Checking Equality false
Checking Equality ...

Immutable String in Java

A String is an unavoidable type of variable while writing any application program. String references are
used to store various attributes like username, password, etc. In Java, String objects are immutable.
Immutable simply means unmodifiable or unchangeable.

Once String object is created its data or state can't be changed but a new String object is created.

Let's try to understand the concept of immutability by the example given below:

E.g.:

12
Testimmutablestring.java

class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:
Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new object is
created with Sachin Tendulkar. That is why String is known as immutable.

As you can see in the above figure that two objects are created but s reference variable still refers to
"Sachin" not to "Sachin Tendulkar".

But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.

For example:

Testimmutablestring1.java

class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output: Sachin Tendulkar

In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is not modified.

13
StringBuffer class in Java
StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an alternative
to the immutable String class, allowing you to modify the contents of a string without creating a new
object every time.
Here are some important features and methods of the StringBuffer class:
1. StringBuffer objects are mutable, meaning that you can change the contents of the buffer
without creating a new object.
2. The initial capacity of a StringBuffer can be specified when it is created, or it can be set later
with the ensureCapacity() method.
3. The append() method is used to add characters, strings, or other objects to the end of the buffer.
4. The insert() method is used to insert characters, strings, or other objects at a specified position
in the buffer.
5. The delete() method is used to remove characters from the buffer.
6. The reverse() method is used to reverse the order of the characters in the buffer.

Method Description

append(String s) It is used to append the specified string with this


string. The append() method is overloaded like
append(char), append(boolean), append(int),
append(float), append(double) etc.

insert(int offset, String s) It is used to insert the specified string with this string
at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.

replace(int startIndex, int endIndex, String It is used to replace the string from specified
str) startIndex and endIndex.

delete(int startIndex, int endIndex) It is used to delete the string from specified startIndex
and endIndex.

reverse() is used to reverse the string.

capacity() It is used to return the current capacity.

ensureCapacity(int minimumCapacity) It is used to ensure the capacity at least equal to the


given minimum.

charAt(int index) It is used to return the character at the specified


position.

length() It is used to return the length of the string i.e. total


number of characters.

substring(int beginIndex) It is used to return the substring from the specified


beginIndex.

substring(int beginIndex, int endIndex) It is used to return the substring from the specified
beginIndex and endIndex.

14
E.g.:

class stringbuffer
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Narayana Engineering College, Gudur");
System.out.println(sb.length());
System.out.println(sb.indexOf("n"));
System.out.println(sb.lastIndexOf("n"));
System.out.println(sb.delete(2, 10));
System.out.println(sb.reverse());
sb.append("i mca");
System.out.println(sb);
sb.insert(10, "java programming");
System.out.println(sb);
System.out.println(sb.delete(2, 10));
StringBuffer sb1=new StringBuffer("java is object oriented programming language");
String s1=sb1.substring(7, 20);
System.out.println(s1);
StringBuffer sb3=new StringBuffer("low cost");
System.out.println(sb3.replace(0,3,"high"));
}
}

Output:

D:\java>javac stringb.java

D:\java>java stringbuffer
35
6
18
Nangineering College, Gudur
ruduG ,egelloC gnireenignaN
ruduG ,egelloC gnireenignaNi mca
ruduG ,egejava programminglloC gnireenignaNi mca
rujava programminglloC gnireenignaNi mca
object orien
high cost

StringBuilder Class in Java


StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates
an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it
creates a mutable sequence of characters. The function of StringBuilder is very much similar to the
StringBuffer class, as both of them provide an alternative to String Class by making a mutable sequence of
characters. However, the StringBuilder class differs from the StringBuffer class on the basis of
synchronization. The StringBuilder class provides no guarantee of synchronization whereas the
StringBuffer class does. Therefore this class is designed for use as a drop-in replacement for StringBuffer
15
in places where the StringBuffer was being used by a single thread (as is generally the case). Where
possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under
most implementations. Instances of StringBuilder are not safe for use by multiple threads. If such
synchronization is required then it is recommended that StringBuffer be used. String Builder is not thread-
safe and high in performance compared to String buffer.

Method Description

append(String s) It is used to append the specified string with this


string. The append() method is overloaded like
append(char), append(boolean), append(int),
append(float), append(double) etc.

insert(int offset, String s) It is used to insert the specified string with this string
at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.

replace(int startIndex, int endIndex, String It is used to replace the string from specified
str) startIndex and endIndex.

delete(int startIndex, int endIndex) It is used to delete the string from specified startIndex
and endIndex.

reverse() is used to reverse the string.

capacity() It is used to return the current capacity.

ensureCapacity(int minimumCapacity) It is used to ensure the capacity at least equal to the


given minimum.

charAt(int index) It is used to return the character at the specified


position.

length() It is used to return the length of the string i.e. total


number of characters.

substring(int beginIndex) It is used to return the substring from the specified


beginIndex.

substring(int beginIndex, int endIndex) It is used to return the substring from the specified
beginIndex and endIndex.

Difference between StringBuffer and StringBuilder:

Java provides three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder.
The String class is an immutable class whereas StringBuffer and StringBuilder classes are mutable. There
are many differences between StringBuffer and StringBuilder. The StringBuilder class is introduced since
JDK 1.5.

A list of differences between StringBuffer and StringBuilder is given below:


16
No. StringBuffer StringBuilder

1) StringBuffer is synchronized i.e. thread safe. StringBuilder is non-synchronized i.e. not


It means two threads can't call the methods of thread safe. It means two threads can call the
StringBuffer simultaneously. methods of StringBuilder simultaneously.

2) StringBuffer is less efficient than StringBuilder is more efficient than


StringBuilder. StringBuffer.

3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5

Wrapper classes in Java

The wrapper class in Java provides the mechanism to convert primitive into object and object into
primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into
primitives automatically. The automatic conversion of primitive into an object is known as autoboxing
and vice-versa unboxing.

Use of Wrapper classes in Java

Java is an object-oriented programming language, so we need to deal with objects many times like in
Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where we need to use
the wrapper classes.
Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will
not change the original value. But, if we convert the primitive value in an object, it will change the
original value.
Serialization: We need to convert the objects into streams to perform the serialization. If we have a
primitive value, we can convert it in objects through the wrapper classes.
Synchronization: Java synchronization works with objects in Multithreading.
java.util package: The java.util package provides the utility classes to deal with objects.
Collection Framework: Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue,
ArrayDeque, etc.) deal with objects only.
The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight
wrapper classes are given below:

Primitive Wrapper class


Type

boolean Boolean

char Character

17
byte Byte

short Short

int Integer

long Long

float Float

double Double

Autoboxing

The automatic conversion of primitive data type into its corresponding wrapper class is known as
autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float,
boolean to Boolean, double to Double, and short to Short.

Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the primitive
into objects.

Wrapper class Example: Primitive to Wrapper


//Java program to convert primitive into objects
//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(a+" "+i+" "+j);


}}

Unboxing

The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It
is the reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of
wrapper classes to convert the wrapper type into primitives.

Wrapper class Example: Wrapper to Primitive


//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){

18
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);


}}

Java Wrapper classes Example


/Java Program to convert all primitives into its corresponding
//wrapper objects and vice-versa
public class WrapperExample3{
public static void main(String args[]){
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;

//Autoboxing: Converting primitives into objects


Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;

//Printing objects
System.out.println("---Printing object values---");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
19
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);

//Unboxing: Converting Objects to Primitives


byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;

//Printing primitives
System.out.println("---Printing primitive values---");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}}

Output:
---Printing object values---
Byte object: 10
Short object: 20
Integer object: 30
Long object: 40
Float object: 50.0
Double object: 60.0
Character object: a
Boolean object: true
---Printing primitive values---
byte value: 10
short value: 20
int value: 30
long value: 40
float value: 50.0
double value: 60.0
char value: a
boolean value: true

20

You might also like