You are on page 1of 48

next →← prev

Java Arrays
Normally, an array is a collection of similar type of elements which have a contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, The elements of an

array are stored in a contiguous memory location. It is a data structure where we store similar elements.

We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored

on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the

sizeof operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and

implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an

array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
o runtime. To solve this problem, collection framework is used in Java which grows automatically.

Types of Array in java


There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

1. dataType[] arr; (or)

2. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

Example of Java Array


Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an

1. //Java Program to illustrate how to declare, instantiate, initialize


2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}

Test it Now

Output:

10
20
70
40
50

Declaration, Instantiation and Initialization of Java Arr


We can declare, instantiate and initialize the java array together by:

1. int a[]={33,3,4,5};//declaration, instantiation and initialization

Let's see the simple example to print this array.

1. //Java Program to illustrate the use of declaration, instantiation


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

Test it Now
Output:

33
3
4
5

For-each Loop for Java Array


We can also print the Java array using for-each loop. The Java for-each loop prints the array elements

one by one. It holds an array element in a variable, then executes the body of the loop.

JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables
you to traverse the complete array sequentially without using an index variable.

The syntax of the for-each loop is given below:

1. for(data_type variable:array){
2. //body of the loop
3. }

Let us see the example of print the elements of Java array using the for-each loop.

1. //Java Program to print the array elements using for-each loop


2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. //printing array using for-each loop
6. for(int i:arr)
7. System.out.println(i);
8. }}

Output:

33
3
4
5

Example

The following code displays all the elements in the array myList −

public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (double element: myList) {
System.out.println(element);
}
}
}

This will produce the following result −

Output
1.9
2.9
3.4
3.5

Passing Array to a Method in Java


We can pass the java array to method so that we can reuse the same logic on any array.

Let's see the simple example to get the minimum number of an array using a method.

1. //Java Program to demonstrate the way of passing an array


2. //to method.
3. class Testarray2{
4. //creating a method which receives an array as a parameter
5. static void min(int arr[]){
6. int min=arr[0];
7. for(int i=1;i<arr.length;i++)
8. if(min>arr[i])
9. min=arr[i];
10.
11. System.out.println(min);
12. }
13.
14. public static void main(String args[]){
15. int a[]={33,3,4,5};//declaring and initializing an array
16. min(a);//passing array to method
17. }}

Test it Now

Output:

Anonymous Array in Java


Java supports the feature of an anonymous array, so you don't need to declare the array while passing

an array to the method.

1. //Java Program to demonstrate the way of passing an anonymous array


2. //to method.
3. public class TestAnonymousArray{
4. //creating a method which receives an array as a parameter
5. static void printArray(int arr[]){
6. for(int i=0;i<arr.length;i++)
7. System.out.println(arr[i]);
8. }
9.
10. public static void main(String args[]){
11. printArray(new int[]{10,22,44,66});//passing anonymous array to method
12. }}

Test it Now

Output:

10
22
44
66

Returning Array from the Method


We can also return an array from the method in Java.

1. //Java Program to return an array from the method


2. class TestReturnArray{
3. //creating method which returns an array
4. static int[] get(){
5.[1.] int a[]=new int[5];
6.[2.] a={10,30,50,90,60};
7. return (a);
8. }
9.
10. public static void main(String args[]){
11. //calling method which returns an array
12. int arr[]=get();
13. //printing the values of an array
14. for(int i=0;i<arr.length;i++)
15. System.out.println(arr[i]);
16. }}

Test it Now

Output:

10
30
50
90
60
Or
public class TestReturnArray{
//creating method which returns an array
static int[] get(){
int a[]={10,30,50,90,60};
return (a);
}

public static void main(String args[]){


//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}}

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.

1. //Java Program to demonstrate the case of


2. //ArrayIndexOutOfBoundsException in a Java Array.
3. public class TestArrayException{
4. public static void main(String args[]){
5. int arr[]={50,60,70,80};
6. for(int i=0;i<=arr.length;i++){
7. System.out.println(arr[i]);
8. }
9. }}

Test it Now

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4


at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
Multidimensional Array in Java
In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

1. int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;

Example of Multidimensional Java Array


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

1. //Java Program to illustrate the use of multidimensional array


2. class Testarray3{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }}

Test it Now

Output:

1 2 3
2 4 5
4 4 5

Addition of 2 Matrices in Java


Let's see a simple example that adds two matrices.

1. //Java Program to demonstrate the addition of two matrices in Java


2. class Testarray5{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,3,4},{3,4,5}};
6. int b[][]={{1,3,4},{3,4,5}};
7.
8. //creating another matrix to store the sum of two matrices
9. int c[][]=new int[2][3];
10.
11. //adding and printing addition of 2 matrices
12. for(int i=0;i<2;i++){
13. for(int j=0;j<3;j++){
14. c[i][j]=a[i][j]+b[i][j];
15. System.out.print(c[i][j]+" ");
16. }
17. System.out.println();//new line
18. }
19.
20. }}

Test it Now
Output:

2 6 8
6 8 10

Multiplication of 2 Matrices in Java


In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the columns of the
matrix which can be understood by the image given below.

Let's see a simple example to multiply two matrices of 3 rows and 3 columns.

1. //Java Program to multiply two matrices


2. public class MatrixMultiplicationExample{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,1,1},{2,2,2},{3,3,3}};
6. int b[][]={{1,1,1},{2,2,2},{3,3,3}};
7.
8. //creating another matrix to store the multiplication of two matrices
9. int c[][]=new int[3][3]; //3 rows and 3 columns
10.
11. //multiplying and printing multiplication of 2 matrices
12. for(int i=0;i<3;i++){
13. for(int j=0;j<3;j++){
14. c[i][j]=0;
15. for(int k=0;k<3;k++)
16. {
17. c[i][j]=c[i][j]+a[i][k]*b[k][j];
18. }//end of k loop
19. System.out.print(c[i][j]+" "); //printing matrix element
20. }//end of j loop
21. System.out.println();//new line
22. }
23. }}

Test ita Now

Output:

6 6 6
12 12 12
18 18 18

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.

o 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.
o 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.
o Synchronization: Java synchronization works with objects in Multithreading.
o java.util package: The java.util package provides the utility classes to deal with
objects.
o 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 Type Wrapper class

Boolean Boolean

Char Character

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


1. //Java program to convert primitive into objects
2. //Autoboxing example of int to Integer
3. public class WrapperExample1{
4. public static void main(String args[]){
5. //Converting int into Integer
6. int a=20;
7. Integer i=Integer.valueOf(a);//converting int into Integer explicitly
8. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
9.
10. System.out.println(a+" "+i+" "+j);
11. }}

Output:

20 20 20

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

1. //Java program to convert object into primitives


2. //Unboxing example of Integer to int
3. public class WrapperExample2{
4. public static void main(String args[]){
5. //Converting Integer to int
6. Integer a=new Integer(3);
7. int i=a.intValue();//converting Integer to int explicitly
8. int j=a;//unboxing, now compiler will write a.intValue() internally
9.
10. System.out.println(a+" "+i+" "+j);
11. }}

Output:

3 3 3

Bubble Sort in Java


We can create a java program to sort array elements using bubble sort. Bubble sort
algorithm is known as the simplest sorting algorithm.

In bubble sort algorithm, array is traversed from first element to last element. Here, current
element is compared with the next element. If current element is greater than the next
element, it is swapped.

1. public class BubbleSortExample {


2. static void bubbleSort(int[] arr) {
3. int n = arr.length;
4. int temp = 0;
5. for(int i=0; i < n; i++){
6. for(int j=1; j < (n-i); j++){
7. if(arr[j-1] > arr[j]){
8. //swap elements
9. temp = arr[j-1];
10. arr[j-1] = arr[j];
11. arr[j] = temp;
12. }
13.
14. }
15. }
16.
17. }
18. public static void main(String[] args) {
19. int arr[] ={3,60,35,2,45,320,5};
20.
21. System.out.println("Array Before Bubble Sort");
22. for(int i=0; i < arr.length; i++){
23. System.out.print(arr[i] + " ");
24. }
25. System.out.println();
26.
27. bubbleSort(arr);//sorting array elements using bubble sort
28.
29. System.out.println("Array After Bubble Sort");
30. for(int i=0; i < arr.length; i++){
31. System.out.print(arr[i] + " ");
32. }
33.
34. }
35. }
Output:

Array Before Bubble Sort


3 60 35 2 45 320 5
Array After Bubble Sort
2 3 5 35 45 60 320

/* Java program to implement basic stack


operations */
class Stack {
static final int MAX = 1000;
int top;
int a[] = new int[MAX]; // Maximum size of Stack

boolean isEmpty()
{
return (top < 0);
}
Stack()
{
top = -1;
}

boolean push(int x)
{
if (top >= (MAX - 1)) {
System.out.println("Stack Overflow");
return false;
}
else {
a[++top] = x;
System.out.println(x + " pushed into stack");
return true;
}
}

int pop()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top--];
return x;
}
}

int peek()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top];
return x;
}
}
}

// Driver code
class Main {
public static void main(String args[])
{
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop() + " Popped from stack");
}
}
Pros: Easy to implement. Memory is saved as pointers are not involved.
Cons: It is not dynamic. It doesn’t grow and shrink depending on needs at runtime.
Output :
10 pushed into stack
20 pushed into stack
30 pushed into stack
30 popped from stack

Strings, which are widely used in Java programming, are a sequence of characters.
In Java programming language, strings are treated as objects.
The Java platform provides the String class to create and manipulate strings.

Creating Strings
The most direct way to create a string is to write −
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String
object with its value in this case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword and
a constructor. The String class has 11 constructors that allow you to provide the initial
value of the string using different sources, such as an array of characters.

Example

Live Demo
public class StringDemo {

public static void main(String args[]) {


char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}

This will produce the following result −

Output
hello.
Note − The String class is immutable, so that once it is created a String object cannot
be changed. If there is a necessity to make a lot of modifications to Strings of
characters, then you should use String Buffer & String Builder Classes.

String Length
Methods used to obtain information about an object are known as accessor methods.
One accessor method that you can use with strings is the length() method, which
returns the number of characters contained in the string object.
The following program is an example of length(), method String class.

Example

Live Demo

public class StringDemo {

public static void main(String args[]) {


String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}

This will produce the following result −

Output
String Length is : 17

Concatenating Strings
The String class includes a method for concatenating two strings −
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also
use the concat() method with string literals, as in −
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in −
"Hello," + " world" + "!"
which results in −
"Hello, world!"
Let us look at the following example −

Example

Live Demo

public class StringDemo {

public static void main(String args[]) {


String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}

This will produce the following result −

Output
Dot saw I was Tod

Creating Format Strings


You have printf() and format() methods to print output with formatted numbers. The
String class has an equivalent class method, format(), that returns a String object
rather than a PrintStream object.
Using String's static format() method allows you to create a formatted string that you
can reuse, as opposed to a one-time print statement. For example, instead of −

Example

System.out.printf("The value of the float variable is " +


"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);

You can write −


String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);

String Methods
Here is the list of methods supported by String class −

Sr.No. Method & Description

1 char charAt(int index)

Returns the character at the specified index.

2 int compareTo(Object o)

Compares this String to another Object.

3 int compareTo(String anotherString)

Compares two strings lexicographically.

4 int compareToIgnoreCase(String str)

Compares two strings lexicographically, ignoring case differences.

5 String concat(String str)

Concatenates the specified string to the end of this string.

6 boolean contentEquals(StringBuffer sb)

Returns true if and only if this String represents the same sequence of
characters as the specified StringBuffer.
7 static String copyValueOf(char[] data)

Returns a String that represents the character sequence in the array


specified.

8 static String copyValueOf(char[] data, int offset, int count)

Returns a String that represents the character sequence in the array


specified.

9 boolean endsWith(String suffix)

Tests if this string ends with the specified suffix.

10 boolean equals(Object anObject)

Compares this string to the specified object.

11 boolean equalsIgnoreCase(String anotherString)

Compares this String to another String, ignoring case considerations.

12 byte getBytes()

Encodes this String into a sequence of bytes using the platform's default
charset, storing the result into a new byte array.

13 byte[] getBytes(String charsetName)

Encodes this String into a sequence of bytes using the named charset,
storing the result into a new byte array.

14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

Copies characters from this string into the destination character array.

15 int hashCode()

Returns a hash code for this string.

16 int indexOf(int ch)

Returns the index within this string of the first occurrence of the specified
character.

17 int indexOf(int ch, int fromIndex)

Returns the index within this string of the first occurrence of the specified
character, starting the search at the specified index.

18 int indexOf(String str)

Returns the index within this string of the first occurrence of the specified
substring.

19 int indexOf(String str, int fromIndex)

Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index.

20 String intern()

Returns a canonical representation for the string object.

21 int lastIndexOf(int ch)

Returns the index within this string of the last occurrence of the specified
character.

22 int lastIndexOf(int ch, int fromIndex)

Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified index.

23 int lastIndexOf(String str)

Returns the index within this string of the rightmost occurrence of the
specified substring.

24 int lastIndexOf(String str, int fromIndex)

Returns the index within this string of the last occurrence of the specified
substring, searching backward starting at the specified index.

25 int length()
Returns the length of this string.

26 boolean matches(String regex)

Tells whether or not this string matches the given regular expression.

27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset,


int len)

Tests if two string regions are equal.

28 boolean regionMatches(int toffset, String other, int ooffset, int len)

Tests if two string regions are equal.

29 String replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar


in this string with newChar.

30 String replaceAll(String regex, String replacement

Replaces each substring of this string that matches the given regular
expression with the given replacement.

31 String replaceFirst(String regex, String replacement)

Replaces the first substring of this string that matches the given regular
expression with the given replacement.

32 String[] split(String regex)

Splits this string around matches of the given regular expression.

33 String[] split(String regex, int limit)

Splits this string around matches of the given regular expression.

34 boolean startsWith(String prefix)

Tests if this string starts with the specified prefix.

35 boolean startsWith(String prefix, int toffset)


Tests if this string starts with the specified prefix beginning a specified
index.

36 CharSequence subSequence(int beginIndex, int endIndex)

Returns a new character sequence that is a subsequence of this


sequence.

37 String substring(int beginIndex)

Returns a new string that is a substring of this string.

38 String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.

39 char[] toCharArray()

Converts this string to a new character array.

40 String toLowerCase()

Converts all of the characters in this String to lower case using the rules
of the default locale.

41 String toLowerCase(Locale locale)

Converts all of the characters in this String to lower case using the rules
of the given Locale.

42 String toString()

This object (which is already a string!) is itself returned.

43 String toUpperCase()

Converts all of the characters in this String to upper case using the rules
of the default locale.

44 String toUpperCase(Locale locale)


Converts all of the characters in this String to upper case using the rules
of the given Locale.

45 String trim()

Returns a copy of the string, with leading and trailing whitespace


omitted.

46 static String valueOf(primitive data type x)

Returns the string representation of the passed data type argument.

Java StringBuffer class


Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class
in java is same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.

Important Constructors of StringBuffer class

Constructor Description

StringBuffer() creates an empty string buffer with the initial capacity of 16.

StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int capacity) creates an empty string buffer with the specified capacity as lengt

Important methods of StringBuffer class

Modifier and Method Description


Type

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


synchronized
string. The append() method is overloaded like
StringBuffer

append(char), append(boolean), append(int),

append(float), append(double) etc.

public insert(int offset, is used to insert the specified string with this
synchronized String s)
string at the specified position. The insert()
StringBuffer

method is overloaded like insert(int, char),

insert(int, boolean), insert(int, int), insert(int, float),

insert(int, double) etc.

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

public delete(int is used to delete the string from specified startIndex


synchronized startIndex, int
and endIndex.
StringBuffer endIndex)

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() is used to return the current capacity.

public void ensureCapacity(int is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.

public char charAt(int index) is used to return the character at the specified position.

public int length() is used to return the length of the string i.e. total number

of characters.

public String substring(int is used to return the substring from the specified
beginIndex)
beginIndex.

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

What is mutable string


A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.

1) StringBuffer append() method


The append() method concatenates the given argument with this string.

1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }

2) StringBuffer insert() method


The insert() method inserts the given string with this string at the given position.
1. class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }

3) StringBuffer replace() method


The replace() method replaces the given string from the specified beginIndex and endIndex.

1. class StringBufferExample3{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }

4) StringBuffer delete() method


The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.

1. class StringBufferExample4{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }

5) StringBuffer reverse() method


The reverse() method of StringBuilder class reverses the current string.

1. class StringBufferExample5{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }

6) StringBuffer capacity() method


The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current
capacity is 16, it will be (16*2)+2=34.

1. class StringBufferExample6{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }

7) StringBuffer ensureCapacity() method


The ensureCapacity() method of StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.

1. class StringBufferExample7{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }
StringBuffer class in Java
StringBuffer is a peer class of String that provides much of the functionality of strings.
String represents fixed-length, immutable character sequences while StringBuffer
represents growable and writable character sequences.

StringBuffer may have characters and substrings inserted in the middle or appended to
the end. It will automatically grow to make room for such additions and often has more
characters preallocated than are actually needed, to allow room for growth.

StringBuffer Constructors

StringBuffer( ): It reserves room for 16 characters without reallocation.


StringBuffer s=new StringBuffer();

StringBuffer( int size)It accepts an integer argument that explicitly sets the size of the
buffer.
StringBuffer s=new StringBuffer(20);

StringBuffer(String str): It accepts a String argument that sets the initial contents of
the StringBuffer object and reserves room for 16 more characters without reallocation.
StringBuffer s=new StringBuffer("GeeksforGeeks");

Methods
Some of the most used methods are:
 length( ) and capacity( ): The length of a StringBuffer can be found by the
length( ) method, while the total allocated capacity can be found by the capacity( )
method.
Code Example:

import java.io.*;
class GFG {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("GeeksforGeeks");
int p = s.length();
int q = s.capacity();
System.out.println("Length of string GeeksforGeeks=" + p);
System.out.println("Capacity of string GeeksforGeeks=" + q);
}
}
Output:
Length of string GeeksforGeeks=13
Capacity of string GeeksforGeeks=29
 append( ): It is used to add text at the end of the existence text. Here are a few of
its forms:
 StringBuffer append(String str)
 StringBuffer append(int num)
Code Example:

import java.io.*;
class GFG {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("Geeksfor");
s.append("Geeks");
System.out.println(s); // returns GeeksforGeeks
s.append(1);
System.out.println(s); // returns GeeksforGeeks1
}
}
Output:

GeeksforGeeks
GeeksforGeeks1
 insert( ): It is used to insert text at the specified index position. These are a few of
its forms:
 StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
Here, index specifies the index at which point the string will be inserted into the
invoking StringBuffer object.

Code Example:

import java.io.*;
class GFG {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("GeeksGeeks");
s.insert(5, "for");
System.out.println(s); // returns GeeksforGeeks

s.insert(0, 5);
System.out.println(s); // returns 5GeeksforGeeks

s.insert(3, true);
System.out.println(s); // returns 5GetrueeksforGeeks

s.insert(5, 41.35d);
System.out.println(s); // returns 5Getr41.35ueeksforGeeks
s.insert(8, 41.35f);
System.out.println(s); // returns 5Getr41.41.3535ueeksforGeeks

char geeks_arr[] = { 'p', 'a', 'w', 'a', 'n' };

// insert character array at offset 9


s.insert(2, geeks_arr);
System.out.println(s); // returns 5Gpawanetr41.41.3535ueeksforGeeks
}
}
Output:
GeeksforGeeks
5GeeksforGeeks
5GetrueeksforGeeks
5Getr41.35ueeksforGeeks
5Getr41.41.3535ueeksforGeeks
5Gpawanetr41.41.3535ueeksforGeeks
 reverse( ): It can reverse the characters within a StringBuffer object
using reverse( ).This method returns the reversed object on which it was called.

Code Example:

import java.io.*;
class GFG {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("GeeksGeeks");
s.reverse();
System.out.println(s); // returns skeeGrofskeeG
}
}
Output:
skeeGskeeG
 delete( ) and deleteCharAt( ): It can delete characters within a StringBuffer by
using the methods delete( ) and deleteCharAt( ).The delete( ) method deletes a
sequence of characters from the invoking object. Here, start Index specifies the
index of the first character to remove, and end Index specifies an index one past
the last character to remove. Thus, the substring deleted runs from start Index to
endIndex–1. The resulting StringBuffer object is returned. The
deleteCharAt( ) method deletes the character at the index specified by loc. It
returns the resulting StringBuffer object.These methods are shown here:

 StringBuffer delete(int startIndex, int endIndex)
 StringBuffer deleteCharAt(int loc)
Code Example:

import java.io.*;
class GFG {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("GeeksforGeeks");
s.delete(0, 5);
System.out.println(s); // returns forGeeks
s.deleteCharAt(7);
System.out.println(s); // returns forGeek
}
}
Output:
forGeeks
forGeek
 replace( ): It can replace one set of characters with another set inside a
StringBuffer object by calling replace( ). The substring being replaced is specified
by the indexes start Index and endIndex. Thus, the substring at start Index through
endIndex–1 is replaced. The replacement string is passed in str.The resulting
StringBuffer object is returned.Its signature is shown here:

StringBuffer replace(int startIndex, int endIndex, String str)


Code Example:

import java.io.*;
class GFG {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("GeeksforGeeks");
s.replace(5, 8, "are");
System.out.println(s); // returns GeeksareGeeks
}
}
Output:
GeeksareGeeks
 ensureCapacity( ): It is used to increase the capacity of a StringBuffer object. The
new capacity will be set to either the value we specify or twice the current capacity
plus two (i.e. capacity+2), whichever is larger. Here, capacity specifies the size of
the buffer.
void ensureCapacity(int capacity)
Besides that all the methods that are used in String class can also be used.
 StringBuffer appendCodePoint(int codePoint): This method appends the string
representation of the codePoint argument to this sequence.
Syntax:
public StringBuffer appendCodePoint(int codePoint)
 char charAt(int index): This method returns the char value in this sequence at the
specified index.
Syntax:
 public char charAt(int index)
 IntStream chars(): This method returns a stream of int zero-extending the char
values from this sequence.
Syntax:
 public IntStream chars()
 int codePointAt(int index): This method returns the character (Unicode code
point) at the specified index.
Syntax:
 public int codePointAt(int index)
 int codePointBefore(int index): This method returns the character (Unicode code
point) before the specified index.
Syntax:
 public int codePointBefore(int index)
 int codePointCount(int beginIndex, int endIndex): This method returns the
number of Unicode code points in the specified text range of this sequence.
Syntax:
 public int codePointCount(int beginIndex,
 int endIndex)
 IntStream codePoints(): This method returns a stream of code point values from
this sequence.
Syntax:
 public IntStream codePoints()
 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): In this
method, the characters are copied from this sequence into the destination
character array dst.
Syntax:
 public void getChars(int srcBegin,
 int srcEnd,
 char[] dst,
 int dstBegin)
 int indexOf(String str): This method returns the index within this string of the first
occurrence of the specified substring.
Syntax:
 public int indexOf(String str)

 public int indexOf(String str,


 int fromIndex)
 int lastIndexOf(String str): This method returns the index within this string of the
last occurrence of the specified substring.
Syntax:
 public int lastIndexOf(String str)

 public int lastIndexOf(String str,


 int fromIndex)
 int offsetByCodePoints(int index, int codePointOffset): This method returns the
index within this sequence that is offset from the given index by codePointOffset
code points.
Syntax:

public int offsetByCodePoints(int index,


int codePointOffset)
 void setCharAt(int index, char ch): In this method, the character at the specified
index is set to ch.
Syntax:
 public void setCharAt(int index,
 char ch)
 void setLength(int newLength): This method sets the length of the character
sequence.
Syntax:
 public void setLength(int newLength)
 CharSequence subSequence(int start, int end): This method returns a new
character sequence that is a subsequence of this sequence.
Syntax:
 public CharSequence subSequence(int start,
 int end)
 String substring(int start): This method returns a new String that contains a
subsequence of characters currently contained in this character sequence.
Syntax:
 public String substring(int start)

 public String substring(int start,


 int end)
 String toString(): This method returns a string representing the data in this
sequence.
Syntax:
 public String toString()
 void trimToSize(): This method attempts to reduce storage used for the character
sequence.
Syntax:
 public void trimToSize()
Some Interesting facts:
1. java.lang.StringBuffer extends (or inherits from) Object class.
2. All Implemented Interfaces of StringBuffer class:Serializable, Appendable,
CharSequence.
3. public final class StringBuffer extends Object implements Serializable,
CharSequence, Appendable
4. String buffers are safe for use by multiple threads. The methods can be
synchronized wherever necessary so that all the operations on any particular
instance behave as if they occur in some serial order.
5. Whenever an operation occurs involving a source sequence (such as appending or
inserting from a source sequence) this class synchronizes only on the string buffer
performing the operation, not on the source.
6. It inherits some of the methods from Object class which are clone, equals, finalize,
getClass, hashCode, notify, notifyAll.

Java Wrapper Class


In Java, Wrapper Class is used for converting primitive data type into object and object
into a primitive data type. For each primitive data type, a pre-defined class is present
which is known as Wrapper class. From J2SE 5.0 version the feature of autoboxing and
unboxing is used for converting primitive data type into object and object into a primitive
data type automatically.

Why Use Wrapper Classes?


As we knew that in Java when input is given by the user, it is in the form of String. To
convert a string into different data types, Wrapper classes are used.
We can use wrapper class each time when want to convert primitive to object or vice
versa.
The following are the Primitive Data types with their Name of wrapper class and the
method used for the conversation.
Primitive DataType Wrapper ClassName Conversion methods

byte Byte public static byte parseByte(String)

short Short public static short parseShort(String)

int Integer public static int parseInt(String)

long Long public static long parseLong(String)

float Float public static float parseFloat(String)

double Double public static double parseDouble(String)

char Character

boolean Boolean public static boolean parseBoolean(String)

In Java, all the primitive wrapper classes are immutable. When a new object is created
the old object is not modified. Below is an example to demonstrate this concept.

Example:

class WrapperPrimitiveDemo1

public static void main(String[] args)


{

Integer a = new Integer(12);

System.out.println("Old value = "+a);

xyz(a);

System.out.println("New Value = "+a);

private static void xyz(Integer a)

a = a + 10;

Number Class
Java Number class is the super class of all the numeric wrapper classes. There are 6
sub classes, you can get the idea by following image.
The Number class contains some methods to provide the common operations for all the
sub classes.

Following are the methods of Number class


with there example
1. Value() Method
This method is used for converting numeric object into a primitive data type. For
example we can convert a Integer object to int or Double object to float type. The
value() method is available for each primitive type and syntax are given below.

Syntax:

byte byteValue()

short shortValue()

int intValue()

long longValue()

float floatValue()

double doubleValue()

Example:
Here we are using several methods like: byteValue(), intValue(),
floatValue() etc for convert object type to primitive type. The double type object is
used to fetch different types of primitive values.

public class NumberDemo1

public static void main(String[] args)

Double d1 = new Double("4.2365");

byte b = d1.byteValue();

short s = d1.shortValue();

int i = d1.intValue();

long l = d1.longValue();

float f = d1.floatValue();

double d = d1.doubleValue();
System.out.println("converting Double to byte : " + b);

System.out.println("converting Double to short : " + s);

System.out.println("converting Double to int : " + i);

System.out.println("converting Double to long : " + l);

System.out.println("converting Double to float : " + f);

System.out.println("converting Double to double : " + d1);

Java Integer class


Java Integer class is used to handle integer objects. It provides methods that can be
used for conversion primitive to object and vice versa.
It wraps a value of the primitive type int in an object. This class provides several
methods for converting an int to a String and a String to an int, as well as other
constants and methods helpful while working with an int.
It is located into java.lang pakage and java.base module. Declaration of this class is
given below.

Declaration
public final class Integer extends Number implements Comparable<Integer>

Methods of Integer class with examples are discussed below.

1. toString() Method
This method returns a String object representing this Integer's value. The value is
converted to signed decimal representation and returned as a string. It
overrides toString() method of Object class.
It does not take any argument but returns a string representation of the value of this
object in base 10. Syntax of this method is given below.

public String toString(int b)

Example:
In this example, we are using toString method to get string representation of Integer
object.

public class IntegerClassDemo1

public static void main(String args[])

int a = 95;

Integer x = new Integer(a);

System.out.println("toString(a) = " + Integer.toString(a));

}
valueOf()
The valueOf() method is used to get an Integer object representing the specified int
value. It takes a single int type argument and returns an Integer instance. Syntax of the
method is given below.

Syntax:

public static Integer valueOf(int b)

Exmaple:

public class IntegerClassDemo1

public static void main(String args[])

int a = 95;

Integer x = Integer.valueOf(a);

System.out.println("valueOf(a) = " + x);

}
parseInt()
The parseInt() method is used to parse the specified string argument as a signed
decimal integer. The characters in the string must all be decimal digits.
It takes a single argument of string type and returns an int value.

Syntax:

public static intparseInt(String val, int radix) throws NumberFormatException

Example:
In the following example, we are passing a string that contains digits
to parseInt() method. The method returns an int value corresponding to the string.

public class IntegerClassDemo1

public static void main(String args[])

String a = "95";

int x = Integer.parseInt(a);
System.out.println("parseInt(a) = " + x);

Java Long class


The Long class is a wrapper class that is used to wrap a value of the primitive type long
in an object. An object of type Long contains a single field whose type is long.
In addition, this class provides several methods for converting a long to a String and
vice versa. Declaration of the class is given below.

Declaration
public final class Long extends Number implements Comparable<Long>

This class is located into java.lang package and java.base module. Here we are
discussing methods of Long class with their examples.

toString()
This method returns a String object representing this Long's value. The value is
converted to signed decimal representation and returned as a string. It
overrides toString() method of Object class.
It does not take any argument but returns a string representation of the value of this
object in base 10. Syntax of this method is given below.

Syntax:
public String toString(long b)

Example:

public class LongDemo1

public static void main(String as[])

long a = 25;

System.out.println("toString(a) = " + Long.toString(a));

valueOf()
The valueOf() method is used to get an Long object representing the specified long
value. It takes a single long type argument and returns a Long instance. Syntax of the
method is given below.

Syntax:
public static Long valueOf(long b)

Example:

public class LongDemo1

public static void main(String as[])

long a = 25;

String b = "45";

Long x = Long.valueOf(a);

System.out.println("valueOf(a) = " + x);

x = Long.valueOf(b);

System.out.println("ValueOf(b) = " + x);

x = Long.valueOf(b, 6);

System.out.println("ValueOf(b,6) = " + x);

}
parseLong()
The parseLong() method is used to parse the specified string argument as a signed
decimal Long. The characters in the string must all be decimal digits.
It takes a single argument of string type and returns a Long value.

Syntax:

public static long parseInt(String val, int radix) throws


NumberFormatException

Example:
In the following example, we are passing a string that contains digits
to parseLong() method. The method returns a long value corresponding to the string.

public class LongDemo1

public static void main(String as[])

long a = 25;

String b = "45";

Long x = Long.parseLong(b);

System.out.println("parseLong(b) = " + x);

x = Long.parseLong(b, 6);

System.out.println("parseLong(b,6) = " + x);

You might also like