Presentation is loading. Please wait.

Presentation is loading. Please wait.

Review Session CS2110 Prelim #1.

Similar presentations


Presentation on theme: "Review Session CS2110 Prelim #1."— Presentation transcript:

1 Review Session CS2110 Prelim #1

2 Primitive types vs classes
Java Basics Primitive types vs classes Variable declarations: int i = 5; Animal a = new Animal(“Bob”); How does “==” behave? a name “Bob” i 5

3 Java Basics Default values What value does a field contain when it is declared but not instantiated? Animal a; Object ob; int i; boolean b; char c; double d; //null //null //0 //false //’\0’ (null byte) //0.0 Explain that all Objects (Strings included) have a default value of null, while primitive types have other default values: Note that this is mainly for fields and not local variables (You’ll get a compiler warning if don’t initialize a local variable, and sometimes an error if Java is clever enough)

4 Wrapper Classes (Boxing)
Java Basics Wrapper Classes (Boxing) class Character contains useful methods Examples of useful static Character methods: Character.isDigit(c) IntCharacter.isLetter(c) Autoboxing –should be called autowrapping! Integer x = 100; int y = x; We don’t want to get too much into wrapper classes at this point because it’s a pretty strange concept for people just picking up Java and it’s not very important early on. This is mainly to let them know that primitive types cannot have methods, and each primitive type has a related wrapper class with useful methods Don’t talk about casting between primitives and their wrappers or about equality of wrapped primitives, just treat these classes as if they were a collection of static methods related to the primitives. It can be nice to mention that the method they saw earlier Double.parseDouble(str) comes from the Double wrapper class, and that Integer.parseInt is a similar useful one. Integer.MAX_VALUE and Integer.MIN_VALUE can also be useful.

5 String literals String instantiation:
Java Basics String literals String instantiation: Constructor: String s = new String(“dog”); Literal: String s2 = “dog”; Roughly equivalent, but literal is preferred s “dog” s2 “dog”

6 Strings are immutable Once a String is created, it cannot be changed
Java Basics Strings are immutable Once a String is created, it cannot be changed Methods such as toLowerCase and substring return new Strings, leaving the original one untouched In order to “modify” Strings, you instead construct a new String and then reassign it to the original variable: String name = “Gries”; name = name + “, “; name = name + “David”;

7 Java Basics String catenation Operator + operator is called catenation, or concatenation If one operand is a String and the other isn’t, the other is converted to a String Important case: Use “” + exp to convert exp to a String. Evaluates left to right. Common mistake: System.out.println(“sum: “ ); Prints “sum: 56” System.out.println(“sum: “ + (5 + 6)); Prints “sum: 11”

8 Other String info Always use equals to compare Strings:
Java Basics Other String info Always use equals to compare Strings: str1.equals(str2) Very useful methods: length, substring (overloaded), indexOf, charAt Useful methods: lastIndexOf, contains, compareTo

9 1D Array Review Why is the following illegal?
2D Arrays 1D Array Review Animal[] pets = new Animal[3]; pets.length is 3 pets[0] = new Animal(); pets[0].walk(); pets null null 1 2 Why is the following illegal? pets[1] = new Object(); Explain how variable pets and the referenced value are separate. Explain that the compiler will allow any object to be stored in the array as long as it has the appropriate type. We need to be assured that we can call any methods that belong to Animal with the elements in the array. All elements in the array are of the same type. new Object() won’t fit because it cannot be casted down to Animal.

10 Java arrays do not change size!
2D Arrays Java arrays Java arrays do not change size! b 1 1 2 3 “Cornell” “Cornell” bBig “Ithaca” “Ithaca” String[] b = {“Cornell”, “Ithaca”}; String[] bBig = Arrays.copyOf(b, 4); b = bBig; Explain that Java arrays do not expand. If you would like to add more elements to an array, you need to copy the previous array to the new one. Note that the students do not need to know System.arraycopy or Arrays.copyOf.

11 2D arrays: An array of 1D arrays.
Java only has 1D arrays, whose elements can also be arrays. int[][] b = new int[2][3]; This array has 2 int[] arrays of length 3 each. 1 2 b 1 1 2

12 2D arrays: An array of 1D arrays.
How many rows in b? b.length How many columns in row 0? b[0].length How many columns in row 1? b[1].length 1 2 b 1 1 2

13 2D arrays: An array of 1D arrays.
int[][] b = new int[2][]; The elements of b are of type int[]. b null 1

14 2D arrays: An array of 1D arrays.
int[][] b = new int[2][]; b[0] = new int[] {0,4,1,3,9,3}; b[1] = new int[] {1110,2110,3110}; b is called a ragged array 1 4 b 2 1 1 1110 2110 3110 2 1 3 3 4 9 5 3

15 The superclass of exceptions: Throwable
class Throwable: Superclass of Error and Exception Does the “crashing” Contains the constructors and methods Throwable() Throwable(String) class Error: A very serious problem and should not be handled Example: StackOverflowError class Exception: Reasonable application might want to crash or handle the Exception in some way Like so many things in Java… Exception is just a class! Throwable is the base class that actually fires off a crash in the JVM. When using keyword “throw”, only Throwable instances will work with it. Also, only Throwable instances can be caught. Explain there are two constructors: The second one stores a string, which is a detailed message of what occurred. Instances of Error can be caught but shouldn’t be. There are very serious problems like running out of memory.

16 A Throwable instance: ArithmeticException
Exceptions A Throwable instance: ArithmeticException There are so many exceptions we need to organize them. Throwable detailMessage “/ by zero” Throwable Exception Exception Error RuntimeException RuntimeException ArithmeticException This is just an example of a throwable instance. We have so many different exceptions for different problems that we run into. Field detailMessage is part of the Throwable partition of the ArithmeticException. You can restate that there are two constructors. One that has a String parameter and one that doesn’t. ArithmeticException

17 Bubbling up exceptions
Exceptions will bubble up the call stack and crash the methods that called it. 1 2 3 4 5 6 7 8 9 10 11 12 13 class Ex { void first() { second(); } void second() { third(); void third() { int c = 5/0; AE Method call: first(); AE Console: Exception in thread “main” java.lang.ArithmeticException: at Ex.third(Ex.java:11) at Ex.second(Ex.java:7) at Ex.first(Ex.java:3) AE AE = ArithmeticException

18 Try-catch blocks Console:
Exceptions Try-catch blocks 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Ex { void first() { second(); } void second() { try { System.out.println(“in”); third(); System.out.println(“out”); } catch (Exception e){ System.out.print(“error”); void third() { int c = 5/0; An exception will bubble up the call stack and crash the methods that called it … unless it is caught. catch will handle any exceptions of type Exception (and its subclasses) that happened in the try block Exception Type Console: in What if third had “c = 0/5”? What would be the output? Slowly explain each line of code. Go through the transitions. Explain that when the dangerous code occurs in the try-block, it immediately terminates the try-block. Finally, explain that we gracefully caught the exception and didn’t crash the application (as long as the exception thrown is the exception type or one of its subclasses.) ArithmeticException! error

19 How to write an exception class
Exceptions How to write an exception class /** An instance is an exception */ public class OurException extends Exception { /** Constructor: an instance with message m*/ public OurException(String m) { super(m); } /** Constructor: an instance with default message */ public OurException() { this(“Default message!”);

20 A Little More Geometry! Shape x ____ y ____ Square area() size ____
Abstract Classes A Little More Geometry! Shape x ____ y ____ Square area() size ____ Triangle area() base____ height ____ Circle area() radius ____ Encourage the students to download the code for this online The goal is to incorporate an area method for all shapes x,y are coordinates that are for all shapes. Each subclass has its own relevant fields. Explain that Circle, Square, and Triangle all have different area() methods but Shape does not have one

21 A Partial Solution: Add method area to class Shape:
Abstract Classes A Partial Solution: Add method area to class Shape: public double area() { return 0; } public double area() { throw new RuntimeException(“area not overridden”); } Let’s try to solve the casting problem: Ask for ideas. Solve our earlier problem - makes sumAreas(..) simple and clean, but has its own host of issues: Subclasses of Shape have to remember to override - easy to lose track of, cause bugs down the line Shapes that aren’t subclasses have 0 area, which would normally be incorrect Now add the RuntimeException: Gets even closer. Now we can’t call getArea on Shapes that aren’t subclasses. Still, Subclasses of Shape have to remember to override - easy to lose track of, cause bugs down the line Makes a lot more Runtime Errors - Compile Time are easier to catch and fix

22 Problems not solved Shape s = new Shape(...); Should be disallowed
Abstract Classes Problems not solved What is a Shape that isn’t a Circle, Square, Triangle, etc? What is only a shape, nothing more specific? Shape s = new Shape(...); Should be disallowed 2. What if a subclass doesn’t override area()? Can’t force the subclass to override it! Incorrect value returned or exception thrown.

23 Solution: Abstract classes
public abstract class Shape { public double area() { return 0; } Abstract class Can’t be instantiated. (new Shape() illegal) This solves our first problem - by making Shape abstract, we don’t have to worry about instantiating it. Cannot create an object of class Shape because use of new-expression is illegal. So every Shape is truly a Circle, Square, Triangle, or some other subclass.

24 Solution: Abstract methods
Abstract Classes Solution: Abstract methods public abstract class Shape { public abstract double area(); } Can have implemented methods, too Place abstract method only in abstract class. Semicolon instead of body. Abstract method Subclass must override. This solves the second problem. An abstract method must be overridden in every subclass - not doing so is a compile time error --program us illegal. An abstract method doesn’t have a body - just method header then semicolon.

25 Abstract Classes, Abstract Methods
Cannot instantiate an object of an abstract class. (Cannot use new-expression) A subclass must override abstract methods. (but no multiple inheritance in Java, so…) Why? Java requires this so that the following doesn’t happen. If subclasses didn’t override the abstract method, we could have a situation where the method gets called but it has no implementation to use If we could instantiate an object of an abstract class and tried to call one of the abstract methods, it would have no implementation to use

26 Interfaces public interface Whistler { void whistle();
int MEANING_OF_LIFE= 42; } class Human extends Mammal implements Whistler { methods are automatically public and abstract fields are automatically public, static, and final (i.e. constants) Must implement all methods in the implemented interfaces An interface is like a fully abstract class but has a slightly different syntax. An interface can contain type signatures for methods, just like abstract methods in abstract classes, but they have to be public. An interface can contain fields, but they have to be public, static, and final and they have to contain an initializer. So they are really just constants

27 Multiple interfaces public interface Singer { void singTo(Human h); }
class Human extends Mammal implements Whistler, Singer { Classes can implement several interfaces! They must implement all the methods in those interfaces they implement. Must implement singTo(Human h) and whistle() NOTE If someone asks about conflicting constants in interfaces, Java will actually have an compile-time error due to ambiguity. So you would need to call the constant you want from the interface like Whistler.MEANING_OF_LIFE or Singer.MEANING_OF_LIFE. Similarly for conflicting return types for methods of the same name, java will say that the return type is incompatible with one of the interfaces.

28 Interfaces Solution: Interfaces Interface Whistler offers promised functionality to classes Human and Parrot! Animal Mammal Bird Whistler Human Dog Parrot Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, the class will compile only if all methods defined by that interface are overridden in the class ---are declared in the class.

29 Casting Human h = new Human(); Object o = (Object) h;
Interfaces Casting Human h = new Human(); Object o = (Object) h; Animal a = (Animal) h; Mammal m = (Mammal) h; Singer s = (Singer) h; Whistler w = (Whistler) h; All point to the same memory address! Object Animal Whistler Mammal Singer Human There are six (compiler) perspectives of the same Human object. From each perspective, you can call a method m() (say) only if it is defined in that perspective or above it; otherwise, the call is illegal. This ensures that a method to be called actually exists at runtime. But of course the object does NOT change when one casts.

30 Casting Human h = new Human(); Object o = h; Animal a = h;
Interfaces Casting Human h = new Human(); Object o = h; Animal a = h; Mammal m = h; Singer s = h; Whistler w = h; Object Automatic up-cast Animal Whistler Mammal Singer Forced down-cast Human Note that explicit upcasts are unnecessary. Explicit downcasts are necessary --and they should be done only if it is KNOWN that the cast will work (use instanceof to check that). Note that c instanceof C is true iff c has a partition called C. For the object shown on this slide, h instance of C is true for C being Whistler, Human, Mammal, Singer, Animal, and Object.

31 Casting up to an interface automatically
Interfaces Casting up to an interface automatically class Human … implements Whistler { void listenTo(Whistler w) {...} } Human h = new Human(...); Human h1 = new Human(...); h.listenTo(h1); Parrot p = new Parrot(...); h.listenTo(p); Object Animal Whistler Mammal Arg h1 of the call has type Human. Its value is being stored in w, which is of type Whistler. Java does an upward cast automatically. Same thing for p of type Parrot. Human When h.listenTo(h) or h.listenTo(w) gets called, it calls the listenTo method declared in Human. (“Bottom-up rule”) w.listenTo(w) doesn’t compile because a Whistler object does not have a listenTo method. Whenever we call upon w, the compiler knows that it can call upon the methods that were declared in (the type) Whistler.

32 Shape implements Comparable<T>
Interfaces Shape implements Comparable<T> public class Shape implements Comparable<Shape> { ... /** … */ public int compareTo(Shape s) { double diff= area() - s.area(); return (diff == 0 ? 0 : (diff < 0 ? -1 : +1)); } At this point, in your Demo, change class Shape to implement Comparable<T> as shown on this slide, adding method compareTo and implementing Comparable<Shape>. You should then be able to run method main and show them that the sort works. Note: It would be nice to write compareTo using just: return area() - s.area(); but the expression is a double. And if we try to cast it to an int, using return (int)(area() - s.area()); it doesn’t give the right answer is the area different is between -1 and 1 (non-inclusive).

33 Beauty of interfaces Boolean Byte Double Integer
Arrays.sort sorts an array of any class C, as long as C implements interface Comparable<T> without needing to know any implementation details of the class. Classes that implement Comparable: Boolean Byte Double Integer String BigDecimal BigInteger Calendar Time Timestamp and 100 others Interfaces Beauty of interfaces All 110 very diverse/different classes that implement Comparable just need to use one method! (Arrays.sort) Interfaces stop us from needlessly writing 110 different sort implementations! If YOUR class C (say) implements Comparable, thus providing a method that gives an ordering to objects of the class, you can use Arrays.sort to sort arrays C[].

34 Interfaces String sorting Arrays.sort(Object[] b) sorts an array of any class C, as long as C implements interface Comparable<T>. String implements Comparable, so you can write String[] strings= ...; ... Arrays.sort(strings); During the sorting, when comparing elements, a String’s compareTo function is used Because of interfaces, we need only one sort method, which just relies on compareTo. As long as Arrays.sort can cast elements to type Comparable, it can reliably call method compareTo.

35 Abstract Classes vs. Interfaces
Abstract class represents something Sharing common code between subclasses Interface is what something can do A contract to fulfill Software Engineering purpose Similarities: Can’t instantiate Must implement abstract methods (If you have time) go through the points in the context of the previous examples of Humans/whistlers and shapes. Software Engineering: specify and enforce boundaries between different parts of a team project Because they will have had some exposure to Lists, you can say that if they implement the List<T> interface, it allows a user to have a guarantee that their list implementation will have those List methods. It doesn’t say anything about the implementation (backing array vs. objects and pointers). It just needs to satisfy the specification. Else, there will be a compiler error.

36 Four loopy questions //Precondition Initialization; // invariant: P
Loop Invariants Four loopy questions //Precondition Initialization; // invariant: P while ( B ) { S } 1. Does it start right? Does initialization make invariant P true? 3. Does repetend S make progress toward termination? 4. Does repetend S keep invariant P true? 2. Does it stop right? Does P and !B imply the desired result?

37 Add elements backwards
Loop Invariants Add elements backwards Precondition b ??? h Invariant b ??? s = sum h Postcondition b s = sum

38 Add elements backwards
Loop Invariants Add elements backwards h INV: b ??? s = sum int s = 0; int h = b.length-1; while (h >= 0) { s = s + b[h]; h--; } Does it start right? Does it stop right? Does it keep the invariant true? Does it make progress toward termination? Emphasize that loop invariants have these four components that directly link to the four loopy questions. If you want, give them a mnemonic to remember SSKP like Smart Sharks Kick Pebbles

39 What method calls are legal
Prelim Review What method calls are legal Animal an; … an.m(args); legal ONLY if Java can guarantee that method m exists. How to guarantee? m must be declared in Animal or inherited.

40 Java Summary On the “Resources” tab of the course website
We have selected some useful snippets We recommend going over all the slides

41 Casting among types (int) 3.2 casts double value 3.2 to an int
any number type any number expression byte short int long float double narrow wider must be explicit cast, may truncate may be automatic cast char is a number type: (int) 'V' (char) 86 Unicode representation: 86 'V' Page A-9, inside back cover 41

42 Declaration of class Circle
Multi-line comment starts with /* ends with */ Precede every class with a comment /** An instance (object) represents a circle */ public class Circle { } Put declarations of fields, methods in class body: { … } public: Code everywhere can refer to Circle. Called access modifier Put class declaration in file Circle.java Page B-5

43 Overloading Possible to have two or more methods with same name
/** instance represents a rectangle */ public class Rectangle { private double sideH, sideV; // Horiz, vert side lengths /** Constr: instance with horiz, vert side lengths sh, sv */ public Rectangle(double sh, double sv) { sideH= sh; sideV= sv; } /** Constructor: square with side length s */ public Rectangle(double s) { sideH= s; sideV= s; Lists of parameter types must differ in some way

44 this evaluates to the name of the object in which is appears
Use of this this evaluates to the name of the object in which is appears Memorize this! /** Constr: instance with radius radius*/ public Circle(double radius) { this.radius= radius; } Page B-28

45 /** An instance represents a shape at a point in the plane */
public class Shape { private double x, y; // top-left point of bounding box /** Constructor: a Shape at point (x1, y1) */ public Shape (double x1, double y1) { x= x1; y= y1; } /** return x-coordinate of bounding box*/ public double getX() { return x; /** return y-coordinate of bounding box*/ public double getY() { return y; Class Shape

46 Object: superest class of them all
Class doesn’t explicitly extend another one? It automatically extends class Object. Among other components, Object contains: Constructor: public Object() {} /** return name of object */ public String toString() c.toString() is /** return value of “this object and ob are same”, i.e. of this == ob */ public boolean equals(Object ob) Page C-18

47 Java has 4 kinds of variable
Field: declared non-static. Is in every object of class. Default initial val depends on type, e.g. 0 for int public class Circle { private double radius; private static int t; public Circle(double r) { double r1= r; radius= r1; } Class (static) var: declared static. Only one copy of it. Default initial val depends on type, e.g. 0 for int Parameter: declared in () of method header. Created during call before exec. of method body, discarded when call completed. Initial value is value of corresp. arg of call. Scope: body. Local variable: declared in method body. Created during call before exec. of body, discarded when call completed. No initial value. Scope: from declaration to end of block.

48 Written using generic type
parameter T (you choose name) Basic class Box public class Box<T> { private T object; public void set(T ob) { object = ob; } public T get() { return object; } … Written using generic type public class Box { private Object object; public void set(Object ob) { object = ob; } public Object get() { return object; } … New code Box<Integer> b= new Box<Integer>(); b.set(new Integer(35)); Integer x= b.get(); Replace type Object everywhere by T

49 Linked Lists (These slides are from the class lectures and available on the website as well)

50 Linked Lists Idea: maintain a list (2, 5, 7) like this: 2 a1 a6 v next
null v next h a1 This is a singly linked list To save space we write names like a6 instead of 50

51 Easy to insert a node in the beginning!
2 a1 a6 v next 5 a6 a8 v next 7 a8 null v next h a1 (2, 5, 7) h a3 2 a1 a6 v next 5 a8 7 null 8 (8, 2, 5, 7) 51

52 Easy to remove a node if you have its predecessor!
2 a1 a6 v next 5 a6 a2 v next 8 a2 a8 v next 7 a8 null v next h a1 k a6 (2, 5, 8, 7) h a1 2 a6 v next 5 a8 7 null 8 a2 k (2, 5, 7) 52

53 Recursion

54 Sum the digits in a non-negative integer
/** return sum of digits in n. * Precondition: n >= 0 */ public static int sum(int n) { if (n < 10) return n; // { n has at least two digits } // return first digit + sum of rest return sum(n/10) + n%10 ; } sum calls itself! E.g. sum(7) = 7 E.g. sum(8703) = sum(870) + 3;

55 Stack Frame A “frame” contains information about a method call:
local variables parameters return info At runtime, Java maintains a stack that contains frames for all method calls that are being executed but have not completed. Method call: push a frame for call on stack, assign argument values to parameters, execute method body. Use the frame for the call to reference local variables, parameters. End of method call: pop its frame from the stack; if it is a function, leave the return value on top of stack.

56 (some) things to know for the prelim
Can you list the steps in evaluating a new-expression? Can you do them yourself on a piece of paper? Can you list the steps in executing a method call? Can you do them yourself on a piece of paper? Do you understand exception handling? E.g. What happens after a catch block has been executed? Can you write a recursive method or understand a given one? Abstract class and interfaces ArrayList, interface Comparable Loops invariants


Download ppt "Review Session CS2110 Prelim #1."

Similar presentations


Ads by Google