1 review of java basic concepts –names and reserved words –expressions and precedence of...

37
1 Review of Java • Basic Concepts – Names and Reserved Words – Expressions and Precedence of Operators – Flow of Control – conditional statements – Flow of Control – loops – Arrays • Reading: Your CS110 Text/Notes

Upload: charleen-ward

Post on 17-Jan-2016

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

1

Review of Java

• Basic Concepts– Names and Reserved Words– Expressions and Precedence of Operators– Flow of Control – conditional statements– Flow of Control – loops– Arrays

• Reading: Your CS110 Text/Notes

Page 2: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

2

Review of Java

• If you are not completely familiar with this material, please see me. You should not be taking this course!

• Don’t expect that you’ll catch up as we go through the CS210 material. That is not going to work!

Page 3: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

3

Names and Reserved Words

• Names are used for classes and methods:– Classes: Scanner, BingoBall– Methods: next( ), hasNext( )

• Names are used for variables and constants– Variables: i, j, current, currentValue, isOn– Constants: SIZE, MAX_VALUE

• Reserved words are java language identifiers:– Examples: class, return, public, static, int, boolean

Page 4: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

4

Expressions and Precedence

There are three major groups of basic operations in Java:– Arithmetic (+, -, * , /, %, ++, --, ... )– Comparison ( !=, ==, <=, => , < , ...)– Logical ( ||, &&, !)

Arithmetic operators have the highest precedence followed by comparison operators. Logical operators have the least precedence.

Page 5: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

5

Expressions and PrecedenceThe precedence of operators determines the order

of evaluation for expressions. Here is the order precedence of For arithmetic operations from highest to lowest:– Highest: [ ], ( ), ++, --– Next: +(unary), -(unary), ~, !– Next: new, (type)– Next: *, /, %– Next: +(binary), -(binary)– Etc.

Page 6: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

6

Expressions and Precedence

An Expression is a construct made up of operators and method invocations applied on variables and constants.

Each expression has a type.

Examples:

– x+y+3 (x and y are integer variables)

– z/3+y%2 (z is a double and y is an int)

– x<=z && ~(y > 2)

– obj.doIt()

Page 7: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

7

Flow of Control - Selection

• If statements with optional else clauses:if (boolean condition){statement;

} else {statement;

}

• Switch statementsswitch (integer value) {case FIRST_VALUE:

statements;case SECOND_VALUE:

statements;default:

statements;}

Page 8: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

8

Flow of Control - Repetition

• Whilewhile (scan.hasNext()) {

statements; // repeated until false above

}

• Forfor (int i = 0; i < MAX; i++) {

statements; // repeated until false above

}

• Do … whiledo {

statements; // repeated until false below

} while (!done);

Page 9: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

9

Arrays

• Arrays are a group of elements that can be referenced via a name and an index value

• Declaring an array with or w/o initializationint [] digits = new int [10]; ORint [] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

• Setting the value of an element of an arraydigits [0] = 0;

• Using the values of elements of an arrayint sum = digits[2] + digits[4];

Page 10: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

10

Review of Java• Object Oriented Programming Concepts

– Objects and Classes– Encapsulation, Constructors, and Methods– References and Aliases– Interfaces and Inheritance– Class Hierarchies and Polymorphism– Generic Types (ArrayList Class)– Exceptions

• Reading: L&C Appendix B (3rd Ed.) or Chap. 2 (2nd ed.)

Page 11: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

11

Data Types

• Java Primitive types: int, double, boolean, char, byte, …

• Arrays (Array of ints, Array of boolean, …)

Page 12: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

12

Data Types

• Java Primitive types: int, double, boolean, char, byte, …

• Arrays (Array of ints, Array of boolean, …)• To define more complex customized types, we

write our own classes which define the type of the data objects (instances) of that class.

• We define a class by using and combining other types (primitive types, arrays and other defined classes)

Page 13: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

13

Objects and Classes

• Object and class relationship• Class Definitionpublic class ClassName

{

// attributes <=== defines the state of

the objects of this type

(instances of the class)

// methods <=== defines the behavior of the

} objects

• Instantiating Objects using ClassesClassName myClassName = new ClassName();

Page 14: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

14

Class Definitionpublic class Car {

private int speed; <== object attributes or

private Engine engine; instance variables

public int getSpeed() {

return speed;

}

public void drive() {

....

}

}

Page 15: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

15

Encapsulation

• Encapsulation of Attributespublic class ClassName{// constantspublic static final int MAX_SIZE = 20;private static final int DEFAULT_SIZE = 10;

// class variablesprivate static int largestSizeOfAll;

// instance variablesprivate int mySize;

}

Page 16: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

16

Constructors and Methods

• Constructor (ClassName with no return type)public class ClassName

{

public ClassName (parameter list if any)

{

statements;

}

• Method (Method name with a return type)public type methodName(parameter list if any)

{

statements;

}

}

Page 17: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

17

Constructor

• A constructor is a special method that is designed to create an object (initialize an object).

• A constructor is different from a regular method in three ways.

Page 18: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

18

Using References

• Using a class constantif (size <= ClassName.MAX_SIZE)

statement;

• Using a class method (static method)type returnValue = ClassName.methodName(...);

• Using an instance method via a referencetype returnValue = myClassName.methodName(...);

Page 19: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

19

Aliases and Garbage Collection

• Creating an alias of a referenceClassName yourClassName = myClassName;

• Making object eligible for garbage collectionmyClassName = yourClassName = null;

Object of classClassName

myClassName

yourClassName

null

null

Object of classClassName

myClassName

yourClassName“Garbage”

Page 20: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

20

Primitive/Non-primitive Types

int x; x

x = 12; x

String y; y

String y = new String(“ABC”); y

y = null; y

0

12

null

null

“ABC”

“ABC”

Page 21: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

21

Method Overloadingpublic class Car {

....

public void drive() {

int temp = 12; <------------- local attribute (scope?)

....

}

public void drive(int speed) {

....

}

}

-------------------------------------------------------------------------------------

Car ford = new Car(...);

ford.drive(110); this method call binds to ??? instance mthod

Page 22: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

22

Static/non-static var

public class MyClass {

private int objAttr;

....

}

instance variable (object attribute): one copy of attribute for each Object of type MyClass. Each object can access and modify its own copy. An object changing its own attribute will not be seen by other instances.

public class YourClass {

priavate static classAttr;

....

}

static variable (class variable):

there is only one copy of the attribute

which is associated with the class

itself. All Objects of type YourClass

can access and modify this class

variable and changing it in one

object is seen by all other objects.

Page 23: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

23

Static/non-static method

public class MyClass {

public String myMethod() {

....

}

}

instance method or object method is associated with an object of type MyCLass. To call the method:

MyClass mine= new MyClass(...);

String x = mine.myMethod();

public class YourClass {

public static String yourMethod(int y) {

....

}

}

static method is associated with the class itself. To call the method:

String y = YourClass.yourMethod(211);

Page 24: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

24

Interface

• An interface is a collection of constants and abstract methods.

• An abstract method has no code attached to it. It is just composed of the method header.

• A class implements an interface by providing method implementation for each of the abstract methods of the interface.

Page 25: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

25

Interfaces

A class that implements an interfacepublic class ClassName implements InterfaceName

{

. . .

}<<interface>>InterfaceName

ClassName Class must define codefor all methods definedin InterfaceName

Interface defines themethod signature forall required methods

Page 26: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

26

Inheritance

• A class that extends another classpublic class ClassName extends SuperClassName

{

. . .

}

SuperClassName

ClassName SubClass may define codeto override some or all ofthe SuperClass methods

SuperClass defines all the methods for all SubClasses.

Page 27: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

27

Inheritance

• All the public and protected methods of the super-class are accessible by the subclasses, but not the private ones.

• A subclass may have additional methods and instance variables of its own.

• The super-class does not know anything about its subclasses.

• A sub-class may override some or all of the methods of the super-class. (Example)

Page 28: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

28

class/interface/abstarct class

Difference between:– class and abstract class?– abstract class and interface?

Page 29: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

29

Inheritance

• A class that extends an abstract classpublic class ClassName extends SuperClassName

{

. . .

}<<abstract>>

SuperClassName

ClassName SubClass may define code to overridesome or all of the SuperClass methods,but must define code for the signatures

SuperClass defines some of themethods for all SubClasses, but only defines method signaturesfor the rest of the methods

Page 30: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

30

Class Hierarchies and Polymorphism

• An object reference variable may hold as a reference to any compatible type of object

• Compatibility may be via implementing an interface or inheritance from another classClassName a = new ClassName();

InterfaceName b = new ClassName();

SuperClassName c = new ClassName();

• Object behaves as class it was “born as” (i.e. class used with the new operator)

Page 31: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

31

Polymorphism via interfaceinterface Service

public int provide();

ClassService A

Class Service B implements Servicepublic int provide() {

… }

Clas

Class Service A implements Servicepublic int provide() {

… }

Service[] services = new Service[2];services[0] = new ServiceA(...);services[1] = new ServiceB(...);for(int i = 0; i < services.length; i++) { services[i].provide();}

Page 32: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

32

Generic Types

• Collection classes like the ArrayList class can be defined to hold a specific type of object via a generic type designation <T>ArrayList<String> myList = new ArrayList<String>();

• We will use generics often in CS210 with many other types of “collection” classes

Page 33: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

33

Exceptions

• When code encounters a situation that is impossible for it to resolve at that point, it may throw an Exception object, e.g. NameOfException instead of executing its normal return

• If a method may throw an exception, it should indicate that in its method headerpublic void methodName() throws NameOfException

{

if (boolean condition of impossible situation)

throw new NameOfException();

}

Page 34: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

34

Process the Exception

Three options to handle an Exception:– Not handle it at all and let the program

terminate– Handle the exception where it occurs– Handle the exception at another point in the

program (for example the caller of the method or caller of the caller of the method and ... )

Page 35: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

35

Exception Handling

• Code that calls a method that may throw a checked exception must use try-catch or indicate that it throws that exception in its own method headertry{

statements with call to methodName();}catch (NameOfException e) // may be multiple catch clauses{

statements to recover from occurrence of exception}finally // optional finally clause{ statements always performed, e.g. clean up actions}

Page 36: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

36

File Input: Exampleimport java.util.Scanner;import java.io.*;

public class FileDisplay{ public static void main (String [] args)

throws IOException { Scanner scan = new Scanner(System.in); System.out.println("Enter name of file to display"); File file = new File(scan.nextLine()); Scanner fileScan = new Scanner (file); while (fileScan.hasNext()) System.out.println(fileScan.nextLine()); }}

Page 37: 1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control

37

File Output: Exampleimport java.util.Scanner;import java.io.*;

public class FileWrite{ public static void main (String [] args) throws IOException { // Get filename and instantiate File object as before

PrintStream out = new PrintStream(file); while (scan.hasNext()) { String line = scan.nextLine(); if (line.equals("END")) // A sentinel String value break; else out.println(line); } out.close(); }}