Download int - UF CISE

Document related concepts
no text concepts found
Transcript
Announcement
 Review
 Quick
reference
Chapter 1: Basics
Class Definition
Data usually goes first in a class
class Car {
String Make;
int
MaxSpeed;
public brake()
{
System.out.println(“Stop!");
}
Class
Methods usually
go after the data
}
A
class: data fields (properties) + methods (behavior)
Class
 Class
is a template for creating instances
 How
to create instances of a class?
ClassName instanceName = new ClassName(intialInputParam);
Car c1= new Car();
c1.make = “Honda”;
Car c2= new Car();
c2.make = “Ford”;
Packages
 Groups
related classes in the same category
 How to declare a class is part of a package?
package packagename;
package RacingGamePackage;
 Unique
name
 Hierarchal
package book.chapter1;
Packages
 Many




packages in Java API
javax.swing
java.lang
java.util
…
 How
to use a package?
import packagename;
import book.chapter1.Welcome;
Only “Welcome”
class is imported.
import book.chapter1.*;
All classes in
chapter1
imported.
Comments

3 types of comments in Java
Line
comment //
Example

// This is a line comment!
Paragraph
comment /* */
Example

/* This is a paragraph comment.
It includes multiple lines. */

JavaDoc comments (automatic
documentation) /** */
Q

What is the output?
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
Input
1.
Create a Scanner object
Scanner input = new Scanner(System.in);
2.
Use one of the methods below
Method
You will get
next()
String
nextByte()
byte
nextShort()
short
nextInt()
int
nextLong()
long
nextFloat()
float
nextDouble()
double
nextBoolean()
boolean
Variable
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
Identifier
Variable
X
23
Literal
Constants
 Value
is constant, doesn’t change
 Use “final” keyword to declare a value as
constant
final datatype CONSTANTNAME = VALUE;
Example:
final double PI = 3.14159;
final int SIZE = 3;
Shortcut Operators
 Shortcut
operators for assignment
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
and evaluates
The expression (++var) increments var by 1
var++
--var
var--
post-increment
original value
pre-decrement
and evaluates
decrement.
post-decrement
original value
to the new value in var after the increment.
The expression (var++) evaluates to the
in var and increments var by 1.
The expression (--var) decrements var by 1
to the new value in var after the
The expression (var--) evaluates to the
in var and decrements var by 1.
Conversions

Implicit casting (type widening)
double d = 3;


A small number fits easily in a large variable
Explicit casting (type narrowing)
int i = (int)3.9;


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.
range increases
byte, short, int, long, float, double
Q

Example
public class Test{
public static void main(String[] args) {
char x = ‘a’;
char y = ‘c’;
System.out.println(++x);
System.out.println(y++);
}
}
>b
>c
Chapter 3: Selections
Two-way if
 Example
if (radius >= 0) {
area = radius * radius * 3.14159;
System.out.println("The area is: “ + area);
}
else {
System.out.println("Negative input");
}
Multiple if-else
 else
if is used for checking multiple
conditions
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';
Logical Operators
 What
if we need more complex conditions
composed of “and/or/..”?
Operator
Name
!
not
&&
and
||
OR
^
Exclusive OR
Switch Statement
 Tax
Program
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
 Conditional
statement as
(boolean-expression) ? expression1 : expression2
if (x > 0)
y=1
else
y = -1;
y = (x > 0) ? 1 : -1;
Formatting Output
 %s
 s stands for a string
 %f
 stands for floating point number
 System.out.printf("%s,
 Output:
%s", "Hello", "World!");
“Hello, World!”
 System.out.printf(“%.1f
 Output:
“28.8 pounds”
pounds” ,28.8968);
Formatting Specifier
 Format
%
Tells the
compiler to
expect a
specifier …
specifiers in more detail
flag
width
.precision
A flag (such
as - to left
justify)
Minimum
number of
characters
to show
type
Maximum
number of
digits after
decimal point
Data type (e.g.
%f)
Formatting Output
Specifier
Output
Example
%b
a boolean value
%c
a character
'a'
%d
a decimal integer
200
%f
a floating-point number
45.460000
%e
a number
4.556000e+01
%s
a string
in scientific notation
true or false
"Java is cool"
Q
 What
is the output?
System.out.printf(“amount is %5.4f” ,32.32);
> amount is 32.3200
System.out.printf(“%6s \n” ,”java”);
>□□java
>
Chapter 4: Loops
while Loop
while(condition)
{
statement;
}
1.
2.
3.
If the condition is true, the statement is
executed; then the condition is evaluated
again …
The statement is executed over and over
until the condition becomes false.
When the loop finishes, control passes to
the next instruction in the program,
following the closing curly brace of the loop.
Caution!
 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!
int count = 1;
while (count > 0)
{
System.out.println("Welcome to Java!");
count++;
}
do while

Will be executed at least once
do {
Statement(s)
(loop body)
// Loop body;
Statement(s);
} while (loop-condition);
true
Loop
Continuation
Condition?
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!");
}
Which Loop?

Some recommendations
1.
2.
3.
4.
Use the most intuitive loop
If number of repetitions known for
If number of repetitions unknown  while
If should be executed at least once (before
testing the condition)  do-while
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.
 continue
 "while"
or "do" loop moves directly to the
next condition test of the loop.
 "for" loop moves to the “action-after-eachiteration” expression, and then to the condition
test.
Q
 How
many times count++ will be executed?
int count = 0;
int count= 0;
while (count < 10)
for (int i=0; i<= 10; i++)
count++;
count++;
10
11
int count = 5;
int count = 5;
while (count < 10)
while (count < 10)
count++;
count += 3;
5
2
Announcement
 Poll
results
 Look up your class section
 Test credit card #
Chapter 5: Methods
Method
A
method
modifier
Method
body
output
name
input
public static int sum(int x, int y)
{
int sum = 0;
for (int i = x; i <= y; i++)
sum += i;
return sum;
}
Invoking a Method
 First,
a method should be defined
 Then we can use the method
 i.e.
calling or 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);
}
Invoking a Method
 When
calling a method within the same class, we
directly call the 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
Invoking a Method
 When
calling a method from another class, use class
name if a static method
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;
}
}
public class TestClass{
public static void main(String[] args) {
int total1 = AnotherClass .sum(1, 10);
}
}
Class
name
Invoking a Method
 When
calling a method from another class, use class
name if a static method
public class AnotherClass{
public int sum(int x, int y)
{
int sum = 0;
for (int i = x; i <= y; i++)
sum += i;
return sum;
}
}
public class TestClass{
public static void main(String[] args) {
AnotherClass a = new AnotherClass();
int total1 = a.sum(1, 10);
}
}
Instance
name
Memory
 How
Space
required for
main
method:
k:
i:5
j:2
memory is managed?
Space
required for
max
method:
x:5
y:2
Space
required for
max
method:
Result: 5
x:5
y:2
Space
required for
main
method:
k:
i:5
j:2
Space
required for
main
method:
k:
i:5
j:2
Space
required for
main
method:
k: 5
i:5
j:2
Stack
is empty
Pass by Reference
 What

about reference types?
E.g. Random r = new Random();
Space
required for
test
method:
x
Actual Object
…
Space
required
for main
method:
r
(reference)
Stack Memory
Heap Memory
Method Overload
 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.
Variable Scope
 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
public class Test{
int x; //data field: accesible to all methods
public int method1()
{ //do something ...}
public int method2()
{ //do something ...}
}
Variable Scope
 Method
level Scope:
public int sum(int x, int y)
{
int sum = 0;
for (int i = x; i <= y; i++)
sum += i;
return sum;
}
Variable Scope
 Block
level 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;
Q
 Which
statements are incorrect?
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
 Array
is a data structure that represents a
collection of the same type of data.
 Array
is a reference type
int[] myList = new int[7];
0x675
myList
(memory location of
the actual array)
23
45
53
16
32
Array
element at
index 6
8
91
Value of
element at
index 6
Length of Array

Once an array is created, its size is fixed.


i.e. it cannot be changed!
You can find the size of an array using
arrayRefVar.length

For example
int length = myList.length;

This returns 7.
Indexed Variables

Each element of array is an
indexed variable:
arrayRefVar[index];

Example (accessing first element)
myList[0];
Populate Array

Individual initialization
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
Populate Array

Shorthand initialization
double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand syntax must be in
one statement.

Splitting it would cause a syntax
error!
for-each

JDK 1.5 introduced a new for loop that
enables you to traverse the complete array
sequentially without using an index variable.
for (elementType value:arrayRefVar)
…

For example, the following code displays all
elements in the array myList:
for (double value: myList)
System.out.println(value);
Array Copy

Arrays are reference type, so be careful!
list2 = list1;

After assignment, both lists will point to the
same memory location.
Before the assignment
list2 = list1;
list1
After the assignment
list2 = list1;
Contents
of list1
list2
list1
Contents
of list1
list2
Contents
of list2
Garbage
Contents
of list2
Array Copy

To copy the contents (and not the reference),
you can use a loop:
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];
Array Copy

To copy the contents (and not the reference),
you can also use the arrayCopy utility:
System.arraycopy(source, srcPos, target, tarPos, length);

Example
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];
System.arraycopy(sourceArray, 0, targetArray,
0,sourceArray.length);
Passing Array

Two ways to pass an array to a method
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
Passing Values


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.
int x = 10;
int[] y = new int[7];
23
10
x
y
45
53
16
32
8
Return Array
Returning
an 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);
Q

Does the following statement
resize the array?
int[] myList;
myList = new int[10];
myList = new int[20];
myList
new int[10]
Array
myList
new int[10]
Array
new int[20]
Array