Arrays: An array
represents a group of elements of same data type. Arrays are generally
categorized into two types:
· Single
Dimensional arrays (or 1 Dimensional arrays)
· Multi-Dimensional
arrays (or 2 Dimensional arrays, 3 Dimensional arrays, …)
Single Dimensional Arrays: A one dimensional array or single
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.
· We can declare a one dimensional array
and directly store elements at the time of its declaration, as: int marks[] = {50, 60, 55, 67, 70};
· We can create a 1D array by declaring the
array first and then allocate memory for it by using new operator, as: int
marks[]; //declare marks array marks =
new int[5]; //allot memory for storing 5 elements These two statements also can
be written as: int marks [] = new int
[5];
Program 1: Write a program to accept elements into an array and
display the same. // program to accept elements into an array and display the
same.
import java.io.*; class
ArrayDemo1
{ public
static void main (String args[]) throws IOException
{ //Create
a BufferedReader class object (br)
BufferedReader br =
new BufferedReader (new InputStreamReader (System.in));
System.out.println
(“How many elements: “ );
int n = Integer.parseInt
(br.readLine ());
//create a 1D array with size n
int
a[] = new int[n];
System.out.print
("Enter elements into array : ");
for (int i = 0; i<n;i++)
a
[i] = Integer.parseInt ( br.readLine ());
System.out.print (“The entered
elements in the array are: “);
for
(int i =0; i < n; i++) System.out.print
(a[i] + “\t”);
}
· Two Dimensional Arrays (2d array): A two dimensional array represents several
rows and columns of data. To represent a two dimensional array, we should use
two pairs of square braces [ ] [ ] after the array name. For example, the marks
obtained by a group of students in five different subjects can be represented
by a 2D array.
o
We can declare a two dimensional array and
directly store elements at the time of its declaration, as:
int
marks[] [] = {{50, 60, 55, 67, 70},{62, 65, 70, 70, 81}, {72, 66, 77, 80, 69} };
o
We can create a two dimensional array by
declaring the array first and then we can allot memory for it by using new
operator as: int marks[ ] [ ];
//declare marks array marks = new int[3][5]; //allot memory for storing
15 elements.
These two statements also can be
written as: int marks [ ][ ] = new int[3][5];
Program 2: Write
a program to take a 2D array and display its elements in the form of a matrix.
//Displaying a 2D array as a
matrix class Matrix
{ public
static void main(String args[])
{ //take
a 2D array
int
x[ ][ ] = {{1, 2, 3}, {4, 5, 6} }; // display the array elements for
(int i = 0 ; i < 2 ; i++) { System.out.println
(); for
(int j = 0 ; j < 3 ; j++) System.out.print(x[i][j]
+ “\t”);
}
}
}
· Three Dimensional arrays (3D arrays):
We can consider a three dimensional array as a combination of several two
dimensional arrays. To represent a three
dimensional array, we should use three pairs of square braces [ ] [ ] after the
array name.
o
We can declare a three dimensional array and directly
store elements at the time of its declaration, as:
int arr[
] [ ] [ ] = {{{50, 51, 52},{60, 61, 62}}, {{70, 71, 72}, {80, 81, 82}}};
o
We can create a three dimensional array by
declaring the array first and then we can allot memory for it by using new
operator as:
int arr[ ] [ ] = new
int[2][2][3]; //allot memory for storing 15 elements.
arrayname.length: If we want to know
the size of any array, we can use the property ‘length’ of an array. In case of
2D, 3D length property gives the number of rows of the array.
Strings: A String represents group of characters. Strings are
represented as String objects in java.
Creating Strings:
· We
can declare a String variable and directly store a String literal using
assignment operator.
String
str = "Hello";
· We
can create String object using new operator with some data. String s1 = new
String ("Java");
· We
can create a String by using character array also. char arr[] = { 'p','r','o',’g’,’r’,’a’,’m’}; · We can create a String by passing array
name to it, as:
String s2 = new String (arr);
· We
can create a String by passing array name and specifying which characters we
need:
String
s3 = new String (str, 2, 3);
Here starting
from 2nd character a total of 3 characters are copied into String
s3.
Method
|
Description
|
String concat (String str)
|
Concatenates calling String with str. Note:
+ also used to do the same
|
int length ()
|
Returns length of a String
|
char charAt (int index)
|
Returns the character at
specified location ( from 0 )
|
int compareTo
(String str)
|
Returns a negative value if calling String is less than
str, a positive value if calling String is greater than str or 0 if Strings
are equal.
|
boolean equals
(String str)
|
Returns true if calling
String equals str.
Note: == operator
compares the references of the string objects. It does not compare the
contents of the objects. equals () method compares the contents. While comparing the strings, equals ()
method should be used as it yields the correct result.
|
boolean
equalsIgnoreCase
(String str)
|
Same as above but ignores
the case
|
boolean startsWith
( String prefix )
|
Returns true if calling
String starts with prefix
|
boolean endsWith
(String suffix)
|
Returns true if calling
String ends with suffix
|
int indexOf (String str)
|
Returns first occurrence of
str in String.
|
int lastIndexOf(String str)
|
Returns last occurrence
of str in the String.
Note: Both the above
methods return negative value, if str not
|
found in calling
String. Counting starts from 0.
|
|
String replace (char
oldchar, char newchar)
|
returns a new String that is obtained by replacing all
characters oldchar in String with newchar.
|
String substring
(int beginIndex)
|
returns a new String consisting of all characters from
beginIndex until the end of the String
|
String substring (int beginIndex, int endIndex)
|
returns a new String consisting of all characters from
beginIndex until the endIndex.
|
String toLowerCase ()
|
converts all characters
into lowercase
|
String toUpperCase ()
|
converts all characters
into uppercase
|
String trim ()
|
eliminates all leading and trailing spaces
|
Program 3: Write
a program using some important methods of String class.
// program using String class methods class
StrOps
{ public static void main(String args
[])
{ String str1 = "When it comes to Web
programming, Java is #1.";
String str2 = new String
(str1);
String str3 = "Java strings are
powerful."; int result, idx; char
ch;
System.out.println ("Length of str1: " +
str1.length ()); // display str1, one
char at a time.
for(int i=0; i <
str1.length(); i++)
System.out.print
(str1.charAt (i));
System.out.println ();
if (str1.equals (str2) )
System.out.println
("str1 equals str2");
else
System.out.println
("str1 does not equal str2");
if (str1.equals (str3) )
System.out.println ("str1 equals
str3"); else
System.out.println
("str1 does not equal str3");
result = str1.compareTo (str3);
if(result
== 0)
System.out.println
("str1 and str3 are equal");
else
if(result < 0)
System.out.println
("str1 is less than str3");
else
System.out.println
("str1 is greater than str3");
str2 = "One Two
Three One"; // assign a new string to str2 idx = str2.indexOf ("One");
System.out.println
("Index of first occurrence of One: " + idx);
idx = str2.lastIndexOf("One");
System.out.println
("Index of last occurrence of One: " + idx);
}
}
We can divide objects broadly as
mutable and immutable objects. Mutable objects are those objects whose contents
can be modified. Immutable objects are those objects, once created can not be
modified. String objects are immutable.
The methods that directly manipulate data of the object are not available in
String class.
Creating StringBuffer:
· We
can create a StringBuffer object by using new operator and pass the string to
the object, as: StringBuffer sb = new
StringBuffer ("Kiran");
· We can create a StringBuffer object by
first allotting memory to the StringBuffer object using new operator and later
storing the String into it as:
StringBuffer sb = new
StringBuffer (30);
In general a StringBuffer object
will be created with a default capacity of 16 characters. Here, StringBuffer
object is created as an empty object with a capacity for storing 30 characters.
Even if we declare the capacity as 30, it is possible to store more than 30
characters into StringBuffer.
To store characters, we can use append () method as:
Sb.append (“Kiran”);
StringBuffer Class Methods:
Method
|
Description
|
StringBuffer append (x)
|
x may be int, float, double, char, String or StringBuffer.
It will be appended to calling StringBuffer
|
StringBuffer insert (int
offset, x)
|
x may be int, float, double, char, String or
StringBuffer. It will be inserted into
the StringBuffer at offset.
|
StringBuffer delete (int
start, int end)
|
Removes characters from
start to end
|
StringBuffer reverse ()
|
Reverses character sequence
in the StringBuffer
|
String toString ()
|
Converts StringBuffer into
a String
|
int length ()
|
Returns length of the
StringBuffer
|
Program 4: Write
a program using some important methods of StringBuffer class.
// program using StringBuffer class methods
import java.io.*; class
Mutable
{ public
static void main(String[] args) throws IOException
{ //
to accept data from keyboard
BufferedReader br=new BufferedReader
(new InputStreamReader (System.in));
System.out.print
("Enter sur name : ");
String
sur=br.readLine ( );
System.out.print
("Enter mid name : ");
String
mid=br.readLine ( );
System.out.print
("Enter last name : ");
String
last=br.readLine ( );
//
create String Buffer object
StringBuffer sb=new StringBuffer ( );
//
append sur, last to sb sb.append
(sur); sb.append
(last);
//
insert mid after sur int n=sur.length ( ); sb.insert
(n, mid); // display full name
System.out.println
("Full name = "+sb);
System.out.println
("In reverse ="+sb.reverse ( ));
}
}