1 / 24

159.234 LECTURE

159.234 LECTURE. 24. JAVA. Variables, Arrays, Operators, Expressions, Flow Control, Parameter Passing, Exceptions. Java Expressions & Flow Control. Variable Scope, Lifetime and Initialisation Operator Precedence Branching Statements Looping Statements Java Strings Java Parameter Passing.

washi
Download Presentation

159.234 LECTURE

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 159.234LECTURE 24 JAVA Variables, Arrays, Operators, Expressions, Flow Control, Parameter Passing, Exceptions

  2. Java Expressions & Flow Control • Variable Scope, Lifetime and Initialisation • Operator Precedence • Branching Statements • Looping Statements • Java Strings • Java Parameter Passing

  3. Variables Scope, Initialization & Lifetime public class Hello3{ private static String greetings = "Hello world!"; char N; public static void main(String[] args){ int i=0; System.out.println(greetings); for(int i=0; i < 10; i++){ //… } } } Class level, global to the class; initialized to data type default. automatic, local, temporary, or stack variable; valid only for the duration of the block. It is illegal to declare a variable in an inner block that has the same name as a variable in an outer block. (This is ok in C++)

  4. 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 ppt presentation, Java-1). 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. Variables Scope, Initialization & Lifetime

  5. Objects Objectsin Java can be created on the heap using new. e.g.: MyClass c = new MyClass(); float xa[] = new float[100]; • However, there is no equivalent of the C++ delete • The System Garbage Collector in the JVMautomatically • removes objects from the heap when they are no longer in • scope and when system resources become low.

  6. Arrays can be declared of any type: fundamental or class char a[]; Person people[]; The above declarations just declare the array reference -- not the objects in the array. Two forms of array declaration: char [] firstName; Person []people; Both forms are equivalent. With the latter you may consider the declaration as having the type on the left and the variable name on the right. Create arrays by using the new keyword firstName = new char[40]; people = new Person[50]; The two arrays are created but their contents are not. people contains 50 references, each to an object of type Person, whose value is null. Each Person object must be explicitly created: people[0] = new Person(); people[1] = new Person(); ...

  7. public class Person{ • ... • static public void main(String[] args) { • Person p = new Person("Napoleon"); • p.setAddress("Albany"); • p.setDateOfBirth(1945, 4, 25); • p.printinfo(); • Person[] person = new Person[3]; • person[0] = new Person("Itchy"); • person[1] = new Person("Scratchy"); • person[2] = new Person("Kati"); • person[0].setName("Itch"); • person[1].setName("Scratch"); • person[2].setName("Kat"); • for(int i=0; i < 3; i++) • { • System.out.println("person[" + i + "] = " + person[i].getName()); • } • } • }//end of class Person Array of Objects Without these, a NullPointerException will be thrown!

  8. Care should be taken to parenthesize expressions where more than one operator is being used.

  9. System.out.println( "Hello" + "World" ); String str1; if( str1 instanceof String ){...} 256 >> 2 is 64 (arithmetic) right shift -256 >> 3 is -32 sign bit copied, and uses 2's complement -256 >>> 3 is 536870880 (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 ); Operator Examples Checks an object’s inheritance + 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++) See Shift.java

  10. Looping Mechanisms 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(); } } > java Loops 0 1 2 0 2 4 1 2 3 4 5 2 4 6 8 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 > for loop while loop do while loop break statement can only be used in a loop! continue statement label e.g. Stop: Jump to next iteration of the loop as pointed to by mylabel See Loops.java

  11. Remember break statement! public class Branches{ public static void main( String args[] ) { Reader reader = new InputStreamReader(System.in); BufferedReader input = new BufferedReader(reader); System.out.println(">"); int i = Integer.parseInt(input.readLine()); 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; } } } Branch Control if( ){ }else{ } as in C/C++ switch (works on any discrete type such as short, int, byte or char ) Example results: > java Branches > 7 i <= 10 i == 7 i >= 6 See Branches.java

  12. Looping Mechanisms: Extra Features Labeledbreak statement Break statement that jumps to the statement that follows the labeled statement. Useful for breaking out of nested switch statements Typically, you would use this to break out from nested loops, or nested switch statements. Labeledcontinue statement Terminate the current iteration and continue with the next iteration of the loop to which the label refers. continue statement can only be used in a loop! (but not in a switch) A labeled continue statement can cause control to be passed to the next iteration of an outer enclosing loop in a nested loop situation. See LabeledBreak.java & LabeledContinue.java

  13. Looping Mechanisms: Extra Features Labeledbreak statement in a nested switch statements class Switch2 { //define the controlling class public static void main(String[] args){ //main method outerSwitch: switch(5){//labeled outer switch statement case 5: //execute the following switch statement //Note that the code for this case is not followed by // break. Therefore, except for the labeled break at // case 1, execution would fall through the case 6 and // the default as demonstrated in the program named // switch2. However, the use of the labeled break // causes control to break all the way out of the // labeled switch bypassing case 6 and the default. switch(1){ //inner switch statement case 1: System.out.println( "Match and break from here"); break outerSwitch; //break with label case 2: System.out.println( "No match for this constant"); break; }//end inner switch statement case 6: System.out.println( "Case 6 in outer switch"); default: System.out.println("Default in outer switch"); }//end outer switch statement System.out.println("Beyond switch statements"); }//end main }//End switch2 class. Example results: > java Switch2 Match and break from here Beyond switch statements See Switch2.java

  14. Looping Mechanisms: For each Loop (since product version 5.0) The for-each construct is applicable to Collections as well as arrays, where it hides the index variable rather than the iterator. The following method returns the sum of the values in an int array: // Returns the sum of the elements of a int sum(int[] a) { int result = 0; for (int i : a) { result += i; } return result; }

  15. Referencedata type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. public class Point{ ... public static void swapPoints(Point p1, Point p2){ Point temp = p1; p1 = p2; p2 = temp; } } Java uses Pass-by-Value This will fail to swap the points!

  16. Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level. public class Point{ ... public static void swapPoints(Point p1, Point p2){ Point temp = p1; p1.x = p2.x; p1.y = p2.y; p2.x = temp.x; p2.y = temp.y; } Java uses Pass-by-Value this would fail because temp is only a reference to p1, and the next statements will change p1's values

  17. public class Point{ ... public static void swapPoints(Point p1, Point p2){ Point temp = new Point(p1); p1.x = p2.x; p1.y = p2.y; p2.x = temp.x; p2.y = temp.y; } Java uses Pass-by-Value • Reference data type parameters, such as objects, are also passed into methods by value. • This means that when the method returns, the passed-in reference still references the same object as before. • However, the values of the object's fields can be changed in the method, if they have the proper access level. this will now work! Take note that we are calling the class’s copy constructor here. See TestPoint.java

  18. public class Point{ //default constructor public Point(){ x=0; y=0; } ... public static void movePoint(Point p, int deltaX, int deltaY){ p.setX(p.getX() + deltaX); p.setY(p.getY() + deltaY); p = new Point(); } Java uses Pass-by-Value • Reference data type parameters, such as objects, are also passed into methods by value. • This means that when the method returns, the passed-in reference still references the same object as before. • However, the values of the object's fields can be changed in the method, if they have the proper access level. this new operation will not alter the contents of p permanently See TestPoint.java

  19. Java Exceptions An exceptionis an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. Just for completeness… The Error class is used to implement more serious error conditions (most of which are abnormal errors). An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Although it is possible for the user to handle Errors, due to their serious nature it is often advisable to let the program terminate. http://java.sun.com/j2se/1.3/docs/api/java/lang/Error.html

  20. 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. Any exceptions that are able to be thrown by each method are documented in the Java API Documentation. Common exceptions - useful to know about: ArrayIndexOutOfBoundsException ArithmeticException (divide by zero for ints) NullPointerException NegativeArraySizeException SecurityException IOException Thrown when an application attempts to use null in a case where an object is required

  21. 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) > The program crashes because main makes no attempt to catch the exception 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++; } } }

  22. Example results: > java Catch Enter an integer: 12 Value is: 12 > java Catch Enter an integer: abc Input corrupted, using default Value is: 0 > import java.io.*; public class Catch{ public static void main( String args[] ) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; int value = 0; System.out.print("Enter an integer: ");// write out a // prompt line = in.readLine(); // read line of // input 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 the following System.out.println("Value is: " + value ); } } } Catching Exceptions Note: try-catch-finally construct The finally block always executes when the try block exits finally defines a block of code that is always executed even if an unexpected exception occurs

  23. If a thrown exception is not caught, then the program (or thread) will terminate immediately. The runtime system always executes the statements within the finallyblock regardless of what happens within the try block. So it's the perfect place to perform cleanup. finally behaves differently from catch(…) of C++. catch(…) will only run if none of the catch clauses matched the exception thrown. Therefore, the catch(…) clause will not always be executed. http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html

  24. errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; } readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } } Without exception handling, there's so much error detection, reporting, and returning here that the original lines of code are lost in the clutter.

More Related