review quick reference

64
Review Quick reference Announcement

Upload: indiya

Post on 27-Jan-2016

45 views

Category:

Documents


1 download

DESCRIPTION

Review Quick reference. Chapter 1: Basics. Methods usually go after the data. Data usually goes first in a class. Class. class Car { String Make; int MaxSpeed ; public brake() { System.out.println (“Stop!"); } } A class: data fields (properties) + methods (behavior). - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Review Quick reference

Review

Quick reference

Announcement

Page 2: Review Quick reference

Chapter 1: Basics

Page 3: Review Quick reference

class Car { String Make; int MaxSpeed; public brake() { System.out.println(“Stop!"); }

}

A class: data fields (properties) + methods (behavior)

Class Definition

Methods usually go after the data

Class

Data usually goes first in a class

Page 4: Review Quick reference

Class is a template for creating instances

How to create instances of a class?

Class

ClassName instanceName = new ClassName(intialInputParam);

Car c1= new Car();

c1.make = “Honda”;

Car c2= new Car();

c2.make = “Ford”;

Page 5: Review Quick reference

Groups related classes in the same category How to declare a class is part of a package?

Unique name Hierarchal

Packages

package packagename;

package RacingGamePackage;

package book.chapter1;

Page 6: Review Quick reference

Many packages in Java API javax.swing java.lang java.util …

How to use a package?

Packages

import packagename;

import book.chapter1.Welcome;

import book.chapter1.*;

Only “Welcome” class is imported.

All classes in chapter1 imported.

Page 7: Review Quick reference

3 types of comments in JavaLine comment //

Example // This is a line comment!

Paragraph comment /* */Example

/* This is a paragraph comment.

It includes multiple lines. */ JavaDoc comments (automatic

documentation) /** */

Comments

Page 8: Review Quick reference

What is the output?

Q

public class Test{

public static void main(String[] args) {

System.out.println(“3.5 * 2 / 2 – 2.5 is ");

System.out.println(3.5 * 2 / 2 – 2.5);

}

}

>3.5 * 2 / 2 – 2.5 is

>1.0

Page 9: Review Quick reference

Chapter 2: More Basics

Page 10: Review Quick reference

1. Create a Scanner object

Scanner input = new Scanner(System.in);

2. Use one of the methods below

Input

Method You will get

next() String

nextByte() byte

nextShort() short

nextInt() int

nextLong() long

nextFloat() float

nextDouble() double

nextBoolean() boolean

Page 11: Review Quick reference

A variable stores your data int x = 10;

Identifier Name of your variable

letters, digits, underscores (_), and dollar signs ($)

Cannot start with a digit Cannot be a reserved word

Variable

X

23

Variable

Identifier

Literal

Page 12: Review Quick reference

Value is constant, doesn’t changeUse “final” keyword to declare a value

as constant

Constants

final datatype CONSTANTNAME = VALUE;Example:

final double PI = 3.14159; final int SIZE = 3;

Page 13: Review Quick reference

Shortcut operators for assignment

Shortcut Operators

Operator Example Equivalent

+= i += 8 i = i + 8

-= f -= 8.0 f = f - 8.0

*= i *= 8 i = i * 8

/= i /= 8 i = i / 8

%= i %= 8 i = i % 8

Page 14: Review Quick reference

Increment, decrement operators

++/--

Operator Name Description

++var pre-increment The expression (++var) increments var by 1 and evaluates

to the new value in var after the increment.var++ post-increment The expression (var++) evaluates to the

original value in var and increments var by 1.

--var pre-decrement The expression (--var) decrements var by 1 and evaluates

to the new value in var after the decrement. var-- post-decrement The expression (var--) evaluates to the

original value in var and decrements var by 1.

Page 15: Review Quick reference

Implicit casting (type widening)

A small number fits easily in a large variable

Explicit casting (type narrowing)

A large number (3.9, double) cannot be fit in a smaller variable (int), so fraction part is truncated.

You need to explicitly cast your number.

Conversions

double d = 3;

int i = (int)3.9;

byte, short, int, long, float, double

range increases

Page 16: Review Quick reference

Example

>b>c

Q

public class Test{

public static void main(String[] args) {

char x = ‘a’;

char y = ‘c’;

System.out.println(++x);

System.out.println(y++);

}

}

Page 17: Review Quick reference

Chapter 3: Selections

Page 18: Review Quick reference

Example

Two-way if

if (radius >= 0) { area = radius * radius * 3.14159; System.out.println("The area is: “ + area);}else { System.out.println("Negative input");}

Page 19: Review Quick reference

else if is used for checking multiple conditions

Multiple if-else

if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';

if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';

Page 20: Review Quick reference

What if we need more complex conditions composed of “and/or/..”?

Logical Operators

Operator Name

! not

&& and

|| OR

^ Exclusive OR

Page 21: Review Quick reference

Tax Program

Switch Statement

switch (status) { case 0: //compute taxes for single filers; break; case 1: //compute taxes for married file jointly; break; case 2: //compute taxes for married file separately; break; case 3: //compute taxes for head of household; break; default: System.out.println("Errors: invalid status");}

Page 22: Review Quick reference

Conditional statement as(boolean-expression) ? expression1 : expression2

Conditional Statement

if (x > 0) y = 1else y = -1;

y = (x > 0) ? 1 : -1;

Page 23: Review Quick reference

%s s stands for a string

%f stands for floating point number

System.out.printf("%s, %s", "Hello", "World!"); Output: “Hello, World!”

System.out.printf(“%.1f pounds” ,28.8968); Output: “28.8 pounds”

Formatting Output

Page 24: Review Quick reference

Format specifiers in more detail

Formatting Specifier

% flag width .precision type

Tells the compiler to expect a specifier …

A flag (such as - to left justify)

Minimum number of characters to show

Maximum number of digits after decimal point

Data type (e.g. %f)

Page 25: Review Quick reference

Formatting Output

Specifier Output Example

%b a boolean value true or false

%c a character 'a'

%d a decimal integer 200

%f a floating-point number 45.460000

%e a number in scientific notation 4.556000e+01

%s a string "Java is cool"

Page 26: Review Quick reference

What is the output?

> amount is 32.3200

>□□java

>

Q

System.out.printf(“amount is %5.4f” ,32.32);

System.out.printf(“%6s \n” ,”java”);

Page 27: Review Quick reference

Chapter 4: Loops

Page 28: Review Quick reference

1. If the condition is true, the statement is executed; then the condition is evaluated again …

2. The statement is executed over and over until the condition becomes false.

3. When the loop finishes, control passes to the next instruction in the program, following the closing curly brace of the loop.

while Loop

while(condition){ statement;}

Page 29: Review Quick reference

The body of a while loop must eventually make the condition false

If not, it is an infinite loop, which will execute until the user interrupts the program!

Caution!

int count = 1;

while (count > 0)

{

System.out.println("Welcome to Java!");

count++;

}

Page 30: Review Quick reference

Will be executed at least once

do while

do {

// Loop body;

Statement(s);

} while (loop-condition);

Loop Continuation Condition?

true

Statement(s) (loop body)

false

Page 31: Review Quick reference

for loop

int count = 0;

while (count < 10)

{

System.out.println("Welcome to Java!");

count++;

}

for(int count =0; count < 10; count ++)

{

System.out.println("Welcome to Java!");

}

Page 32: Review Quick reference

Some recommendations1. Use the most intuitive loop2. If number of repetitions known for3. If number of repetitions unknown

while4. If should be executed at least once

(before testing the condition) do-while

Which Loop?

Page 33: Review Quick reference

break causes the loop to be abandoned, and execution continues following the closing curly brace.

break

while ( i > 0 ) { .... if ( j == .... ) break; // abandon the loop ….} // end of the loop body

break will bring you here

Page 34: Review Quick reference

continue causes the rest of the current round of the loop to be skipped. "while" or "do" loop moves directly to

the next condition test of the loop. "for" loop moves to the “action-after-

each-iteration” expression, and then to the condition test.

continue

Page 35: Review Quick reference

How many times count++ will be executed?

Q

int count = 0;

while (count < 10)

count++;10

int count= 0;

for (int i=0; i<= 10; i++)

count++;

11

int count = 5;

while (count < 10)

count++;5

int count = 5;

while (count < 10)

count += 3;2

Page 36: Review Quick reference

Poll resultsLook up your class sectionTest credit card #

Announcement

Page 37: Review Quick reference

Chapter 5: Methods

Page 38: Review Quick reference

A method

Method

public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

modifier outputname

input

Methodbody

Page 39: Review Quick reference

First, a method should be definedThen we can use the method

i.e. calling or invoking a method

Invoking a Method

public static void main(String[] args) { int total1 = sum(1, 10); int total2= sum(20, 30); int total3 = sum(35, 45); int total4 = sum(35,1000);}

Page 40: Review Quick reference

When calling a method within the same class, we directly call the method

Invoking a Method

public class TestClass{ public static void main(String[] args) { int total1 = sum(1, 10);}//----------------------------------------------public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

}

calling directly

Page 41: Review Quick reference

When calling a method from another class, use class name if a static method

Invoking a Method

public class TestClass{ public static void main(String[] args) { int total1 = AnotherClass .sum(1, 10); }

}Class name

public class AnotherClass{ public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

}

Page 42: Review Quick reference

When calling a method from another class, use class name if a static method

Invoking a Method

public class TestClass{ public static void main(String[] args) { AnotherClass a = new AnotherClass(); int total1 = a.sum(1, 10); }

}Instance name

public class AnotherClass{ public int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

}

Page 43: Review Quick reference

How memory is managed?

Memory

Space required for

main method:

k:i:5j:2

Space required for

main method:

k:i:5j:2

Space required for

main method:

k:i:5j:2

Space required for

main method:

k: 5i:5j:2

Stackis empty

Space required for

maxmethod:

x:5y:2

Space required for

maxmethod:

Result: 5x:5y:2

Page 44: Review Quick reference

What about reference types? E.g. Random r = new Random();

Pass by Reference

Space required for main method:

r(reference)

Stack MemoryHeap Memory

Actual Object

Space required for

testmethod:

x

Page 45: Review Quick reference

Method overload is only based on input arguments

Method overload can not be based on different output values

Method overload cannot be based on different modifiers

Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match.

This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error.

Method Overload

Page 46: Review Quick reference

Scope: Part of the program where the variable

can be referenced.A local variable:

A variable defined inside a method. The scope of a local variable starts from

its declaration and continues to the end of the block that contains the variable.

Variable Scope

Page 47: Review Quick reference

Class level Scope: Accessible to all methods of that class

Variable Scope

public class Test{ int x; //data field: accesible to all methods

public int method1() { //do something ...}

public int method2() { //do something ...}

}

Page 48: Review Quick reference

Method level Scope:

Variable Scope

public int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

Page 49: Review Quick reference

Block level Scope:

Variable Scope

public int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) { int k = -1; sum = k + i; }

return sum;}

Page 50: Review Quick reference

Which statements are incorrect?

Q

public int sum() { int sum = i; for(int i = 0; i <= 10; i++) { sum += j; for (int j = 0; j <= 10; j+=k) { int k = -1; sum = i + j; } } return sum;}

Page 51: Review Quick reference

Chapter 6: 1D Arrays

Page 52: Review Quick reference

Array is a data structure that represents a collection of the same type of data.

Array is a reference type

Array

23

45

53

16

32

8

91

int[] myList = new int[7];

0x675

myList(memory location of

the actual array)

Array element at

index 6

Value of element at

index 6

Page 53: Review Quick reference

Once an array is created, its size is fixed.

i.e. it cannot be changed! You can find the size of an array using

For example

This returns 7.

Length of Array

arrayRefVar.length

int length = myList.length;

Page 54: Review Quick reference

Each element of array is an indexed variable:

Example (accessing first element)

Indexed Variables

arrayRefVar[index];

myList[0];

Page 55: Review Quick reference

Individual initialization

Populate Array

double[] myList = new double[4];

myList[0] = 1.9;

myList[1] = 2.9;

myList[2] = 3.4;

myList[3] = 3.5;

Page 56: Review Quick reference

Shorthand initialization

This shorthand syntax must be in one statement.

Splitting it would cause a syntax error!

Populate Array

double[] myList = {1.9, 2.9, 3.4, 3.5};

Page 57: Review Quick reference

JDK 1.5 introduced a new for loop that enables you to traverse the complete array sequentially without using an index variable.

For example, the following code displays all elements in the array myList:

for-each

for (double value: myList) System.out.println(value);

for (elementType value:arrayRefVar) …

Page 58: Review Quick reference

Arrays are reference type, so be careful!

After assignment, both lists will point to the same memory location.

Array Copy

list2 = list1;

Contents of list1

list1

Contents of list2

list2

Before the assignment list2 = list1;

Contents of list1

list1

Contents of list2

list2

After the assignment list2 = list1;

Garbage

Page 59: Review Quick reference

To copy the contents (and not the reference), you can use a loop:

Array Copy

int[] sourceArray = {2, 3, 1, 5, 10};int[] targetArray = new int[sourceArray.length];

for (int i = 0; i < sourceArrays.length; i++) targetArray[i] = sourceArray[i];

Page 60: Review Quick reference

To copy the contents (and not the reference), you can also use the arrayCopy utility:

Example

Array Copy

System.arraycopy(source, srcPos, target, tarPos, length);

int[] sourceArray = {2, 3, 1, 5, 10};int[] targetArray = new int[sourceArray.length];

System.arraycopy(sourceArray, 0, targetArray, 0,sourceArray.length);

Page 61: Review Quick reference

Two ways to pass an array to a method

Passing Array

public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) System.out.print(array[i] + " ");}

int[] list = {3, 1, 2, 6, 4, 2};printArray(list);

printArray(new int[]{3, 1, 2, 6, 4, 2});

Anonymous Array

Page 62: Review Quick reference

Two Java uses pass by value to pass arguments to a method.

There are important differences between passing a value of variables of primitive data types and passing arrays.

Passing Values

23

45

53

16

32

8

int[] y = new int[7];

y

int x = 10;

10

x

Page 63: Review Quick reference

Returning an array

Return Array

public static int[] reverse(int[] list) { int[] result = new int[list.length];  for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; }  return result;}

int[] list1 = new int[]{1, 2, 3, 4, 5, 6};int[] list2 = reverse(list1);

Page 64: Review Quick reference

Does the following statement resize the array?

Q

int[] myList;myList = new int[10];myList = new int[20];

myList new int[10] Array

myList new int[10] Array

new int[20] Array