1 java review outline java primitives, program structure operators, control flow, loops classes and...

26
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList • Files Most of these slides are based on “Intro to OOP with Java” text book by C. Thomas

Upload: dorthy-johnson

Post on 04-Jan-2016

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

1

Java Review

Outline

• Java Primitives, Program Structure• Operators, Control Flow, Loops• Classes and Objects• Arrays and ArrayList• Files

Most of these slides are based on “Intro to OOP with Java” text book by C. Thomas Wu

Page 2: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

2

Java Translation

• The Java compiler translates Java source code into a special representation called bytecode in the .class file

• Java bytecode is not the machine language for any specific CPU

• Another software tool, called an interpreter (in our case the Java Virtual Machine), executes the bytecode

• Java is considered to be architecture-neutral

• The Java compiler is not tied to any particular machine

Page 3: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

3

Program Structure

public class MyProgram

{

}

// comments about the class

public static void main (String[] args)

{

}

// comments about the method

method headermethod body

Page 4: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

4

Arithmetic Operators

Intro to OOP with Java, C. Thomas Wu

Page 5: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

5

Operator Precedence Rules

Page 6: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

6

if ( testScore < 70 )

System.out.println("You did not pass");

else

System.out.println("You did pass");

Syntax for the if Statement

if ( <boolean expression> )

<then block>

else

<else block>

Then BlockThen Block

Else BlockElse Block

Boolean ExpressionBoolean Expression

Indentation is important!

Can be visualized as a flowchart

Page 7: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

7

Comparing Objects

String str1 = new String("Java");String str2 = new String("Java");

if (str1 == str2) {System.out.println("They are equal");

} else {System.out.println("They are not equal");

}

Sol : They are not equal

Discussion of some string methods

With primitive data types, we have only one way to compare them, but with objects (reference data type), we have two ways to compare them.

We can test whether two variables point to the same object (use ==), orWe can test whether two distinct objects have the same contents.

Page 8: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

8

Syntax for the switch Statement

switch ( gradeLevel ) {

case 1: System.out.print("Go to the Gymnasium");

break;

case 2: System.out.print("Go to the Science Auditorium");

break;

case 3: System.out.print("Go to Harris Hall Rm A3");

break;

case 4: System.out.print("Go to Bolt Hall Rm 101");

break;

}

switch ( <arithmetic expression> ) {

<case label 1> : <case body 1>

<case label n> : <case body n>

}

Case Body

Case Body

Arithmetic ExpressionArithmetic Expression

Case Label

Case Label

Page 9: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

9

while ( number <= 100 ) {

sum = sum + number;

number = number + 1;

}

Syntax for the while Statement

while ( <boolean expression> )

<statement>

Statement(loop body)

Statement(loop body)

Boolean ExpressionBoolean Expression

Page 10: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

10

String inputStr;

int age;

// Create a Scanner object to read input.

Scanner keyboard = new Scanner(System.in);

keyboard.useDelimiter(System.getProperty("line.separator"));

System.out.println(“Please enter your age (between 0 and 130):");

age = Integer.parseInt(keyboard.nextLine());

while (age < 0 || age > 130) {

System.out.println("An invalid age was entered. Please try again.");

age = Integer.parseInt(keyboard.nextLine());

}

Example: Testing Input Data

Page 11: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

11

do {

sum += number;

number++;

} while ( sum <= 1000000 );

Syntax for the do-while Statement

do

<statement>

while ( <boolean expression> ) ;

Statement(loop body)

Statement(loop body)

Boolean ExpressionBoolean Expression

Page 12: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

12

for ( i = 0 ; i < 20 ; i++ ) {

number = scanner.nextInt();

sum += number;

}

Syntax for the for Statement

for ( <initialization>; <boolean expression>; <increment> )

<statement>

1) Initialization

1) Initialization

2) Boolean Expression

2) Boolean Expression

4) Increment and back to 2)

4) Increment and back to 2)

3) (loop body)

3) (loop body)

Page 13: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

13

Defining a Class

class {

}

Import StatementsImport Statements

Class CommentClass Comment

Class NameClass Name

Data MembersData Members

Methods(incl. Constructor)

Methods(incl. Constructor)

Page 14: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

14

Creating a Package

• The following steps illustrate the process of creating a package name company that includes the Employee class.1. Include the statement

package company; as the first statement of the source file for the Employee class.2. The class declaration must include the visibility modifier public as

public class Employee { ...}

3. Create a folder named company, the same name as the package name. In Java, the package must have a one-to-one correspondence with the folder.

4. Place the modified Employee class into the company folder and compile it.

5. Modify the CLASSPATH environment variable to include the folder that contains the company folder.

6. Include the statement import company.* in the driver class : EmployeePayRaise

Page 15: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

15

Arrays of Primitive Data Types

• What is an Array? Why do we need them?• Array Declaration

<data type> [ ] <variable> //variation 1<data type> <variable>[ ] //variation 2

• Array Creation

<variable> = new <data type> [ <size> ]

• Example

double[ ] rainfall;

rainfall

= new double[12];

Variation 1

double rainfall [ ];

rainfall

= new double[12];

Variation 2

An array is like an object!

Page 16: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

16

Array Processing

double[] rainfall = new double[12];

String[] monthName = new String[12];

monthName[0] = "January";

monthName[1] = "February";

double annualAverage, sum = 0.0;

for (int i = 0; i < rainfall.length; i++) {

rainfall[i] = Double.parseDouble(keyboard.nextLine());

sum += rainfall[i];

}

annualAverage = sum / rainfall.length;

The same pattern for the remaining ten months.

The same pattern for the remaining ten months.

Page 17: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

17

Javadoc and Java Style

• General information on javadoc is located at• http://java.sun.com/j2se/javadoc

• Java Style Specifics

• http://geosoft.no/development/javastyle.html

Page 18: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

18

Javadoc (cont’d)

Page 19: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 5 - 19

Lists and Maps

• The java.util standard package contains different types of classes for maintaining a collection of objects.

• These classes are collectively referred to as the Java Collection Framework (JCF).

• JCF includes classes that maintain collections of objects as sets, lists, or maps.

• A Java interface defines only the behavior of objects – It includes only public methods with no method bodies.– It does not include any data members except public

constants– No instances of a Java interface can be created

Page 20: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 5 - 20

JCF Lists

• JCF includes the List interface that supports methods to maintain a collection of objects as a linear list

L = (l0, l1, l2, . . . , lN)

• We can add to, remove from, and retrieve objects in a given list.

• A list does not have a set limit to the number of objects we can add to it.

Page 21: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 5 - 21

List Methods

• Here are five of the 25 list methods:

boolean add ( Object o )

Adds an object o to the list

void clear ( )

Clears this list, i.e., make the list empty

Object get ( int idx )

Returns the element at position idx

boolean remove ( int idx )

Removes the element at position idx

int size ( )

Returns the number of elements in the list

Page 22: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 5 - 22

Using Lists

•To use a list in a program, we must create an instance of a class that implements the List interface.

•Two classes that implement the List interface:– ArrayList– LinkedList

•The ArrayList class uses an array to manage data.

•The LinkedList class uses a technique called linked-node representation.

Page 23: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 5 - 23

Sample List Usage

• Here's an example of manipulating a list:

ArrayList<BankAccount> accounts

= new ArrayList<BankAccount>();

accounts.add(new BankAccount(1001));

accounts.add(new BankAccount(1015));

accounts.add(new BankAccount(1729));

accounts.add(1, new BankAccount(1008));

accounts.remove(0);

Page 24: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

Files

• Reading Files• Scanner inputStream = null;• Scanner console = new Scanner(System.in);• System.out.print("Input file: ");• String inputFileName = console.next();• inputStream =• new Scanner(new

FileInputStream(inputFileName));• String line = null;• while (inputStream.hasNextLine( ))• {• line = inputStream.nextLine( )• }

24

Page 25: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

Files (cont’d)

• Writing Files• PrintWriter outputStream = null;• System.out.print("Output file: ");• String outputFileName = console.next();• outputStream = new PrintWriter(

new FileOutputStream(outputFileName));• String line = null;• while (inputStream.hasNextLine( ))• {• line = inputStream.nextLine( );• outputStream.println(count + ":" + line);• }

25

Page 26: 1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides

Files (cont’d)

• Make sure to close the file streams when done• inputStream.close( );• outputStream.close( );

26