 An array is a collection of variables of the
same type , referred by a common name.
 Advantage of an array is that it organizes
data in such a way that it can be easily
manipulated.
 If data is stored in array, it can be easily
sorted.
 In java, arrays are implemented as objects.
 A one-dimensional array is list of related
objects
 type array_name[]=new type[size];
 Type declares the element type of the array
 Size determines the number of elements in
the array created.
 Two steps, declaration and allocation of
memory for array
 First declare any array reference variable
 Second, allocate memory for the array using
“new” operator.
 Ex: int sample[]=new int[10];
 Can be split into two statements as
int sample[];
sample=new int[10];
 In this , first statement , when sample array is
created , no physical object is referred
 Second statement , executes that sample is
linked with an array.
class ArrayDemo{
public static void main(String args[]){
int sample[]=new int[10];
int i;
for(i=0;i<10;i++)
sample[i]=i;
for(i=0;i<10;i++)
System.out.print("Sample["+i+"]:"+sample[i]+"n"
);
}
}
class MinMax{
public static void main(String args[]){
int nums[]=new int[10];
int min,max;
nums[0]=99;
nums[1]=-10;
nums[2]=100123;
nums[3]=18;
nums[4]=-978;
nums[5]=5623;
nums[6]=463;
nums[7]=-9;
nums[8]=287;
nums[9]=49;
min=max=nums[0];
for(int i=0;i<10;i++) {
if(nums[i]<min)
min=nums[i];
if(nums[i]>max)
max=nums[i]; }
System.out.print("Minimum="+min+"nMaximum:"+max);
} }
 Rather than having 10 different assignment
statements, there is an easier way to do this
in a single assignment step
 type array_name[]={val1,val2,val3 … val N};
 Rather than giving a value for size directly the
values can be given for the array in a single
step.
 They are assigned in the index order from left
to right side.
 No need to use new operator in this case
class MinMax2{
public static void main(String args[]){
int nums[]={ 99,-10,100123,18,-978,5623,463,-
9,287,49};
int min,max;
min=max=nums[0];
for(int i=0;i<10;i++)
{
if(nums[i]<min)
min=nums[i];
if(nums[i]>max)
max=nums[i];
}
System.out.print("Minimum="+min+"nMaximum:"+max);
}
}
 Array boundaries are strictly enforced in Java
 Gives run time error in case of end of an array or
over run or under run of an array
class ArrayErr{
public static void main(String args[]){
int sample[]=new int[10];
int i;
for(i=0;i<100;i++)
sample[i]=i;
}
}
 Arrays of two or more dimensions, in java
language multidimensional arrays means
arrays of arrays.
 Two dimensional arrays
 Irregular arrays
 Arrays of three or more dimensions
 To declare a two dimensional array of size
10, 20 you would write,
 int table[][]=new int[10][20];
 Other languages use of comma is done for
array dimensions, here square brackets are
used.
class TwoD{
public static void main(String args[]){
int table[][]=new int[3][4];
int i,t;
for(t=0;t<3;t++)
{
for(i=0;i<4;i++){
table[t][i]=t+i;
System.out.print(table[t][i]+" ");
}
System.out.println();
}
}
}
 In case of multidimensional array, we should
mention the memory of the left first
 You can give the rightmost dimension separately
 Used in the situation where a very large two
dimensional array is required which is sparsely
populated (on in which not all the elements will
be used)
 int table[ ][ ]=new int[3][ ];
 table[0]=new int[4];
 table[1]=new int[3];
 table[2]=new int[2];
 General form of three or more dimensional array
 type name[][]…[ ]= new
type[size1][size2]…[sizeN];
 int multidimen[ ][ ][ ]=new int [3][10][5];
 A multidimensional array can be initialized by
enclosing each dimension initializer list
within its own set of curly braces.
type array_name[ ][ ]={
{val,val,val…val},
{val,val,val…val},
.
.
{val,val,val…val},
};
class squares{
public static void main(String args[]){
int square[][]={{1,1},{2,4},{3,9},{4,16},{5,25}};
int i,j;
for(i=0;i<5;i++){
for(j=0;j<2;j++)
System.out.print(square[i][j]+" ");
System.out.println();
}
}
}
 type[ ] var_name;
 Eg : int counter[]=new int[3];
 int [] counter=new int[3];
 Both the above statements are same
 This approach is helpful when you want to
create multiple arrays of the same type
 int num0[],num1[],num2[];
 Better approach is
 int [ ] num0,num1,num2;
 When you assign one array reference variable
to another, you are simply changing what
object that variable refers to.
 You are not causing a copy of the array to be
made nor you are causing the contents of one
of array to be copied to another.
class AssignAref
{
public static void main(String args[]){
int i;
int nums1[]=new int[10];
int nums2[]=new int[10];
for(i=0;i<10;i++)
nums1[i]= i;
for(i=0;i<10;i++)
nums2[i]= -i;
System.out.print("num1:");
for(i=0;i<10;i++)
System.out.print(nums1[i]+" " );
System.out.println();
System.out.print("num2:");
for(i=0;i<10;i++)
System.out.print(nums2[i]+" " );
System.out.println();
//make num2 refer to num1
nums2=nums1;
System.out.print("here is nums2
after assignment:");
for(i=0;i<10;i++)
System.out.print(nums2[i]+"
" );
System.out.println();
//operate on nums1 array through
nums2
nums2[3]=99;
System.out.print("here is nums1
after change through nums2");
for(i=0;i<10;i++)
System.out.print(nums1[i]+"
" );
System.out.println();
}
}
 Arrays are implemented as objects, each
array is associated with a length instance
variable that contains the number of elements
that array can hold.
 Length contains size of the array
class lengthDemo{
public static void main(String
args[]){
int list[]=new int[10];
int nums[]={1,2,3};
int
table[][]={{1,2,3},{4,5},{6,7,8
,9}};
System.out.println("length
of the list is "+list.length);
System.out.println("length
if nums "+nums.length);
System.out.println("length
of table is: "+table.length);
for(int
i=0;i<table.length;i++)
System.out.println("lengh
of table["+i+"] is
"+table[i].length);
System.out.println();
for(int
j=0;j<list.length;j++)
list[j]=j*j;
for(int
k=0;k<list.length;k++)
System.out.print(list[
k]+" ");
System.out.println();
}
}
 A for-each loop cycles through a collection of
objects such as array in strictly sequential
fashion from start to finish.
 It is released in JDK 5, for-each is also referred as
enhanced for loop
 Syntax:
for(type itr_variable: collection)
statement block;
 type specifies the data type of the iteration
variable i.e itr_variable
 That will receive elements from collections one at
a time from beginning to the end of the
collection
 Itr_variable recieves the data from collection,
hence type of the collection and itr_variable
should be same always
class EnhancedForLoop {
public static void main(String[] args) {
int primes[] = { 2, 3, 5, 7, 11, 13, 17};
for (int t: primes) {
System.out.println(t);
}
}
}
 If we want to terminate the for-each loop before
completion of all the loops, one can use “break”
statement.
class EnhancedForLoop {
public static void main(String[] args) {
int primes[] = { 2, 3, 5, 7, 11, 13, 17};
for (int t: primes) {
System.out.println(t);
if(t==5)break;
}
}
}
 Itr_variable is only for read only purpose.
 An assignement to the iteration variable has no
effect on underlying array.
class EnhancedForLoop {
public static void main(String[] args) {
int primes[] = { 2, 3, 5, 7, 11, 13, 17};
for (int t: primes) {
System.out.print(t+" ");
t=t*2;
}
System.out.println();
for (int t: primes) {
System.out.print(t+" ");
}
}
}
 Enhanced for loop works for
multidimensional arrays.
 Multidimensional array is arrays of array.
 Two dimensional array is an array of one
dimensional array.
 In each iteration, it obtains next array not an
individual element
class Foreach2{
public static void main(String args[])
{
int sum=0;
int nums[][]=new int[3][5];
for(int i=0;i<nums.length;i++)
for(int j=0;j<nums[i].length;j++)
nums[i][j]=(i+1)*(j+1);
System.out.println("Value is :");
for(int x[]:nums){
for(int y:x){
System.out.print(y+" ");
sum+=y;
}
System.out.println();
}
System.out.println("Summation :"+sum);
}
}
 Used for searching of the data in the given
set of numbers.
 Can be used for searching in unsorted array
 It stops when the key is found.
class search{
public static void main(String args[])
{
int nums[]={6,8,3,7,5,6,1,4};
int key=5;
boolean found=true;
for(int x:nums)
if(x==key){
found=true;
break;
}
if(found)
System.out.print("Value found!!");
}
}
 String defines and supports character strings
 In other languages string is an array of
characters
 Here strings are objects.
 By using new and calling String constructor.
 String str=new String(“hello” );
 String object called str will contain a string
called “hello”
Method Meaning
boolean equals(str) Returns true if the involving string
contains the same character
sequence as str
int length() Obtains the length of the str
char chatAt(index) Obtains character at index
mentioned
int compareTo(str) Returns less than zero if the
invoking string is less than str,
gretaer than zero if invking string
is greater than str and zero if they
are equal
int indexOf(str) Searches invoking string for
substring specified by str. Returns
the index of the first match or -1
on failure
int lastIndexOf(str) Searches invoking string for
substring specified by str. Returns
the index of the last match or -1
on failure
class StrOps{
public static void main(String args[]){
String str1="when it come to web
programming, Java is #1.";
String str2=new String(str1);
String str3="Java strings are powerfull";
int result,idx;
char ch;
System.out.println("length of
str1:"+str1.length());
//display one charecter 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("String 1 and 2 are
equal");
else
System.out.println("String 1 and 2 are
not equal");
if(str1.equals(str3))
System.out.println("String 1 and 3 are
equal");
else
System.out.println("String 1 and 3 are not
equal");
result=str1.compareTo(str3);
if(result==0)
System.out.println("String 1 and 3
are not equal");
else if(result<0)
System.out.println("String 1 is
less than string 3");
else
System.out.println("String 1 is
greater than string 3");
str2="one two three one";
idx=str2.indexOf("one");
System.out.println("Index of first
occurance of one :"+idx);
idx=str2.lastIndexOf("one");
System.out.println("Index of last
occurance of one :"+idx);
}
}
 Can be easily performed by using + between
strings.
String str=“java”;
String sr1=“programming”;
String finalstring=str+str1;
class StringArrays{
public static void main(String args[]){
String strs[]={"this", "is", "a","test"};
System.out.println("original array");
for(String s:strs)
System.out.print(s+" ");
System.out.println();
//change in a string
strs[1]="was";
strs[3]="test,tool";
System.out.println("After modification");
for(String s:strs)
System.out.print(s+" ");
}
}
 Once created, the character sequence that makes
up the string cannot be altered.
 When a change is required , you just have to create
a new string, the unused strings are automatically
garbage collected.
 substring()- method returns a new string that
contains a specified portion of the invoking string.
class Substr{
public static void main(String args[])
{
String orgstring="java programming is the
best!";
String substring=orgstring.substring(5,12);
System.out.println("original
string:"+orgstring+"nSubstring is
:"+substring);
}
}
class Stringswitch{
public static void main(String args[])
{
String choice="cancel";
switch(choice){
case "connect": System.out.println("Connecting!");
break;
case "cancel":System.out.println("cancelling!");
break;
default: System.out.println("Enter correct string");
break;
}
}
}
 A command line argument is the information
that directly follows the program’s name on
the command line when it is executed.
 They are stored in String array passed in the
main()
class CLDemo
{
public static void main(String args[])
{
System.out.println("These are:"+args.length+"
command line arguements");
System.out.println("they are:");
for(int i=0;i<args.length;i++)
System.out.println("args["+i+"]:"+args[i]);
}
}

Chap1 array

  • 2.
     An arrayis a collection of variables of the same type , referred by a common name.  Advantage of an array is that it organizes data in such a way that it can be easily manipulated.  If data is stored in array, it can be easily sorted.  In java, arrays are implemented as objects.
  • 3.
     A one-dimensionalarray is list of related objects  type array_name[]=new type[size];  Type declares the element type of the array  Size determines the number of elements in the array created.  Two steps, declaration and allocation of memory for array  First declare any array reference variable  Second, allocate memory for the array using “new” operator.
  • 4.
     Ex: intsample[]=new int[10];  Can be split into two statements as int sample[]; sample=new int[10];  In this , first statement , when sample array is created , no physical object is referred  Second statement , executes that sample is linked with an array.
  • 5.
    class ArrayDemo{ public staticvoid main(String args[]){ int sample[]=new int[10]; int i; for(i=0;i<10;i++) sample[i]=i; for(i=0;i<10;i++) System.out.print("Sample["+i+"]:"+sample[i]+"n" ); } }
  • 6.
    class MinMax{ public staticvoid main(String args[]){ int nums[]=new int[10]; int min,max; nums[0]=99; nums[1]=-10; nums[2]=100123; nums[3]=18; nums[4]=-978; nums[5]=5623; nums[6]=463; nums[7]=-9; nums[8]=287; nums[9]=49; min=max=nums[0]; for(int i=0;i<10;i++) { if(nums[i]<min) min=nums[i]; if(nums[i]>max) max=nums[i]; } System.out.print("Minimum="+min+"nMaximum:"+max); } }
  • 7.
     Rather thanhaving 10 different assignment statements, there is an easier way to do this in a single assignment step  type array_name[]={val1,val2,val3 … val N};  Rather than giving a value for size directly the values can be given for the array in a single step.  They are assigned in the index order from left to right side.  No need to use new operator in this case
  • 8.
    class MinMax2{ public staticvoid main(String args[]){ int nums[]={ 99,-10,100123,18,-978,5623,463,- 9,287,49}; int min,max; min=max=nums[0]; for(int i=0;i<10;i++) { if(nums[i]<min) min=nums[i]; if(nums[i]>max) max=nums[i]; } System.out.print("Minimum="+min+"nMaximum:"+max); } }
  • 9.
     Array boundariesare strictly enforced in Java  Gives run time error in case of end of an array or over run or under run of an array class ArrayErr{ public static void main(String args[]){ int sample[]=new int[10]; int i; for(i=0;i<100;i++) sample[i]=i; } }
  • 10.
     Arrays oftwo or more dimensions, in java language multidimensional arrays means arrays of arrays.  Two dimensional arrays  Irregular arrays  Arrays of three or more dimensions
  • 11.
     To declarea two dimensional array of size 10, 20 you would write,  int table[][]=new int[10][20];  Other languages use of comma is done for array dimensions, here square brackets are used.
  • 12.
    class TwoD{ public staticvoid main(String args[]){ int table[][]=new int[3][4]; int i,t; for(t=0;t<3;t++) { for(i=0;i<4;i++){ table[t][i]=t+i; System.out.print(table[t][i]+" "); } System.out.println(); } } }
  • 13.
     In caseof multidimensional array, we should mention the memory of the left first  You can give the rightmost dimension separately  Used in the situation where a very large two dimensional array is required which is sparsely populated (on in which not all the elements will be used)  int table[ ][ ]=new int[3][ ];  table[0]=new int[4];  table[1]=new int[3];  table[2]=new int[2];
  • 14.
     General formof three or more dimensional array  type name[][]…[ ]= new type[size1][size2]…[sizeN];  int multidimen[ ][ ][ ]=new int [3][10][5];
  • 15.
     A multidimensionalarray can be initialized by enclosing each dimension initializer list within its own set of curly braces. type array_name[ ][ ]={ {val,val,val…val}, {val,val,val…val}, . . {val,val,val…val}, };
  • 16.
    class squares{ public staticvoid main(String args[]){ int square[][]={{1,1},{2,4},{3,9},{4,16},{5,25}}; int i,j; for(i=0;i<5;i++){ for(j=0;j<2;j++) System.out.print(square[i][j]+" "); System.out.println(); } } }
  • 17.
     type[ ]var_name;  Eg : int counter[]=new int[3];  int [] counter=new int[3];  Both the above statements are same  This approach is helpful when you want to create multiple arrays of the same type  int num0[],num1[],num2[];  Better approach is  int [ ] num0,num1,num2;
  • 18.
     When youassign one array reference variable to another, you are simply changing what object that variable refers to.  You are not causing a copy of the array to be made nor you are causing the contents of one of array to be copied to another.
  • 19.
    class AssignAref { public staticvoid main(String args[]){ int i; int nums1[]=new int[10]; int nums2[]=new int[10]; for(i=0;i<10;i++) nums1[i]= i; for(i=0;i<10;i++) nums2[i]= -i; System.out.print("num1:"); for(i=0;i<10;i++) System.out.print(nums1[i]+" " ); System.out.println(); System.out.print("num2:"); for(i=0;i<10;i++) System.out.print(nums2[i]+" " ); System.out.println(); //make num2 refer to num1 nums2=nums1; System.out.print("here is nums2 after assignment:"); for(i=0;i<10;i++) System.out.print(nums2[i]+" " ); System.out.println(); //operate on nums1 array through nums2 nums2[3]=99; System.out.print("here is nums1 after change through nums2"); for(i=0;i<10;i++) System.out.print(nums1[i]+" " ); System.out.println(); } }
  • 20.
     Arrays areimplemented as objects, each array is associated with a length instance variable that contains the number of elements that array can hold.  Length contains size of the array
  • 21.
    class lengthDemo{ public staticvoid main(String args[]){ int list[]=new int[10]; int nums[]={1,2,3}; int table[][]={{1,2,3},{4,5},{6,7,8 ,9}}; System.out.println("length of the list is "+list.length); System.out.println("length if nums "+nums.length); System.out.println("length of table is: "+table.length); for(int i=0;i<table.length;i++) System.out.println("lengh of table["+i+"] is "+table[i].length); System.out.println(); for(int j=0;j<list.length;j++) list[j]=j*j; for(int k=0;k<list.length;k++) System.out.print(list[ k]+" "); System.out.println(); } }
  • 22.
     A for-eachloop cycles through a collection of objects such as array in strictly sequential fashion from start to finish.  It is released in JDK 5, for-each is also referred as enhanced for loop  Syntax: for(type itr_variable: collection) statement block;  type specifies the data type of the iteration variable i.e itr_variable  That will receive elements from collections one at a time from beginning to the end of the collection
  • 23.
     Itr_variable recievesthe data from collection, hence type of the collection and itr_variable should be same always class EnhancedForLoop { public static void main(String[] args) { int primes[] = { 2, 3, 5, 7, 11, 13, 17}; for (int t: primes) { System.out.println(t); } } }
  • 24.
     If wewant to terminate the for-each loop before completion of all the loops, one can use “break” statement. class EnhancedForLoop { public static void main(String[] args) { int primes[] = { 2, 3, 5, 7, 11, 13, 17}; for (int t: primes) { System.out.println(t); if(t==5)break; } } }
  • 25.
     Itr_variable isonly for read only purpose.  An assignement to the iteration variable has no effect on underlying array. class EnhancedForLoop { public static void main(String[] args) { int primes[] = { 2, 3, 5, 7, 11, 13, 17}; for (int t: primes) { System.out.print(t+" "); t=t*2; } System.out.println(); for (int t: primes) { System.out.print(t+" "); } } }
  • 26.
     Enhanced forloop works for multidimensional arrays.  Multidimensional array is arrays of array.  Two dimensional array is an array of one dimensional array.  In each iteration, it obtains next array not an individual element
  • 27.
    class Foreach2{ public staticvoid main(String args[]) { int sum=0; int nums[][]=new int[3][5]; for(int i=0;i<nums.length;i++) for(int j=0;j<nums[i].length;j++) nums[i][j]=(i+1)*(j+1); System.out.println("Value is :"); for(int x[]:nums){ for(int y:x){ System.out.print(y+" "); sum+=y; } System.out.println(); } System.out.println("Summation :"+sum); } }
  • 28.
     Used forsearching of the data in the given set of numbers.  Can be used for searching in unsorted array  It stops when the key is found.
  • 29.
    class search{ public staticvoid main(String args[]) { int nums[]={6,8,3,7,5,6,1,4}; int key=5; boolean found=true; for(int x:nums) if(x==key){ found=true; break; } if(found) System.out.print("Value found!!"); } }
  • 30.
     String definesand supports character strings  In other languages string is an array of characters  Here strings are objects.
  • 31.
     By usingnew and calling String constructor.  String str=new String(“hello” );  String object called str will contain a string called “hello”
  • 32.
    Method Meaning boolean equals(str)Returns true if the involving string contains the same character sequence as str int length() Obtains the length of the str char chatAt(index) Obtains character at index mentioned int compareTo(str) Returns less than zero if the invoking string is less than str, gretaer than zero if invking string is greater than str and zero if they are equal int indexOf(str) Searches invoking string for substring specified by str. Returns the index of the first match or -1 on failure int lastIndexOf(str) Searches invoking string for substring specified by str. Returns the index of the last match or -1 on failure
  • 33.
    class StrOps{ public staticvoid main(String args[]){ String str1="when it come to web programming, Java is #1."; String str2=new String(str1); String str3="Java strings are powerfull"; int result,idx; char ch; System.out.println("length of str1:"+str1.length()); //display one charecter 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("String 1 and 2 are equal"); else System.out.println("String 1 and 2 are not equal"); if(str1.equals(str3)) System.out.println("String 1 and 3 are equal"); else System.out.println("String 1 and 3 are not equal"); result=str1.compareTo(str3); if(result==0) System.out.println("String 1 and 3 are not equal"); else if(result<0) System.out.println("String 1 is less than string 3"); else System.out.println("String 1 is greater than string 3"); str2="one two three one"; idx=str2.indexOf("one"); System.out.println("Index of first occurance of one :"+idx); idx=str2.lastIndexOf("one"); System.out.println("Index of last occurance of one :"+idx); } }
  • 35.
     Can beeasily performed by using + between strings. String str=“java”; String sr1=“programming”; String finalstring=str+str1;
  • 36.
    class StringArrays{ public staticvoid main(String args[]){ String strs[]={"this", "is", "a","test"}; System.out.println("original array"); for(String s:strs) System.out.print(s+" "); System.out.println(); //change in a string strs[1]="was"; strs[3]="test,tool"; System.out.println("After modification"); for(String s:strs) System.out.print(s+" "); } }
  • 37.
     Once created,the character sequence that makes up the string cannot be altered.  When a change is required , you just have to create a new string, the unused strings are automatically garbage collected.  substring()- method returns a new string that contains a specified portion of the invoking string.
  • 38.
    class Substr{ public staticvoid main(String args[]) { String orgstring="java programming is the best!"; String substring=orgstring.substring(5,12); System.out.println("original string:"+orgstring+"nSubstring is :"+substring); } }
  • 39.
    class Stringswitch{ public staticvoid main(String args[]) { String choice="cancel"; switch(choice){ case "connect": System.out.println("Connecting!"); break; case "cancel":System.out.println("cancelling!"); break; default: System.out.println("Enter correct string"); break; } } }
  • 40.
     A commandline argument is the information that directly follows the program’s name on the command line when it is executed.  They are stored in String array passed in the main()
  • 41.
    class CLDemo { public staticvoid main(String args[]) { System.out.println("These are:"+args.length+" command line arguements"); System.out.println("they are:"); for(int i=0;i<args.length;i++) System.out.println("args["+i+"]:"+args[i]); } }