(c) D. R.
Gangodkar
• Index begins with 0.
• if the index goes beyond the allocated capacity,
(As it cannot be determined at compile time),
ArrayIndexOutOfBoundsException is thrown at Run-time
(c) D. R. Gangodkar
Lets create some arrays:
int array:
int ia[ ] ; //Declaration
//int [ ] ia ; also OK
a=new int [10];
char array:
char ca [ ];
ca= new char [5];
and so on..
• arrays ( Local as well as instance ) are
automatically initialized to the default value for the
type
• e.g. int 0 , float 0.0 , boolean false
char '\u0000‘ (NULL) (c) D. R. Gangodkar
Example: Create an int array to store 10 elements and print
default values in Tabular format
public class InitArray
{
public static void main( String[ ] args )
{
int[ ] a; // declare array named array
a= new int[ 10 ]; // create the array object
//ALSO possible int[ ] a=new int [ 10 ];
[Link]( "%s%8s\n", "Index", "Value" );
// output each array element's value
for ( int index= 0; index < [Link]; index ++ )
[Link]( "%5d%8d\n", index, a [index] );
} // end main
} // end class InitArray
Output next slide…
(c) D. R. Gangodkar
Output: Note: arrays are automatically initialized ( Local
as well as instance )
(c) D. R. Gangodkar
Declare and initialize an Array
Write a program to implement Bubble sort using array
(c) D. R. Gangodkar
Declare and initialize an Array
Write a program to implement Bubble sort using array
We understand: (1) How to declare and initialize array (2) How to write a method
that has array as parameter (3) How to pass an array
class BubbleSort /* Prints the array */
{ //Method of a class void printArray (int arr[ ])
void bubbleSort( int arr[ ] ) //Param {
{ int n = [Link];
int n = [Link]; for (int i=0; i<n; ++i)
for (int i = 0; i < n-1; i++) [Link](arr[i] + " ");
for (int j = 0; j < n-i-1; j++) [Link]();
if (arr[j] > arr[j+1]) } //end of printArray
{ public static void main(String args[])
// swap {
int temp = arr[j]; int arr[ ] = {64, 34, 25, 12, 22, 11, 90}; //Initial
arr[j] = arr[j+1]; BubbleSort ob = new BubbleSort();
arr[j+1] = temp; [Link](arr); //passing array
} [Link]("Sorted array");
} //end of bubbleSort [Link](arr);
} //end of main
(c) D. R. Gangodkar
} //End of class
Declare and initialize an Array
Output:
Sorted array: 11 12 22 25 34 64 90
Homework:
Write a program to print the marks
(out of 100 ) obtained by 15
students of a class. Display each
students roll no and marks. Display
class average, max and min marks
obtained.
(c) D. R. Gangodkar
3. Initialization
for(i=0; i< 2; i++)
{
for(j=0; j< 3; j++)
{
a [ i ][ j ] =
20;
}
}
Also: Declare and Initialize
(c) D. R. Gangodkar
Write a Program to transpose a 2D matrix. i.e. rows to column
class 2DTranspose
{
public static void main(String args[ ])
{
int a1[ ][ ]=new int [3][4];
int a2[ ][ ]=new int [4][3];
int count=0; // for initializing matrix a1
//Initialize the content of Matrix a1
for(int i=0; i<[Link]; i++)
{
for (int j=0; j<a1[ i ].length; j++)
{
a1[ i ][ j ]=count++; //Some values
[Link] (a1[i][j]+" "); //Display matrix contents
}
[Link]();
} //end of for i (c) D. R. Gangodkar
//Transpose
for(int i=0; i<[Link]; i++)
{
for (int j=0; j<a1[i].length; j++)
{
a2[ j ][ i ]=a1[ i ][ j ]; //Logic copy from i, j to j, i
}
}
//Display the Transpose
for(int i=0; i<[Link]; i++)
{
for (int j=0; j<a2[i].length; j++)
{
[Link] (a2[ i ][ j ]+" ");
}
[Link]();
}
}//End of main
}//End of class (c) D. R. Gangodkar
Variable column matrix
• Problem statement : Declare an array with two rows. First
row has two columns and second row has four columns
int aryInt [ ][ ]= new int[2][ ]; //second dimension not mentioned
aryInt [0]= new int[2];//row 1 (index 0) has two elements
aryInt[1]=new int [4]; //row 2 (index 1) has four elements
(c) D. R. Gangodkar
Variable column matrix
Program: Write a java program for creating the two
dimensional integer matrix as shown below. Initialize the
elements and print the values.
Solution on the next slide…
(c) D. R. Gangodkar
Class AryTest
{
public static void main(String [] args)
{
int arry[ ][ ];//Matrix reference
arry= new int [3][ ];//Specify only rows
// Create columns for each row
arry[0]=new int[2];
arry[1]=new int[4];
arry[2]=new int[3];
for (int i=0; i<[Link]; i++)//Initialize elements
{
for (int j=0; j< arry[i].length; j++)
{
arry[i][j]= i + j;//Initialize with some value
}
} (c) D. R. Gangodkar
//Display the contents of matrix
for (int i=0; i<[Link]; i++)
{
for (int j=0; j<arry[i].length; j++)
{
[Link] (" "+arry[i][j]);
}
[Link]();
}
}//End of main
}//end of class Click to see the output
01
1234
234
(c) D. R. Gangodkar
134
Lets understand Dynamic creation of an array.
Write a program to read the size and
elements of an integer array from the user.
Display the elements
Solution on the next slide…
(c) D. R. Gangodkar
Import [Link];
class DynamicArray {
public static void main(String args[ ])
{
Scanner sc=new Scanner([Link]);
[Link]("Enter the size of int array ");
int size=[Link]();
int a[ ]=new int[size];
[Link]("Enter the elements of an array ");
for (int i=0;i<[Link]; i++)
{
a[i]=[Link]();
}
[Link]("You have entered: ");
for (int i=0;i<[Link]; i++)
{
[Link](a[i]);
}
}
(c) D. R. Gangodkar
(c) D. R. Gangodkar
(c) D. R. Gangodkar
(c) D. R. Gangodkar
(c) D. R. Gangodkar
(c) D. R. Gangodkar
public class Comparison
{
public static void main(String[] args)
{
int n = 2;
if (n != 0 && n > 10)
[Link]("This is true");
else
[Link]("This is false");
}
(c) D. R. Gangodkar
(c) D. R. Gangodkar
(c) D. R. Gangodkar
class IncDec
{
public static void main(String args[ ])
{
int a = 1;
int b = 2;
int c, d;
c = ++b;
d = a++;
c++;
[Link](“a= “ + a);
[Link](“b= “ + b);
[Link](“c= “ + c);
}
} (c) D. R. Gangodkar
Conditional Operator
Bitwise Operator
(c) D. R. Gangodkar
Special Operators
boolean b= manager instanceof BankEmployee;
(c) D. R. Gangodkar
(c) D. R. Gangodkar
(c) D. R. Gangodkar
(c) D. R. Gangodkar
(c) D. R. Gangodkar
(c) D. R. Gangodkar
(c) D. R. Gangodkar
Note: Expression must evaluate to true or false
(c) D. R. Gangodkar
Read a month in numeral and display the season
using if-else as below:
Month Season
12, 1, 2 Winter
3, 4, 5 Spring
6, 7, 8 Summer
9, 10, 11 Autumn
(c) D. R. Gangodkar
Lets write a program
Read a month in numeral and display the season
using if-else as below:
Month Season
12, 1, 2 Winter
3, 4, 5 Spring
6, 7, 8 Summer
9, 10, 11 Autumn
(c) D. R. Gangodkar
class IfElse
{
public static void main(String args[])
{
int month = 4;
String season;
if (month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else season = "Bogus Month";
[Link]("April is in the " + season + ".");
}
} (c) D. R. Gangodkar
In the JDK 7 release, you can use a String object in the
expression of a switch statement:
(c) D. R. Gangodkar
e.g.
String s1=“data1”;
int a=2;
switch (s1)
switch (a)
{
{
case “data1”:….. break;
case 1:….. break;
case “data2”:….. break;
case 2 :….. break;
default:
default:
}
}
Write the seasons program using switch statement
(c) D. R. Gangodkar
Program: Given a month in numerals, print the season of the
Year (i.e. Winter, Spring, Summer and Autumn)
e.g. enter a month
2
Winter
class Switch
{
public static void main(String args[])
{
int month = 4;
String season;
switch (month)
{
case 12:
case 1:
case 2: season = "Winter"; break;
case 3:
case 4:
case 5: season = "Spring"; break;
case 6:
case 7:
case 8: season = "Summer"; break;
(c) D. R. Gangodkar
case 9:
case 10:
case 11: season = "Autumn"; break;
default: season = "Bogus Month";
}
[Link]("April is in " + season + ".");
}
}
(c) D. R. Gangodkar
Write a Program to simulate a simple
calculator. Add, subtract, multiply and divide
using switch statement
(c) D. R. Gangodkar
double num1=0, num2=0, result=0;
Scanner sc=new Scanner([Link]);
[Link]("Enter the first value: ");
num1=[Link]();
[Link]("Enter the second value: ");
num2=[Link]();
[Link]("Enter the operator +, -, * or /: ");
char op= [Link]().charAt(0);
switch (op)
{
case '+': result=num1+num2;
break;
case '-': result=num1-num2;
break;
case '*': result=num1*num2;
break;
case '/': result=num1/num2;
break;
default: [Link]("Wrong operator");
return;
}
[Link](num1+" "+op+" "+num2+"="+result);
(c) D. R. Gangodkar
Nested Switch statement using two variables
i and j
int i = 0;
int j = 1;
switch(i)
{
case 0:
switch(j)
{
case 0:
[Link]("i is 0, j is 0"); break;
case 1:
[Link]("i is 0, j is 1"); break;
default:
[Link]("nested default case!!");
}
break;
default: [Link]("No matching case found!!");
}
(c) D. R. Gangodkar
Write a program to demonstrate the nested
switch statement as below:
Read the value of i and j as integer and print
the message for following conditions:
i j Message
0 0 Task T1
0 1 Task T2
1 0 Task T3
1 1 Task T4
Else invalid task
(c) D. R. Gangodkar
Scanner sc=new Scanner([Link]); //Scanner object
[Link]("Enter the values of i and j: ");
int i=[Link]();//Read the values
int j=[Link]();
switch(i)// Initially switch on the value of “i”
{
case 0:
switch(j)
{
case 0:[Link]("task1"); break;
case 1:[Link]("task2"); break;
default: [Link]("Invalid value of j");
}
break;
(c) D. R. Gangodkar
case 1:
switch(j)
{
case 0:[Link]("task3"); break;
case 1:[Link]("task4"); break;
default: [Link]("Invalid value of j");
}
break;
default:
[Link]("Invalid task");
break;
(c) D. R. Gangodkar
(c) D. R. Gangodkar
class DoWhile
{
public static void main(String args[])
{
int i;
i = 0;
do
i++;
while ( 1/i < 0.001);
[Link](“i is “ + i);
}
}
(c) D. R. Gangodkar
(c) D. R. Gangodkar
Initialization can have byte, short, int, long data types.
Although you can use float and double as well but use it
with caution
Lets see an example
(c) D. R. Gangodkar
Write a Program to check if the given
integer is a Prime number?
(c) D. R. Gangodkar
class FindPrime
{ //Check if the number is prime
public static void main(String args[])
{
int num = 14;
boolean isPrime = true;
for (int i=2; i < num/2; i++) //Usually SQRT(num)
{
if ((num % i) == 0)
{
isPrime = false;
break;
}
}
if (isPrime) [Link]("Prime");
else [Link]("Not Prime");
}
} (c) D. R. Gangodkar
(c) D. R. Gangodkar
class ForVar
{
public static void main(String args[])
{
int i = 0;
boolean done = false;
for( ; !done; )
{
[Link]("i is " + i);
if(i == 10)
done = true;
i++;
}
}
} (c) D. R. Gangodkar
Refer Symmetric problem in
Interesting Programs arrays and matrix
(c) D. R. Gangodkar
Lets understand the Java’s Command Line Argument Processing
• Write a program to read the command line arguments and
print them.
Class CommandLine
{
public static void main (String args[ ])
{
int argLength=[Link]; //Store in argLength
[Link] ("Command Line arg demo");
[Link] (“ No. of arguments”+argLength);
for(int i=0; i< argLength; i++)
{
[Link](args[i]+ " ");
}
[Link]("=====");
}
(c) D. R. Gangodkar
Lets Program the following
1. Write a Program to read two integers from user and print
the largest and smallest
2. Write a Program to read three integers from user and the
prints sum, average, product, smallest and largest of the
numbers
clue for program 2 on next page……….
(c) D. R. Gangodkar
Lets Program the following
// convert numbers from type String to type int
number1 = Read from Keyboard
number2 = Read from Keyboard
number3 = Read from Keyboard
// initialize largest and smallest
largest = number1;
smallest = number2;
// determine correct values
if ( number2 >= number1 )
{
largest = number2;
smallest = number1;
}
if ( number3 > largest )
largest = number3;
if ( number3 < smallest )
smallest = number3;
(c) D. R. Gangodkar