1 159.234LECTURE 159.234 LECTURE JAVA 24 Variables, Arrays, Operators, Expressions, Flow Control,...
-
Upload
abigayle-daniels -
Category
Documents
-
view
225 -
download
0
Transcript of 1 159.234LECTURE 159.234 LECTURE JAVA 24 Variables, Arrays, Operators, Expressions, Flow Control,...
1
159.234159.234 LECTURE LECTURE
JAVAJAVA
2424
Variables, Arrays, Operators, Expressions, Flow Control, Parameter Passing,
Exceptions
2
• Variable Scope, Lifetime and Initialisation
• Operator Precedence
• Branching Statements
• Looping Statements
• Java Strings
• Java Parameter Passing
Java Expressions & Flow ControlJava Expressions & Flow Control
3
VariablesVariablesScope, Initialization & LifetimeScope, 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.
VariablesVariablesScope, Initialization & LifetimeScope, Initialization & Lifetime
5
• However, there is no equivalent of the C++ delete
• The System Garbage Collector in the JVM automatically removes objects from the heap when they are no longer in scope and when system resources become low.
ObjectsObjects
e.g.:MyClass c = new MyClass();float xa[] = new float[100];
ObjectsObjects in Java can be created on the heap using new.
6
• Arrays can be declared of any type: fundamental or classchar 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 keywordfirstName = 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] = newnew Person();
people[1] = newnew 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!
10
Precedence Java Operator Operands Associativity Description
1 ++
--
+ -
~
!
(type)
Arithmetic
Arithmetic
Arithmetic
Integral
Boolean
Any
Right
Right
Right
Right
Right
Right
Unary pre/post decrement
Unary pre/post decrement
Unary plus and minus
Unary bitwise complement
Unary logical complement
cast
2 * / % Arithmetic Left Multiplication, division and remainder
3 + -
+
Arithmetic
String
Left
Left
Addition and subtraction
String concatenation
4 <<
>>
>>>>>>
Integral
Integral
Integral
Left
Left
Left
Left shift
Right shift with sign extension
Right shift with zero extension
5 < <=
> >=
instanceof
Arithmetic
Arithmetic
Object, type
Left
Left
Left
Less than, less than or equal
Greater than, greater than or equal
Type comparison
6 ==
!=
==
!=
Primitive
Primitive
Object
Object
Left
Left
Left
Left
Equality test (value)
Inequality test (value)
Equality (refer to the same object)
Inequality (refer to different objects)
7 &
&
Integral
Boolean
Left
Left
Bitwise AND
Boolean AND
8 ^
^
Integral
Boolean
Left
Left
Bitwise XOR
Boolean XOR
9 |
|
Integral
Boolean
Left
Left
Bitwise OR
Boolean OR
10 && Boolean Left Conditional AND
11 | | Boolean Left Conditional OR
12 ? : Boolean, any, any Right Conditional ternary
13 =
*= /= %/ += -= <<= >>= >>>= &= ^= |=
Variable, any
Variable, any
Right
Right
Assignment
Assignment with operation
Care should be taken to parenthesize expressions parenthesize expressions where more than one operator is being used.
11
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 );
+ 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++)
Operator ExamplesOperator Examples
Checks an object’s inheritance
See Shift.java
13
Looping MechanismsLooping Mechanisms
See Loops.java
for loop
while loop
do while loop
break statement
continue statement
label
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 Loops0 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 >
Jump to next iteration of the loop as pointed to by
mylabel
can only be usedin a loop!
e.g. Stop:
14
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 ControlBranch Controlif( ){ }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
15
Looping Mechanisms: Looping Mechanisms: Extra FeaturesExtra Features
See LabeledBreak.java & LabeledContinue.java
Labeled breakbreak statement
continue statement
Typically, you would use this to break out from nested loops, or nested switch statements.
can only be used in a loop! (but not in a switch)
Labeled continuecontinue statement Terminate the current iteration and continue with the next iteration of the loop to which the label refers.
Break statement that jumps to the statement that follows the labeled statement.
A labeled continue statement can cause control to be passed to the next iteration of an outer enclosing loop in a nested loop situation.
Useful for breaking out of nested switch statements
16
Looping Mechanisms: Looping Mechanisms: Extra FeaturesExtra Features
See Switch2.java
Labeled breakbreak 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
17
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:
Looping Mechanisms: Looping Mechanisms: For each Loop For each Loop (since product version 5.0)
// Returns the sum of the elements of a int sum(int[] a) { int result = 0; for (int i : a) { result += i; } return result; }
18
• ReferenceReference 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.
public class Point{... public static void swapPoints(Point p1, Point p2){
Point temp = p1;p1 = p2;p2 = temp;
}}
Java uses Pass-by-ValueJava uses Pass-by-Value
This will fail to swap the points!
19
• 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-ValueJava uses Pass-by-Value
this would fail because temp is only a reference
to p1, and the next statements will change
p1's values
20
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-ValueJava uses Pass-by-Value
this will now work!Take note that we are
calling the class’s copy constructor here.
See TestPoint.java
• 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.
21
public class Point{
//default constructorpublic 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-ValueJava uses Pass-by-Value
this new operation will not alter the contents of
p permanently
See TestPoint.java
• 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.
22
Java ExceptionsJava Exceptions
An exceptionexception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
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
Just for completeness…
23
• 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 throwsthrows 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
24
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++;
}
}
}
25
Catching ExceptionsCatching ExceptionsExample 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 IOExceptionthrows 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 ); } }}
Note: try-catch-finally construct
finally defines a block of code that is always executed
even if an unexpected exception occurs
The finally block always executes when the try block exits
26
The runtime system always executes the statements within the finallyfinally block regardless of what happens within the try block. So it's the perfect place to perform cleanup.
http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html
finally 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.
If a thrown exception is not caught, then the program (or thread) will terminate immediately.
27
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.