CS 596 Client-Server Programming
Java Control Structures
[To Lecture Notes Index]
San Diego State University -- This page last updated January 31, 1996
Contents of Java Control Structures Lecture
- Control Structures
- Jump Statements
- Arrays
- Arrays and Memory Leaks
- Out-of Bounds - Exceptions
- Exceptions and Function Calls
- Builtin Exceptions
Contains all the standard C/C++ control structures
class Control
{
public static void main( String args[] )
{
int a = 5;
int b = 10;
if ( a > b ) System.out.println( "a is bigger ");
if ( a > b )
System.out.println( "a is bigger ");
else
System.out.println( "b is bigger ");
switch ( a )
{ //Controlling expression converted to int
case 4:
b++;
break;
case 10:
b--;
break;
default: // optional
System.out.println( "Default action" );
};
while ( a < b )
{
a++;
};
// Control Structures Continued
for ( int loop = 0; loop < a; loop++ )
{
System.out.println( a );
};
System.out.println( loop ); // Error, loop does not
// exist here
do
{
System.out.println( a-- );
System.out.println( b );
}
while ( a > b );
int max = ( a > b ) ? a : b;
if ( ( a > 5 ) && ( b < 10 ) )
System.out.println( "Good" );
a += ( a = 5 );
}
}
break, continue, return
class ControlStructures
{
public static void main( String args[] )
{
for ( int row = 0; row < 5; row++ )
{
for ( int column = 0; column < 4 ; column++ )
{
System.out.println( row + "\t" + column );
if ( ((row + column) % 2 ) == 0 )
break;
System.out.println( " After if " );
}
};
Outer:
for ( int row = 0; row < 5; row++ )
{
for ( int column = 0; column < 4; column++ )
{
System.out.println( row + "\t" + column );
if ( ((row + column) % 2 ) == 0 )
break Outer;
System.out.println( " After if " );
}
}
}
}
Output
0 0 | 3 0 |
1 0 | After if |
After if | 3 1 |
1 1 | 4 0 |
2 0 | 0 0 |
class ArrayExamples
{
public static void main( String args[] )
{
int declarationTypeA[] = new int[5];
float[] floatArray = new float[ 25 ];;
int[] integerArray;
int[] alias;
integerArray = new int[ 10 ]; // Indexed from 0 to 9
for ( int index = 0; index < integerArray.length; index++ )
integerArray[ index ] = 5;
alias = integerArray; // Arrays are references
alias[ 3 ] = 10;
System.out.println( integerArray[ 3 ] );
integerArray = new int[ 8 ];
System.out.println( integerArray[ 3 ] );
System.out.println( alias[ 3 ] );
System.out.println( integerArray );
int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
char[] vowels = { 'a', 'e', 'o', 'i', 'u' };
}
}
Output
10
0
10
[I@5e300868
Multidimensional Arrays
class MultidimensionalArrayExample
{
public static void main( String args[] )
{
int[][] squareArray = new int [ 10 ] [ 20 ];
squareArray[ 2 ] [ 5 ] = 25;
int[][][] threeDArray = new int [ 10 ] [ 20 ][ 5 ];
int[][] triangularArray;
triangularArray = new int [ 30 ] [ ] ;
for ( int row = 0; row < triangularArray.length; row ++ )
triangularArray [ row ] = new int [ row ];
for ( int row = 0; row < triangularArray.length; row ++ )
for ( int col = 0; col < triangularArray[ row ].length; col++ )
triangularArray[ row ][ col ] = 10;
}
}
Arrays are references!
Garbage collection reclaims arrays that can not be accessed!
References are initialized to null
When done with a reference set it to null
class ArrayExamples
{
public static void main( String args[] )
{
int[] integerArray = new int[ 10 ];
integerArray = new int[ 5 ]; // Memory Leak - No!
integerArray[ 1 ] = 5;
int[] aliasForArray = integerArray;
aliasForArray[ 1 ] = 10;
System.out.println( integerArray[ 1 ] ); //Prints 10
}
}
class ArrayOutOfBounds
{
public static void main( String args[] )
{
int students[] = new int[5];
students[ 10 ] = 1;
System.out.println( " The End" );
}
}
Output
java.lang.ArrayIndexOutOfBoundsException: 10
at ArrayOutofBounds.main(All.java:8)
Out-of Bounds - With try
class ArrayOutOfBounds
{
public static void main( String args[] )
{
int students[] = new int[5];
try
{
System.out.println( "Start Try" );
students[ 10 ] = 1;
System.out.println( "After assignment statement" );
}
catch (ArrayIndexOutOfBoundsException e)
{
System.err.println( "OutOfBounds: " + e.getMessage());
};
System.out.println( " After try " );
}
}
Output
Start Try
OutOfBounds: 10
After try
Multiple Exceptions
class MultipleExceptions
{
public static void main( String args[] )
{
int students[] = new int[5];
int classSize = 0;
try
{
System.out.println( "Start Try" );
int classAverage = 10 / classSize;
System.out.println( "After class average" );
students[ 10 ] = 1;
System.out.println( "After array statement" );
}
catch (ArrayIndexOutOfBoundsException e)
{
System.err.println( "OutOfBounds: " + e.getMessage());
}
catch ( ArithmeticException e )
{
System.err.println( " Math Error" + e.getMessage() );
}
System.out.println( " After try " );
}
}
Output
Start Try
Math Error/ by zero
After try
One Size Fits All Exception
class MultipleExceptions
{
public static void main( String args[] )
{
int students[] = new int[5];
int classSize = 0;
try
{
System.out.println( "Start Try" );
students[ 10 ] = 1;
System.out.println( "After array statement" );
int classAverage = 10 / classSize;
}
catch ( Exception e )
{
System.err.println( "Exception:" + e.getMessage());
e.printStackTrace();
}
System.out.println( " After try " );
}
}
Output
Start Try
Exception:10
java.lang.ArrayIndexOutOfBoundsException: 10
at MultipleExceptions.main(All.java:11)
After try
Beware of Order
class MultipleExceptions
{
public static void main( String args[] )
{
int students[] = new int[5];
int classSize = 0;
try
{
System.out.println( "Start Try" );
students[ 10 ] = 1;
System.out.println( "After array statement" );
int classAverage = 10 / classSize;
}
catch ( Exception e )
{
System.err.println( "Exception:" + e.getMessage());
e.printStackTrace();
}
catch (ArrayIndexOutOfBoundsException e)
{
System.err.println( "OutOfBounds: " + e.getMessage());
}
System.out.println( " After try " );
}
}
Compile Error
All.java:21: catch not reached.
} catch (ArrayIndexOutOfBoundsException e) {
^
1 error
Select the First Exception That Applies
class MultipleExceptions
{
public static void main( String args[] )
{
int students[] = new int[5];
int classSize = 0;
try
{
System.out.println( "Start Try" );
students[ 10 ] = 1;
System.out.println( "After array statement" );
int classAverage = 10 / classSize;
}
catch (ArrayIndexOutOfBoundsException e)
{
System.err.println( "OutOfBounds: " +
e.getMessage());
}
catch ( Exception e )
{
System.err.println( "Exception:" + e.getMessage());
e.printStackTrace();
}
System.out.println( " After try " );
}
}
Output
Start Try
OutOfBounds: 10
After try
Final Block - For Clean Up
class FinalBlockWithExceptionCalled
{
public static void main( String args[] )
{
int students[] = new int[5];
try
{
System.out.println( "Start Try" );
students[ 10 ] = 1;
System.out.println( "After array statement" );
}
catch (ArrayIndexOutOfBoundsException e)
{
System.err.println( "OutOfBounds: " + e.getMessage());
}
finally
{
System.out.println( "In Final Block" );
}
System.out.println( " After try " );
}
}
Output
OutOfBounds: 10
In Final Block
After try
Final Block - Always Called
class FinalBlockExceptionNotCalled
{
public static void main( String args[] )
{
int students[] = new int[5];
try
{
System.out.println( "Start Try" );
students[ 2 ] = 1;
System.out.println( "After array statement" );
}
catch (ArrayIndexOutOfBoundsException e)
{
System.err.println( "OutOfBounds: " + e.getMessage());
}
finally
{
System.out.println( "In Final Block" );
}
System.out.println( " After try " );
}
}
Output
Start Try
After array statement
In Final Block
After try
class ExceptionFunction
{
public static void change( int[] course )
{
System.out.println( "Start Change" );
course[ 10 ] = 1;
System.out.println( "End Change" );
};
public static void main( String args[] )
{
int students[] = new int[5];
try
{
System.out.println( "Start Try" );
change( students );
System.out.println( "After array statement" );
}
catch (ArrayIndexOutOfBoundsException e)
{
System.err.println( "OutOfBounds: " + e.getMessage());
}
finally
{
System.out.println( "In Final Block" );
}
System.out.println( " After try " );
}
}
Output
Start Try
Start Change
OutOfBounds: 10
In Final Block
After try
Can't Escape Finally
class ExceptionFunction
{
public static boolean change( int[] course )
{
try
{
System.out.println( "Start change" );
course[ 10 ] = 1;
System.out.println( "End Change" );
}
catch (ArrayIndexOutOfBoundsException e)
{
System.err.println( "OutOfBounds: " );
return true;
}
finally
{
System.out.println( "In Final Block" );
}
return false;
};
public static void main( String args[] )
{
int students[] = new int[5];
System.out.println( "Main" );
System.out.println( change( students ) );
System.out.println( "After Change" );
}
}
Output
Main In Final Block
Start Change true
OutOfBounds: After Change
AWTException | InstantiationException |
ArithmeticException | InterruptedException |
ArrayIndexOutOfBoundsException | InterruptedIOException |
ArrayStoreException | MalformedURLException |
ClassCastException | NegativeArraysizeException |
ClassNotFoundException | NoSuchElementException |
CloneNotSupportedException | NoSuchMethodException |
EOFException | NullPointerException |
EmptyStackException | NumberFormatException |
Exception | ProtocolException |
FileNotFoundException | RuntimeException |
IOException | SecurityException |
IllegalAccessException | SocketException |
IllegalArgumentException | StringIndexOutOfBoundsException |
IllegalMonitorStateException | UTFDataFormatException |
IllegalThreadStateException | UnknownHostException |
IndexOutOfBoundsException | UnknownServiceException |
Errors
AWTError | LinkageErrorNoClassDefFoundError |
AbstractMethodError | NoSuchFieldErrorNoSuchMethodError |
ClassCircularityError | OutOfMemoryError |
ClassFormatErrorError | StackOverflowError |
IllegalAccessError | UnknownError |
IncompatibleClassChangeError | UnsatisfiedLinkErrorVerifyError |
InstantiationErrorInternalError | VirtualMachineError |