Array
Array is a data structure which is collection of
same type of values. We can access individual value using an integer index. The complete set of values is
called array and the individual value
in the array is called an element.
Declaration
of an array
Syntax
int[] marks;
float[] average;
int total[];
float num[];
The [] indicates an arry in array
declaration. To declare an array first we take data type like int, float char
etc followed by [] then name of variable as shown above. [] can be used either
with data type or variable name both are supported by java.
Creation of array
After declaration an array should be
created in the memory then only we can use it.
Syntax
int[] marks; // Declaration of array
marks = new int[3]; // Creation of array
Array is created in
memory using new statement. First
array should be declared then it should be created. For creation of array first
we should write the name of variable which is already declared then” =” symbol,
after that new and data type
followed by [] with number of elements of the array as shown in second line
above. Total number of elements in above example is 4 which is called size
of array, means we can store 4 values in the array.
Initialization of array
Putting values in array is called
initialization of the array.
Syntax
marks[0] = 32;
marks[1] = 48;
marks[2] = 16;
marks[3] = 19;
The size of array is 4, the address of
first element is marks[0] and value stored in this element is 32. Similarly the
address of second location of the array is marks[1] and value stored is 48 and
so on. The address of last (4th) element of the array is marks[3].
There is one more way to initialize the
array as shown below.
Syntax
int marks[] = {32,48,16,19};
This expression creates an array and
initializes it with the values given in curly braces. In this method of array
creation new is not used. It sets the size of array equal to the number
of values in braces.
Array Length
At the time of creation of an array size
of array is stored in a variable called length which can be accessed from the
name of the array variable.
Example
int marks[] = {32,48,16,19};
int arrayLength;
arrayLength = marks.length;
We can get length of
the array as shown above. The “ marks.length” expression
returns size of array or length of array. We can use “Arrays.sort(marks)” method to sort the array.
Example:
public class ArrayExample{
public static void main(String[] args)
{
int marks[] = {32,48,16,19};
int arrayLength;
arrayLength = marks.length;
System.out.println("Given list is: ");
for(int i =0; i < arrayLength; i++)
{
System.out.println(marks[i]);
}
Arrays.sort(marks);
System.out.println("Sorted array : ");
for(int i =0; i < arrayLength; i++)
{
System.out.println(marks[i]);
}
}
}
The output of this example is:
Given list is:
32
48
16
19
Sorted array :
16
19
32
48
Similar to “Arrays.sort(marks)” and marks.length there are some
other methods also provided by java.
Multi
Dimensional Array
Tow dimensional arrays are used
when table of values is to be stored. For example we can make a table of marks
obtained by students in different subjects as given below:
Table
Name: Marks Table
|
|
Subject 1
|
Subject 2
|
Subject 3
|
Subject 4
|
|
Student 1
|
56
|
92
|
85
|
45
|
|
Student 2
|
76
|
46
|
88
|
65
|
|
Student 3
|
68
|
443
|
76
|
87
|
This table is consists of three
rows and four columns. Students represented in row and subjects represented in
columns. When we need a data structure to store data of table form we use two dimensional
arrays. In single dimensional array each dimension of array is indexed from 0
to maximum size minus one like marks[0]….marks[5]. Similarly in two dimensional
arrays we use the row number and column number to represent index of array.
marks[row number][column number]
It is necessary to write row
number in first braces [], and column in second braces [] after variable
name.
Here in this example first row is
Student 1, second row is Student 2, and third row is Student 3. Similarly first
column is Subject 1, Second column is Subject 2, third column is Subject 3 and
forth column is Subject 4.
To save values of above table in
an array we will need to use tow dimensional array.
Creation of two dimensional
array:
int marks[][];
marks = new int[3][4]; // Three rows and four columns.
Or
int marks[][] = new int[3][4];
Like one dimensional array we can
also initialize two dimensional array at the time of declaration.
int marks[][] = {0,0,0,0,1,1,1,1,2,2,2,2};
The initialization is done row by
row, in this example all 0s represents value of all the columns of first row
from column 1 to 4 serially, and similarly value 1 is for row 1 and so on. We
can also initialize tha array as:
int marks[][] = {{0,0,0,0},{1,1,1,1},{2,2,2,2}};
OR
int marks[][] = {{0,0,0,0},
{1,1,1,1},
{2,2,2,2}};
We can save the value in array
direct at some location using row number and column number.
Like:
marks[2][3] =
88; // second row third column.
marks[3][3]
= 76; //third row third column.
Example
public class FirstJavaProgram {
public static void main(String[] args)
{
int marks[][] ={{56,92,85,45},
{76,46,88,65},
{68,43,76,87},
};
int i,j=0;
for(i =0; i<=2; i++)
{
for(j= 0; j<=3; j++ )
{
System.out.println("Row: "+ i + ",Column: " + j + " = " + marks[i][j]);
}
}
}
}
The result of this
program is:
Row: 0,Column: 0 = 56
Row: 0,Column: 1 = 92
Row: 0,Column: 2 = 85
Row: 0,Column: 3 = 45
Row: 1,Column: 0 = 76
Row: 1,Column: 1 = 46
Row: 1,Column: 2 = 88
Row: 1,Column: 3 = 65
Row: 2,Column: 0 = 68
Row: 2,Column: 1 = 43
Row: 2,Column: 2 = 76
Row: 2,Column: 3 = 87
Strings
Java strings are sequence of
characters. String in java is a predefined class in java library. Java provides
two string classes String and StringBuffer.
We can define an initialize a
string as:
String e = ""; // Empty
string
String firstName = "Amitabh"; // String with value
String lastName = "Bacchan";
OR
String cityName;
cityName = new String("Mumbai");
OR
String stateName = new String("Maharastra");
String
Array
We can use strings in arrays
also. We can define array of strings such as:
String cityArray[] = new String[3];
cityArray[0] = "New Delhi";
cityArray[1] = "Mumbai";
cityArray[2] = "Jaipur";
Concatenation
Java string can be concatenated
using + sign.
String fullName = firstName + lastName;
String capitalOfIndia = "New " + "Delhi";
String Methods
Sub
String: We can copy a part of string into another string.
String subStr = firstName.substring(0, 4);
This statement will copy first 4
characters of firstName string starting from 0th to 3rd character in subStr.
Length
of String: We can get length of string using Length method of
string class
int lengthOfString =
firstName.length();
String Comparison: Equals
method of String class allows us to compare two strings. This expression
returns true if strings are same otherwise false.
boolean stringComp1 =
firstName.equals(lastName);
boolean stringComp2 =
firstName.equals("Amit");
Example:
public class FirstJavaProgram {
public static void main(String[] args)
{
String cityArray[] = new String[3];
cityArray[0] = "New Delhi";
cityArray[1] = "Mumbai";
cityArray[2] = "Jaipur";
for(int i =0; i< cityArray.length; i++)
{
System.out.println(cityArray[i]);
}
String e = "";
String firstName = "Amitabh";
String lastName = "Bacchan";
String address = new String("Jalsha, Juhu");
String cityName;
cityName = new String("Mumbai");
System.out.println("First Name: " + firstName);
System.out.println("First Name: " + lastName);
String fullName = firstName + lastName; // Concatenation of strings
System.out.println("Full Name after concatenation: " + fullName);
System.out.println("Address: " + address);
System.out.println("Address: " + cityName);
String capitalOfIndia = "New " + "Delhi"; // Concatenation of strings
System.out.println("Capital of India: " +
capitalOfIndia);
String subStr =
firstName.substring(0, 4); // copy first 4 characters
System.out.println("Sub string " + subStr);
int lengthOfString = firstName.length();
System.out.println("Length of String " +
lengthOfString);
boolean stringComp = firstName.equals("Amit");
System.out.println("String Comparision: " +
stringComp);
}
}
The output of the
program is:
String arra
example:
New Delhi
Mumbai
Jaipur
First Name: Amitabh
First Name: Bacchan
Full Name after concatenation:
AmitabhBacchan
Address: Jalsha, Juhu
Address: Mumbai
Capital of India: New Delhi
Sub string: Amit
Length of String: 7
String Comparision: false
StringBuffer
StringBuffer is another class which supports
strings. String creates string of
fixed length whereas StringBuffer
creates string of flexible length. The length of StringBuffer can be changed as
per the length of the content we want to save in StringBuffer. We can define
and initialize string using StringBuffer as:
StringBuffer
capitalofIndia = new StringBuffer("New Delhi capital
of India");
StringBuffer mainly support following methods:
charAt: Returns the
character at specified position. Example:
System.out.println("Character at position 4: " + capitalofIndia.charAt(4));
This statement returns the
character at position 4 in the string. First position starts from 0 and then
1,2,3 etc. In above string at position 4 character is “D”.
setCharAt:
Set
the character at specified position. Example:
capitalofIndia.setCharAt(3, '-');
System.out.println("String after adding - at
position 3: " + capitalofIndia);
The above statement adds
character “-“ at position 3 in the string and result will be “New-Delhi”.
indexOf:
This
method returns the position of first character of the given substring. For
example we want to check the position of substring “capital” in main string.
int pos = capitalofIndia.indexOf("capital");
System.out.println("Position of substring
capital in the string: " + pos);
The position of substring capital in the string is
10.
length: It returns length of the string. Example:
System.out.println("Length of the string: " + capitalofIndia.length());
The length of string stored in “capitalofIndia”
is 26.
insert: We can insert a substring
with in an existing string like character we have seen above. Example:
capitalofIndia.insert(10, "is
");
System.out.println("After
inserting is in the string: "
+ capitalofIndia);
A string “is” is inserted at position 10 in the original
string.
append:
We can append a new string at the end of existing string. Example
capitalofIndia.append("and
Mumbai is financial capital of India");
System.out.println("After
Append: " + capitalofIndia);
Example:
public class FirstJavaProgram {
public static void main(String[] args)
{
StringBuffer capitalofIndia = new StringBuffer("New Delhi capital of India");
System.out.println("Original String:
" + capitalofIndia);
// Display the character at position 5 in the string
System.out.println("Character at position 4:
" + capitalofIndia.charAt(4));
capitalofIndia.setCharAt(3,
'-');
System.out.println("String after adding - at position 3: " + capitalofIndia);
int pos = capitalofIndia.indexOf("capital");
System.out.println("Position of substring capital in the string: " + pos);
System.out.println("Length of the string: " +
capitalofIndia.length());
capitalofIndia.insert(10, "is ");
System.out.println("After inserting is in the string: " + capitalofIndia);
capitalofIndia.append(" and Mumbai is financial capital of India");
System.out.println("After Append: " +
capitalofIndia);
}
}
The output of this program is:
Original
String: New Delhi capital of India
Character
at position 4: D
String
after adding - at position 3: New-Delhi capital of India
Position
of substring capital in the string: 10
Length
of the string: 26
After
inserting is in the string: New-Delhi is capital of India
After
Append: New-Delhi is capital of India and Mumbai is financial capital of India
No comments:
Post a Comment