Unit - Ii
Unit - Ii
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]);
}
}}
class Test1 {
// A method that takes variable
// number of integer arguments.
static void fun(int... a)
{
System.out.println("Number of arguments: "
+ a.length);
// 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);
System.out.println();
}
1. By string literal
2. By new keyword
7
1) String Literal
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.:
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");
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());
// 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 ...
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
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.
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
Method Description
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.
substring(int beginIndex, int endIndex) It is used to return the substring from the specified
beginIndex and endIndex.
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.
3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
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.
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:
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.
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.
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
//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);
//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