Professional Documents
Culture Documents
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.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored
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.
2. dataType arr[];
1. arrayRefVar=new datatype[size];
Test it Now
Output:
10
20
70
40
50
Test it Now
Output:
33
3
4
5
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.
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.
Output:
33
3
4
5
Example
The following code displays all the elements in the array myList −
Output
1.9
2.9
3.4
3.5
Let's see the simple example to get the minimum number of an array using a method.
Test it Now
Output:
Test it Now
Output:
10
22
44
66
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);
}
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.
Test it Now
Output:
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;
Test it Now
Output:
1 2 3
2 4 5
4 4 5
Test it Now
Output:
2 6 8
6 8 10
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
Output:
6 6 6
12 12 12
18 18 18
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.
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:
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.
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.
Output:
3 3 3
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.
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 {
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
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
Output
Dot saw I was Tod
Example
String Methods
Here is the list of methods supported by String class −
2 int compareTo(Object o)
Returns true if and only if this String represents the same sequence of
characters as the specified StringBuffer.
7 static String copyValueOf(char[] data)
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.
Encodes this String into a sequence of bytes using the named charset,
storing the result into a new byte array.
Copies characters from this string into the destination character array.
15 int hashCode()
Returns the index within this string of the first occurrence of the specified
character.
Returns the index within this string of the first occurrence of the specified
character, starting the search at the specified index.
Returns the index within this string of the first occurrence of the specified
substring.
Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index.
20 String intern()
Returns the index within this string of the last occurrence of the specified
character.
Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified index.
Returns the index within this string of the rightmost occurrence of the
specified substring.
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.
Tells whether or not this string matches the given regular expression.
Replaces each substring of this string that matches the given regular
expression with the given replacement.
Replaces the first substring of this string that matches the given regular
expression with the given replacement.
39 char[] toCharArray()
40 String toLowerCase()
Converts all of the characters in this String to lower case using the rules
of the default locale.
Converts all of the characters in this String to lower case using the rules
of the given Locale.
42 String toString()
43 String toUpperCase()
Converts all of the characters in this String to upper case using the rules
of the default locale.
45 String trim()
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.
Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as lengt
public insert(int offset, is used to insert the specified string with this
synchronized String s)
string at the specified position. The insert()
StringBuffer
public replace(int is used to replace the string from specified startIndex and
synchronized startIndex, int
endIndex.
StringBuffer endIndex, String
str)
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)
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. }
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. }
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. }
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. }
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. }
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( 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
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:
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)
char Character
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
xyz(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.
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.
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);
Declaration
public final class Integer extends Number implements Comparable<Integer>
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.
Example:
In this example, we are using toString method to get string representation of Integer
object.
int a = 95;
}
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:
Exmaple:
int a = 95;
Integer x = Integer.valueOf(a);
}
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:
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.
String a = "95";
int x = Integer.parseInt(a);
System.out.println("parseInt(a) = " + x);
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:
long a = 25;
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:
long a = 25;
String b = "45";
Long x = Long.valueOf(a);
x = Long.valueOf(b);
x = Long.valueOf(b, 6);
}
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:
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.
long a = 25;
String b = "45";
Long x = Long.parseLong(b);
x = Long.parseLong(b, 6);