Review Quick reference

Post on 27-Jan-2016

46 views 1 download

Tags:

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 of Review Quick reference

Review

Quick reference

Announcement

Chapter 1: Basics

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

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”;

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;

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.

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

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

Chapter 2: More Basics

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

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

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;

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

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.

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

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++);

}

}

Chapter 3: Selections

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");}

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';

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

Logical Operators

Operator Name

! not

&& and

|| OR

^ Exclusive OR

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");}

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

Conditional Statement

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

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

%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

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)

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"

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”);

Chapter 4: Loops

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;}

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++;

}

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

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!");

}

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?

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

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

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

Poll resultsLook up your class sectionTest credit card #

Announcement

Chapter 5: Methods

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

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);}

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

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;}

}

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;}

}

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

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

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

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

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 ...}

}

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;}

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;}

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;}

Chapter 6: 1D Arrays

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

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;

Each element of array is an indexed variable:

Example (accessing first element)

Indexed Variables

arrayRefVar[index];

myList[0];

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;

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};

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) …

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

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];

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);

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

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

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);

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