You are on page 1of 15

3.

Java Expressions & Flow Control


Variable Scope, Lifetime and Initialisation Operator Precedence Branching Statements Looping Statements Java Strings Java Parameter Passing

159.235

Graphics

Variable scope, lifetime & initialisation


The scope of variables in a Java program depends on where they are declared. If a variable is declared outside all methods (i.e. at class level)
The variable is global to the class. The variable's contents are accessible inside all methods. Variable contents are initialised to data-type default (see previous table in section 2).

Variables declared inside a method


The variable is only available inside the defining method. The variable exists only while the method is executing. These variables are called automatic, local, temporary, or stack variables. Variable contents are not initialised. (You will get compiler error messages if you read the variable before writing it. When a variable is declared, it is put onto the stack. When an object is created using new, it is put into the heap. Heap variables are cleaned-up by the System Garbage Collector when memory gets low.
Graphics 2

159.235

Precedence 1

Java Operator ++ -+ ~ ! (type) * + + << >> >>> < <= > >= instanceof == != == != & & ^ ^ | | && || / %

Operands Arithmetic Arithmetic Arithmetic Integral Boolean Any Arithmetic Arithmetic String Integral Integral Integral Arithmetic Arithmetic Object, type Primitive Primitive Object Object Integral Boolean Integral Boolean Integral Boolean Boolean Boolean

Associativity Right Right Right Right Right Right Left Left Left Left Left Left Left Left Left Left Left Left Left Left Left Left Left Left Left Left Left

Description Unary pre/post decrement Unary pre/post decrement Unary plus and minus Unary bitwise complement Unary logical complement cast Multiplication, division and remainder Addition and subtraction String concatenation Left shift Right shift with sign extension Right shift with zero extension Less than, less than or equal Greater than, greater than or equal Type comparison Equality test (value) Inequality test (value) Equality (refer to the same object) Inequality (refer to different objects) Bitwise AND Boolean AND Bitwise XOR Boolean XOR Bitwise OR Boolean OR Conditional AND Conditional OR

2 3 4

7 8 9 10 11

12
13

?:
= *= /= %/ += -= >>>= &= ^= |= <<= >>=

Boolean, any, any


Variable, any Variable, any

Right
Right Right

Conditional ternary
Assignment Assignment with operation

159.235

Graphics

Operator Examples
System.out.println( "Hello" + "World" );
String str1; if( str1 instanceof String ){...} 256 >> 2 is 64 (arithmetic) right shift -256 >> 3 is -64 sign bit copied, and uses 2's complement -256 >>>3 is 32 (logical shift) >>> on short or byte gets promoted to int

System.out.print(text with no newline);


int i = 42; System.out.println( Output is + i ); + is String concatenation and the system knows how to make almost everything into some sort of String representation -even references which end up looking like hexadecimal numbers (a bit like pointers in C++)

159.235

Graphics

159.235

public class Loops{ public static void main( String args[] ) { int i; for(i=0;i<3;i++){ System.out.print(i + " "); } System.out.println(); int j, k; for(j = 0, k = 0; k<5; j++,k=j*2){ System.out.print(k + " "); } System.out.println(); boolean test = true; i = 0; while( test ){ i++; if( i > 4 ) test = false; System.out.print(i + " "); } System.out.println(); i = 0; do{ i += 2; System.out.print( i + " "); }while( i < 7 ); System.out.println(); for(i=0;i<5;i++){ System.out.print(i+" "); if( i == 3 ) break; } System.out.println(); mylabel: // jump point for outer loop for(j=0;j<3;j++){ for(i=0;i<5;i++){ System.out.print(i+" "); if( j == 1 && i == 3 ) break; if( i == 3 ) continue mylabel; } System.out.println(); } System.out.println(); }}

Loop Control Structures


for( ; ; ){ } like in C
while( ){ }

do { }while( );
break, continue and labels allowed.

Results:
> java Loops 012 024 12345 2468 0123 01230123 0123 >

Graphics

Branch Control
if( ){ }else{ } as in C/C++ switch (on any discrete type such as short,int, byte or char ), Remember break statement! Example results: > java Branches 1 >7 i <= 10 i == 7 i >= 6 >
159.235 Graphics
}

public class Branches{

public static void main( String args[] ) {


int i = Prompts.getint("> "); if( i > 10 ){ System.out.println(" i > 10"); } else{ System.out.println(" i <= 10"); } if( i > 10 ){ System.out.println(" i > 10"); } else if( i == 7 ){ System.out.println(" i == 7"); } else{ System.out.println(" i <= 10 && i != 7"); } switch( i ) { case 0: System.out.println(" i = 0"); break; case 1: System.out.println(" i = 1"); break; case 2: case 3: case 4: case 5: System.out.println(" i = 2,3,4 or 5"); break; default: System.out.println(" i >= 6"); break; }

Java uses Pass Args-by-Value


Java methods always pass arguments by value reference types can be passed however (the reference itself is copied but what it refers to is not) Example results: > java ArgsByValue you're not going to like this... The Ultimate Answer 54.0 you're not going to like this... luckily using the force puts it right...42.0 >
159.235 Graphics
public class ArgsByValue{ float x; String y; public static void main(String args[]){ ArgsByValue a = new ArgsByValue(); float f = 54F; String str = "The Ultimate Answer "; a.setfloat(f); a.setString(str); str = "you're not going to like this..."; System.out.println(str ); System.out.println(a.y + a.x );

a.force( a ); System.out.println(a.y + a.x );


} public void setfloat( float f ){ x = f; f = 42F; } public void setString( String s ){ y = s; s = "to Life, the Universe and Everything"; } public void force( ArgsByValue aa ){ aa.x = 42F; aa.y = "luckily using the force puts it right..."; } }

Java Strings
Strings are objects, with range of methods String contents cannot be changed once defined use a StringBuffer for dynamic contents Strings have a length() method Example results:
> java Strings String1: Test String 2 String2: another string String3: a string on the heap String4: a string on the sheep >
159.235
public class Strings{ public static void main( String args[] ) { String str1; // reference set up but no instantiation yet String str2 = "Test String 2"; // ref to literal on stack

str1 = str2; // both now point to the literal str2 = "another string"; // 2 points to a different literal String str3 = new String("a string on the heap"); // combine declaration & instantiation
System.out.println("String1: " + str1 ); // String concat operator System.out.println("String2: " + str2 ); System.out.println("String3: " + str3 ); // StringBuffers are elastic and can change contents (Strings can't) StringBuffer str4 = new StringBuffer( str3 ); str4.setCharAt( 16, 's'); str4.setCharAt( 19, 'e'); System.out.println("String4: " + str4 ); } }

Graphics

3. Exercises
Create a program called Sum that calculates the partial sum of the numbers 1 to x. The program should print out a table of values for x and the partial sum calculated so far. Test your program with the following int values of x: 5, 10, 20 and 100. The length of the circumference, c, of any circle can be represented by the formula c = pi * r, and the area, a is a=pi r^2, where r is the radius. Write a program called Circles to calculate the c and a for a range of floating-point values of r. Compile and run your program. What are the results? If you did not already do so in the previous exercise, write your code using separate methods to calculate the circumference and area of the circle, parameterised by the radius. Re-compile and run your program. Ensure that the name and address fields of the Person class are represented as Strings. Search the on-line API to find the Date class; is this appropriate for representing a Person's date of birth? In the main() method add code to assign names, addresses and birth dates to father, mother and child. Compile and run your program. Ensure the output is what you anticipated.

159.235

Graphics

4. Java Exceptions
Similar to C++ exception mechanisms What are Exceptions?
Catching Exceptions Creating Your Own Exceptions Catching Your Own Exceptions

Exceptions are mild error conditions that your programs may encounter. In most languages, the program simply terminates; in Java you have the option of handling the errors as they occur. In Java, these mild errors are implemented by the Exception class.
Graphics 10

159.235

The Error class is used to implement more serious error conditions. Although it is possible for the user to handle Errors, due to their serious nature it is often advisable to let the program terminate. When an error occurs in your program, the code that finds the error can either handle the error, or allow the error to propagate up the program's call stack. In order to propagate the exception up the call stack, the method must declare that it throws the exception.
159.235

Any exceptions that are able to be thrown by each method are documented in the Java API Documentation.

Common exceptions - useful to know about:


ArrayIndexOutOfBoundsExc eption ArithmeticException (divide by zero for ints) NullPointerException NegativeArraySizeException SecurityException IOException
11

Graphics

Example Results:
> java ArrayError Zeroth String First String Second String Last String Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at ArrayError.main(ArrayError.java:13) >

public class ArrayError { public static void main (String args[]) { int i=0; String []greetings = { "Zeroth String", "First String", "Second String", "Last String" }; while (i<5) { System.out.println(greetings[i]); i++; } } }

The program crashes because main makes no attempt to catch the exception

159.235

Graphics

12

Catching Exceptions All exception-causing methods must be within a


try block Programmer must catch all possible exceptions thrown by methods in the try block (even if they are re-thrown). Also use finally
Defines a block of code which is always executed even if an exception occurs. if an exception handler calls System.exit()} the finally block is not executed as the program immediately terminates.
import java.io.*; public class Catch{ public static void main( String args[] ) throws IOException{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); String line; // = in.readLine(); // flush input // readLine() throws IOException int value = 0; System.out.print("Enter an integer: ");// write out a prompt line = in.readLine(); // read line of input

Example results: > java Catch Enter an integer: 12 Value is: 12 > java Catch Enter an integer: abc Input corrupted, using default Value is: 0 >
159.235 Graphics

try{ // attempt to parse String value = Integer.parseInt(line); } catch( NumberFormatException e ){ // catch malformed input value = 0; System.out.println("Input corrupted, using default"); } finally{ // always do following System.out.println("Value is: " + value ); }
} }

13

Throwing your own Exceptions


extend Exception class incorporate your own methods and variables eg to convey details of what happened
public class Throwing{ public static void main( String args[] ){ Kid k = new Kid(); try{ k.action(); } catch( Tantrum t ){ System.out.println( t.getDescriptor() ); } } } class Kid{ public void action() throws Tantrum{ boolean bored = true; if( bored ) throw new Tantrum("I'm bored"); } } class Tantrum extends Exception{ private String descriptor; public Tantrum(){ descriptor = "Unknown cause"; } public Tantrum( String s ){ descriptor = s; } public String getDescriptor(){ return descriptor; } }

nothing to stop a programmer catching one exception only to throw a new one Example results: > java Throwing I'm bored >
159.235

Graphics

14

4. Exercises
Augment the program you wrote to calculate partial sums with the code in Catch.java for reading in values from the keyboard. Ensure the program prints an appropriate message even when user input is invalid. What happens when user input is negative? Augment the program you wrote to calculate the circumference and area of a circle with the code in Catch.java for reading in values from the keyboard. Use the Person class you created earlier. Write a class called UnknownPersonException, which will be thrown when a user tries to access an unknown Person in a database.
159.235 Graphics 15

You might also like