Top Banner
Review Session Ryan Ly (slides by Jai Madhok) Email: [email protected]
28
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Review SessionRyan Ly (slides by Jai Madhok)

Email: [email protected]

Page 2: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Key Concepts

Identifiers- What are they?Rules to determine invalid vs. valid

identifiers Cannot be a reserved word No spaces in between No symbols other than the ‘$’ and ‘_’ Cannot begin with a digit

Page 3: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Data Types

3 kinds of primitive data typesType conversion between data types

Implicit vs. explicit type conversionThe ‘Cast’ operator:

Syntax: (dataType) expressionWhat happens when an operator has

mixed operands?

Page 4: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Strings

A String is an ‘Object’ In Java, they are enclosed in double quotes What is a null string? Empty string? How does indexing work? Predefined methods:

substring(startIndex, stopIndex) charAt(index) indexOf(ch) length() replace() toLowerCase(), toUpperCase()

Page 5: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Named Constants

Use the keyword final Identifier should be in all Capital Letters Memory location whose content is not

allowed to change during program execution Ex: final int CENTS_PER_DOLLAR= 100; Several advantages:

Prevent typos▪ If you mistype the name of the constant, the compiler will

warn you as compared to typing in a wrong value which the compiler will blindly accept

Easy to modify the program in the future Good programming practice

Page 6: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Input Statements

To put data into variables from an input device, we first create an input stream object and associate it with a standard input deviceScanner scan= new Scanner(System.in);

More about Scanner: next() nextInt() nextDouble() nextLine()

How do we read in a single character using a Scanner object?

Know how to use these!

Page 7: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Tokenizing & Parsing

Sometimes we read in input in the form of a string and then want to extract numeric data from it

How do we do this? Tokenize and Parse Syntax:

StringTokenizer t= new StringTokenizer(str, delim) Say we want an integer:

int a= Integer.parseInt(t.nextToken()) Other method: Double.parseDouble()

Note: Parsing and type casting are different things

Page 8: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

File Handling

A file is defined as an area in secondary storage used to hold information

Scanner scan= new Scanner(new FileReader(filename1));

PrintWriter oFile= new PrintWriter(filename2);

Warning: Closing the file you are writing to is more important than you think it is

Use same methods for reading and writing/formatting files as you have been for user input/output

Page 9: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Formatting Output With printf Syntax:

System.out.printf(formatString, argumentList) formatString: string specifying the format argumentList: list of arguments containing

constant values, variables, or expressions, separated by comma

Example:System.out.printf(“There are %.2f inches in %d

centimeters \n”, cm/2.54, cm) Where cm is a variable of the type int.

Note: You can also use the DecimalFormat class to format your decimal output. Take your pick!

Page 10: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

More Fun With Strings

compareTo() Compare Strings character by character until a

mismatch is found What does this method return? What is the basis for deciding what a mismatch

is and what it isn’t?

equals() Case sensitive method How to solve the case sensitivity issue? What does the method return?

Page 11: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Operators- Order of Precedence() . []Unary Operators: negation, casting, not (!), ++,

-- Arithmetic Operators I: * / %Arithmetic Operators II: + -Comparison Operators: < <= > >= Equivalence Operators: == != Logical AND: &&Logical OR: ||Ternary Operator: ?:Assignment Operators: = += -= *= /= %=

Page 12: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Control Structures

Provide alternatives to sequential program execution and are used to alter flow of execution

Alternatives are: Selection – if, if/else, switch/case Repetition – for, while, do-while

Page 13: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

While Loops

Using loop control variables Counter controlled while loops Sentinel controlled while loops Flag controlled while loops

EOF controlled while loops Do-while loops are different

from a generic while Run body then check condition to

decide whether to loop

T

F

Page 14: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

for (initial statement; loop condition; update statement)

KNOW THIS LOOP COLD!

Initial Statement

Loop Conditio

n Statements

Update Statement

T

F

Page 15: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Exit early from a loopSkip the remaining cases in a switch

case constructDon’t try and use them at random

places to make your code work, most of the time it won’t.

Page 16: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

java.util – Scanner, StringTokenizer java.io – BufferedReader, FileReader,

PrintWriter java.text – DecimalFormat java.lang – String, Math

Don’t need to import

Page 17: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Reading flow in java:a = a + 2;

‘A’ in ASCII is 65ASCII is a subset of UnicodeEscape sequencesCompound operators Increment/Decrement operators,

pre/post

Page 18: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Documentation Reading

Read up some common methods of the following classes for use in the assignments and exams: String Scanner Math StringTokenizer Character

Page 19: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

True/FalseMultiple ChoiceCode TracingCode CompletionFinding ErrorsOther random kinds of questions like

matching exercises are a possibility

Page 20: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Exam Tips

Read through all questions carefully Write answers legibly Show all work for partial credit Do not spend too much time on any

one problem if it is causing trouble, come back to it later on

Read through the chapter summaries in the text book and all of Dr. S’s class notes

Good Luck!

Page 21: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

?

Page 22: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

char let=‘A’;for (int i=1; i<=3; i++){ for(int j=i; j<5; j++) System.out.print(let); System.out.println(); let+=1;}

Predict the output [6 points]Difficulty: Medium

Page 23: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

int n1=6, n2=10;if(n1 >= n2/2) {if(true && false)

System.out.print(“one”); }else

System.out.print(“two”);System.out.print(“three”);

Predict the output [3 points]Difficulty: Easy

Page 24: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

int num=6;while(num<16) {

switch(num%4) {case 1: System.out.println(“one”); break;case 2: System.out.println(“two”); case 3: System.out.println(“three”); break;case 0: System.out.println(“multiple”);}

num+=3;}

Predict the output [4-6 points]Difficulty: Medium

Page 25: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

boolean a=true, b=false;if (a && (true|| !b) )

if( b || (!a && false) )System.out.println(“happy”);

else System.out.println(“ halloween”);System.out.println(“goblins”);

Predict the output [6 points]Difficulty: Medium

Page 26: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Sample Code Tracing #5

double a = 1.6;int b = 13;double c = (int) a * 2 + 1;for (; b > 0; b-=3){

b /= c; // legal b/c equivalent to b = (int) (b/c);System.out.println(b);System.out.println(++b * 0.5 + b--);

}

Predict the output [9 points]Difficulty: Hard

Page 27: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Sample Error Finding #1

String s = “hello world”;String space = s.indexOf(“ “);

String pt2 = s.substring(space,s.length); System.out.println(pt2);

Find the error [3 points]Difficulty: Easy

Page 28: Review Session Ryan Ly (slides by Jai Madhok) Email: rly1@jhu.edu.

Sample Error Finding #2

int a, b=10;

do {if (b = 10)

a = 1.5; b = 10;else if ((b-1)%2>5))

a = 3;System.println(“a is ” + a “ and b is ” + b);

} while (a != 5)

Find the 8 errors [16 points]Difficulty: 5 Medium, 3 Hard