Вы находитесь на странице: 1из 54

o

o
o
o
o
o
o
o

(variable declaration) integer floating-point


character boolean
(assignment)

(statement expression)
(calculation evaluation)
(casting)
printf() format()
(Mathematical Functions) Java


Java
public class ClassName {
public static void main(String[] args) {
program statements
}
}

Java ( applet) method main()


ClassName class program statements

2.1 (data and variable)


354 + 45 * 12





(memory) compiler
(address offset)


integer ( 2, 45, 90
) double float (
2.35, 3.00 )

compiler compiler

intro. to Java (FEU.faa)

Java

Java

1. (letter) _ (underscore) $ (dollar
sign)
2.
Java ( operator Java + () () * () / ()
)

taxRate
pricePerUnit
_timeInSecond
$systemClock
unit897
Java Unicode1

text editor code


variable identifier
identifier ()
(keyword reserved word)
Java 2.1
2.1 keyword
abstract
const
assert
continue
boolean
default
break
do
byte
double
case
else
catch
enum
char
extends
class
final

finally
float
for
goto
if
implements
import
instanceof
int

interface
long
native
new
null
package
private
protected
public

return
short
static
strictfp
super
switch
synchronized
this
throw

throws
transient
try
void
volatile
while

2.2 (Data Type)




(datatype) (identifier
variable)

datatype identifier
datatype Java datatype
(primitive datatype) (reference
type) class object
Java primitive datatype 8 4
( 2.2)
1

2 byte ( ASCII 1 byte)

22

intro. to Java (FEU.faa)

Java

1.
2.
3.
4.

(Logical) boolean
(Textual) char
(Integral) byte, short, int, long
(Floating point) double float

2.2 (primitive datatype)


datatype

boolean

byte

short

int

long

float

double

char

(bit)
true false
8
16
32
64
32
64
16

datatype
bit 2.3
datatype
2.3 primitive datatype
datatype

byte
-128 (-27)
short
-32768 (-215)
int
-2147483648 (-231)
long
-9223372036854775808 (-263)
float
-3.4 x 1038
double
-1.7 x 10308

127 (27 - 1)
32767 (215 - 1)
2147483647 (231 - 1)
9223372036854775807 (263 - 1)
3.4 x 1038
1.7 x 10308

2.3
int numberOfBikes;
float taxRate;
double interests, PI;
boolean yesOrNo;
char response;



_ (underscore)
int number_of_bikes;
float tax_rate;
double cum_gpa;
boolean yes_or_no;




letterGrade
gpa cumulativeGPA
2.3.1
(Assignment)

Java

23

intro. to Java (FEU.faa)

2:

1: class TestDefault {
2:
public static void main(String[] args) {
3:
byte bt;
4:
short st;
5:
int in;
6:
long ln;
7:
float ft;
8:
double db;
9:
char ch;
10:
boolean bo;
11:
12:
System.out.println(ch);
13:
System.out.println(bt);
14:
System.out.println(st);
15:
System.out.println(in);
16:
System.out.println(ln);
17:
System.out.println(ft);
18:
System.out.println(db);
19:
System.out.println(bo);
20:
}
21: }

compile error
TestDefault.java:12: variable ch might
System.out.println(ch);
^
TestDefault.java:13: variable bt might
System.out.println(bt);
^
TestDefault.java:14: variable st might
System.out.println(st);
^
TestDefault.java:15: variable in might
System.out.println(in);
^
TestDefault.java:16: variable ln might
System.out.println(ln);
^
TestDefault.java:17: variable ft might
System.out.println(ft);
^
TestDefault.java:18: variable db might
System.out.println(db);
^
TestDefault.java:19: variable bo might
System.out.println(bo);
^
8 errors

not have been initialized


not have been initialized
not have been initialized
not have been initialized
not have been initialized
not have been initialized
not have been initialized
not have been initialized

Java
2
= ( assignment operator)
" (rvalue) =
(lvalue) =" rvalue
2
Java method ( method main() ) local variable
Java member variable reference
variable ( variable class) Java

boolean
char
byte, short, int, long
double, float

24

Java
false
'0'
0
0.0

intro. to Java (FEU.faa)

Java

lvalue
(physical memory)
numberOfBikes = 2;
area = PI * r * r;
taxReturned = calculateTaxReturned(income);

2 = numberOfBikes;
PI * r * r = area;
calculateTaxReturned(income) = taxReturned;


(1)
(2) (standard I/O
channel)

2.3.2





1: /**
2:
Demonstrates variables declaration and initialization
3: */
4:
5: class Variables {
6:
public static void main(String[] args) {
7:
boolean booleanVar = true;
8:
byte byteVar = 0;
9:
byte maxByte = Byte.MAX_VALUE;
10:
byte minByte = Byte.MIN_VALUE;
11:
short shortVar = 0;
12:
short maxShort = Short.MAX_VALUE;
13:
short minShort = Short.MIN_VALUE;
14:
int intVar = 0;
15:
int maxInt = Integer.MAX_VALUE;
16:
int minInt = Integer.MIN_VALUE;
17:
long longVar = 0L;
18:
long maxLong = Long.MAX_VALUE;
19:
long minLong = Long.MIN_VALUE;
20:
float floatVar = 0.0F;
21:
float maxFloat = Float.MAX_VALUE;
22:
float minFloat = Float.MIN_VALUE;
23:
double doubleVar = 0.0D;
24:
double maxDouble = Double.MAX_VALUE;
25:
double minDouble = Double.MIN_VALUE;
26:
char charVar = 'A';
27:
28:
System.out.println("boolean variable: " + booleanVar);
29:
System.out.println("byte variable: " + byteVar);
30:
System.out.println("short variable: " + shortVar);
31:
System.out.println("int variable: " + intVar);
32:
System.out.println("long variable: " + longVar);
33:
System.out.println("float variable: " + floatVar);
34:
System.out.println("double variable: " + doubleVar);
35:
System.out.println("char variable: " + charVar);
36:
37:
System.out.println("Max byte: " + maxByte);
38:
System.out.println("Min byte: " + minByte);
39:
System.out.println("Max short: " + maxShort);
40:
System.out.println("Min short: " + minShort);
41:
System.out.println("Max int: " + maxInt);

25

intro. to Java (FEU.faa)

2:

42:
43:
44:
45:
46:
47:
48:
49:
50: }

System.out.println("Min
System.out.println("Max
System.out.println("Min
System.out.println("Max
System.out.println("Min
System.out.println("Max
System.out.println("Min

int: " + minInt);


long: " + maxLong);
long: " + minLong);
float: " + maxFloat);
float: " + minFloat);
double: " + maxDouble);
double: " + minDouble);

boolean
true char A max
min Java Java
0L
0.0F 0.0D long float
double Java
float double float
Java double
Java
Variables.java
boolean variable: true
byte variable: 0
short variable: 0
int variable: 0
long variable: 0
float variable: 0.0
double variable: 0.0
char variable: A
Max byte: 127
Min byte: -128
Max short: 32767
Min short: -32768
Max int: 2147483647
Min int: -2147483648
Max long: 9223372036854775807
Min long: -9223372036854775808
Max float: 3.4028235E38
Min float: 1.4E-45
Max double: 1.7976931348623157E308
Min double: 4.9E-324

Java (
)
long longVar = 0L;

long longVar;
longVar = 0L;

long longVar; longVar long


longVar = 0L; 0 longVar ( 2-1
Java)
code


double price = 0.0D, tax = 0.7D, returned = 0.0D, interests = 0.0D, principal =
10000.0D;

26

intro. to Java (FEU.faa)

Java

long longVar;

longVar = 0L;

???

long
longVar Java

0
longVar

2-1






(range)
127 byte int

int length = 2, height = 8, width = 4;
double angles = 30.5, distance = 24.50;

, (comma)


int cats = 90, float tax = 0.50; // ERROR mixed-type


double radius;
radius = 2.54;

int one = 1, two = 2, three = one + two;

Java one two


three
compiler three = one + two;
one + two three

2.4 final

PI
Java user
(reserved word) final

27

intro. to Java (FEU.faa)

2:

final

keyboard
1: /**
2:
Demonstrates the use of final keyword
3: */
4:
5: class Final {
6:
public static void main(String[] args) {
7:
final double PI = 3.14;
8:
int radius = 2;
9:
10:
System.out.println("The value of PI is " + Math.PI);
11:
12:
double area = radius * radius * Math.PI;
13:
System.out.println("Area of a circle is " + area);
14:
}
15: }

compile run
The value of PI is 3.14
Area of a circle is 12.56

Final.java PI
FinalWithError.java compiler
1: /**
2:
Changing the value of final keyword
3: */
4:
5: class FinalWithError {
6:
public static void main(String[] args) {
7:
final double PI = 3.14;
8:
int radius = 2;
9:
10:
double area = radius * radius * PI;
11:
System.out.println("Area of a circle is " + area);
12:
13:
PI = 3.142;
14:
area = radius * radius * PI;
15:
System.out.println("Area of a circle is " + area);
16:
}
17: }

compile
FinalWithError.java:13: cannot assign a value to final variable PI
PI = 3.142;
^
1 error

error Java error 13


compile error
error
(
error)
final


149, 600,000 (1.496 x 108)
(electron mass)

28

intro. to Java (FEU.faa)

Java

0.0000000000000000000000000009 (9.0 x 10-28)


(scientific notation)
final double sunDistance = 1.496E8;
final float electronMass = 9.0E-28F;

// 1.496 x 108
// 9.0 x 10-28



27 ()
code (
?)
2.5 (life-time and scope)


(block) {}
1: /**
2:
Showing scope of variables
3: */
4:
5: class Scope {
6:
public static void main(String[] args) {
7:
int x = 5, y = 8;
8:
9:
System.out.print("Value of x is ");
10:
System.out.println(" Value of y is " + y);
11:
//create scope for x and w
12:
{
13:
int x = 45;
14:
int w = 89;
15:
System.out.println("Value of w in brackets is " + x);
16:
System.out.println("Value of y in brackets is " + y);
17:
}
18:
//error w is out of scope
19:
System.out.println("Value of w is " + w);
20:
}
21: }

Scope.java compile
compiler (1) int x main() (2) int w
scope block int x int w
Scope.java:13: x is already defined in main(java.lang.String[])
int x = 45;
^
Scope.java:19: cannot find symbol
symbol : variable w
location: class Scope
System.out.println("Value of w is " + w);
^
2 errors

C++ block
( Scope.java) Java
block block

{
int w = 3;
}
{
int w = 5;
}

29

intro. to Java (FEU.faa)

2:

Java

1: /**
2:
Showing scope of variables
3: */
4:
5: class Scope2 {
6:
static int x = 8, y;
7:
public static void main(String[] args) {
8:
{
9:
int x;
10:
x = 5;
11:
y = x;
12:
System.out.println("Value of y is " + y);
13:
}
14:
y = x;
15:
System.out.println("Value of y is " + y);
16:
}
17: }

Scope2.java compile
Value of y is 5
Value of y is 8

compiler x block
x scope static Java
class variable
y block x y
class variable x

1: /**
2:
Showing scope of variables
3: */
4:
5: class Scope2v1 {
6:
static int x = 8, y;
7:
public static void main(String[] args) {
8:
{
9:
x = 5;
10:
y = x;
11:
System.out.println("Value of y is " + y);
12:
}
13:
y = x;
14:
System.out.println("Value of y is " + y);
15:
}
16: }

Scope2v1.java x
method main()
8 x block x 5
run
Value of y is 5
Value of y is 5

1: /**
2:
Showing scope of variables
3: */
4:
5: class Scope3 {
6:
static int x = 20;
7:
public static void main(String[] args) {
8:
System.out.println("x = " + x);

30

intro. to Java (FEU.faa)

Scope2.java

2:

int x = (x = 12) + 8;
System.out.println("Value of local x is " + x);
}

Scope3.java x scope
class Scope3 scope method main() compile

x = 20
Value of local x is 20

8 x main()
10 x main()

1: /**
2:
Showing scope of variables
3: */
4:
5: class Scope4 {
6:
public static void main(String[] args) {
7:
int x = (x = 12) + 8;
8:
System.out.println("Value of local x is " + x);
9:
}
10: }

Scope4.java Scope3.java
compile run
Scope3.java

1: /**
2:
Showing scope of variables
3: */
4:
5: class Scope6 {
6:
public static void main(String[] args) {
7:
int x = 12, y = x + 8;
8:
System.out.println("Value of local y is " + y);
9:
}
10: }

compile run
Value of local y is 20

x
y


2.6 (statement and expression)


Java (statement) ; (semicolon)

int priceOfBook = 125;


float taxReturn;

31

intro. to Java (FEU.faa)

9:
10:
11:
12: }

;

int

priceOfBook
=
125
;

Java ;
code
code
/* Scope2v1.java - Showing scope of variables* @author faa xumsai*/class
Scope2v1{static int x = 8, y;public static void main(String[] args) { {int x;x =
5;y = x;System.out.println("Value of y is " + y);}y = x; System.out.println("Value
of y is " + y);}}

code
(indentation)

Expression Java

(mathematical evaluation)
(relational evaluation)
operator + (), (), * (), /
() % ()
operator
1: /**
2:
Shows mathematical operators
3: */
4:
5: class OperatorsOnInt {
6:
public static void main(String[] args) {
7:
int i, j, k;
8:
9:
//generate random number between 1 and 10
10:
j = 1 + (int)(Math.random() * 10);
11:
k = 1 + (int)(Math.random() * 10);
12:
System.out.println("j = " + j + " and k = " + k);
13:
14:
//evaluate and display results of math operators
15:
i = j + k; System.out.println("j + k = " + i);
16:
i = j - k; System.out.println("j - k = " + i);
17:
i = j * k; System.out.println("j * k = " + i);
18:
i = j / k; System.out.println("j / k = " + i);
19:
i = j % k; System.out.println("j % k = " + i);
20:
}
21: }



method random() class Math ( Java ) method random()
0 0.9+ 0 1 1 ( n
0.0 <= n < 1.0) 10 1
1 10 i operator
run
j = 5 and k = 2
j + k = 7

32

intro. to Java (FEU.faa)

Java

j
j
j
j

*
/
%

k
k
k
k

=
=
=
=

3
10
2
1

method random() run



Operator
%
integral floating point
i = j % k;

k 2 j 5
( 1) i
int double
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:

/**
Shows mathematical operators
*/
import java.util.Random;
class Operators {
public static void main(String[] args) {
//do the ints
int i, j, k;
//generate random number between 1 and 10
Random rand = new Random();
j = 1 + rand.nextInt(10);
k = 1 + rand.nextInt(10);
System.out.println("j = " + j + " and k = " + k);
//evaluate
i = j + k;
i = j - k;
i = j * k;
i = j / k;
i = j % k;

and display results of math


System.out.println("j + k =
System.out.println("j - k =
System.out.println("j * k =
System.out.println("j / k =
System.out.println("j % k =

operators
" + i);
" + i);
" + i);
" + i);
" + i);

//do the doubles


double v1, v2, v3;
//generate random double between 1.0 and 10.0
v1 = 1.0 + rand.nextDouble() * 9;
v2 = 1.0 + rand.nextDouble() * 9;
System.out.println("v1 = " + v1 + " v2 = " + v2);
v3 = v1 + v2; System.out.println("v1 + v2 = " + v3);
v3 = v1 - v2; System.out.println("v1 - v2 = " + v3);
v3 = v1 * v2; System.out.println("v1 * v2 = " + v3);
v3 = v1 / v2; System.out.println("v1 / v2 = " + v3);
}

j = 7 and k = 6
j + k = 13
j - k = 1
j * k = 42
j / k = 1
j % k = 1
v1 = 3.5279786640632915 v2 = 9.035898448743211
v1 + v2 = 12.563877112806502
v1 - v2 = -5.5079197846799195
v1 * v2 = 31.878456937808643
v1 / v2 = 0.39044027376757345

33

intro. to Java (FEU.faa)

2:

Operators.java operator
i j
(random) method nextInt(max value) method 0
max value max value
1 10 1 method


1: /**
2:
Shows mathematical operators
3: */
4:
5: class Operators1 {
6:
public static void main(String[] args) {
7:
int a, b, c, d, e;
8:
9:
b = 1 + (int)(Math.random() * 10);
10:
c = 1 + (int)(Math.random() * 10);
11:
d = 1 + (int)(Math.random() * 10);
12:
e = 1 + (int)(Math.random() * 10);
13:
14:
System.out.print("b = " + b + " c = " + c);
15:
System.out.println(" d = " + d + " e = " + e);
16:
a = b + c - d;
17:
System.out.println("Value of a is " + a);
18:
a = b * c - d;
19:
System.out.println("Value of a is " + a);
20:
a = b / c * d;
21:
System.out.println("Value of a is " + a);
22:
}
23: }

run
b = 8
Value
Value
Value

c = 2 d
of a is
of a is
of a is

= 6 e = 5
4
10
24

2.7
(precedence)
operator
( )
2.4
2.4 Operator Precedence
Operator
(), [], ., postfix ++, postfix -unary +, unary , prefix ++, prefix -(datatype), new
*, /, %
+, <<, >>, >>>
<, <=, >, >=, instanceof
==, !=
&
^
|
&&

34

intro. to Java (FEU.faa)

Java

||
?:
=, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, |=, ^=

2.7.1 integer
integer

operator
statement
50 * 2 45 / 5

91 2 50 5 45

50 2 100 9


50 * (2 45) / 5

50 * -43 / 5
-430
integer
4 9 2.25
integer Java 2

5/2=2
125 / 4 = 31
3/9=0
15 / 15 = 1
operator %

5%2=1
125 % 4 = 1
3%9=3
15 % 15 = 0

integer
Java double float
(
double float )


(vat) price rate

double price = 120.0, rate = 7.5;

35

intro. to Java (FEU.faa)

2:

Java

integer
1: /**
2:
Integer calculation
3: */
4:
5: class IntegerCal {
6:
public static void main(String[] args) {
7:
//declares and initialize three variables
8:
int studentNumber = 40;
9:
int teacherNumber = 30;
10:
int totalNumber = 0;
11:
12:
totalNumber = studentNumber + teacherNumber;
13:
14:
//display result
15:
System.out.print(studentNumber + " students + " + teacherNumber);
16:
System.out.println(" teachers = " + totalNumber + " people");
17:
18:
System.out.println("30 + 45 = " + 30 + 45);
19:
}
20: }

Integer.java
(studentNumber) (teacherNumber)
totalNumber = studentNumber + teacherNumber;

Java
studentNumber teacherNumber
totalNumber = (assignment operator) 2-2

teacherNumber

studentNumber

40

totalNumber

30

70

2-2 integer

System.out.print()
System.out.println()
System.out.print(studentNumber + " students + " + teacherNumber);

studentNumber string "student +"


teacherNumber
System.out.println(" teachers = " + totalNumber + " people");

36

intro. to Java (FEU.faa)

double vat = price * rate;

string " teachers = " totalNumber


string " people"
( cursor )
40 students + 30 teachers = 70 people

"" Java +
(System.out) " "
Java

System.out.println("30 + 45 = " + (30 + 45));

"30 + 45 = " (30 + 45)


75
30 + 45 = 75
30 45 Java
30 + 45 = 3045
Java
System.out System.out


total = total + value;

value

total

total

value

2-3


total += value;

+=
() operator
2.5

37

intro. to Java (FEU.faa)

2:

2.5 operator

sum = sum + count;


sum = sum - count;
sum = sum * count;
sum = sum / count;
sum = sum % count;

sum += count;
sum -= count;
sum *= count;
sum /= count;
sum %= count;

total += 4;
sum += 1;

operator

count = count + 1;
value -= 1;


operator ++ operator --
count++;
value--;

++
-
postfix (postfix notation) operator
Java

total += 2;


total -= 3;

Java Operator

int count = 8, value = 5;
count = count + value++;

value count
value
count + value value++
Java value count
value execute count = count + value++
13 value 6

count = count + ++value;

14 ()

38

intro. to Java (FEU.faa)

Java

++ Java value
count 14
prefix (prefix notation)
prefix postfix Java
loop
(repetition)
prefix postfix
int count = 10, value = 5;
count--;
value++;
value = ++count + ++value;

execute value = ++count + --value; value 17


count 9 value 6 ( count value++)

code
value = (++count) + (++value);

value = (count += 1) + (value += 1);

value = (count = count + 1) + (value = value + 1);

(?)
value =

(count++) + (value++);

count = 10 value = 5
postfix ++ Java count
10 value 5 value
value 15 count value
count 11 value 16
run value = 15 count = 11 ?

value = 5;
value = value++;

run value = 5 Java postfix


operator ++
run
int sum = value++;

sum 5 value 6 postfix


operator ++
(
value = value + 1 )
++

39

intro. to Java (FEU.faa)

2:

operator ++
operator
1: /**
2:
Shows increment operators
3: */
4: class Increments {
5:
public static void main(String[] args) {
6:
int value = 25, number = 25;
7:
8:
System.out.println("value is " + value);
9:
System.out.println("number is " + number);
10:
--value;
11:
number++;
12:
System.out.println("value is " + value);
13:
System.out.println("number is " + number);
14:
value = value + --number;
15:
System.out.println("value is " + value);
16:
System.out.println("number is " + number);
17:
number = number - value++;
18:
System.out.println("value is " + value);
19:
System.out.println("number is " + number);
20:
number--;
21:
value++;
22:
System.out.println("value is " + value);
23:
System.out.println("number is " + number);
24:
value = --value;
25:
number = number++;
26:
System.out.println("value is " + value);
27:
System.out.println("number is " + number);
28:
}
29: }

run
value is 25
number is 25
value is 24
number is 26
value is 49
number is 25
value is 50
number is -24
value is 51
number is -25
value is 50
number is -25

operator increment (++ --)


operator
operator expression

operator
code

2.7.2 integer (short byte)


byte short Java
int short byte
int (ByteShort.java)
1: /**
2:
Shows byte and short integer calculation
3: */
4: class ByteShort {

40

intro. to Java (FEU.faa)

Java

5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16: }

public static void main(String[] args) {


short numScooters = 10;
short numChoppers = 5;
short total = 0;
total = numScooters + numChoppers;
System.out.println("Number of scooters is " + numScooters);
System.out.println("Number of choppers is " + numChoppers);
System.out.println("Total number of bikes is " + total);
}

compile Java error


ByteShort.java:10: possible loss of precision
found
: int
required: short
total = numScooters + numChoppers;
^
1 error

integer 64 bit total


16 bit compiler
int casting
2.7.3 (casting)

cast
cast
ByteShort.java Java compile
total = numScooters + numChoppers;
total = (short)(numScooters + numChoppers);

Java compile run


Number of scooters is 10
Number of choppers is 5
Total number of bikes is 15

numScooters 32767
compile run
short numScooters = 32767; //
short numChoppers = 5;


Number of scooters is 32767
Number of choppers is 5
Total number of bikes is -32764

total -32764 32772


?
short 32767
total
Java (
bit 64 bit 32 bit)

41

intro. to Java (FEU.faa)

2:

cast

cast Casting.java
1: /**
2:
Changing type of data
3: */
4:
5: class Casting {
6:
public static void main(String[] args) {
7:
byte byteVar = 127;
8:
short shortVar = 32767;
9:
long longVar = 100000;
10:
int intVar = 300000;
11:
12:
System.out.println("byteVar is " + byteVar);
13:
System.out.println("shortVar is " + shortVar);
14:
System.out.println("longVar is " + longVar);
15:
System.out.println("intVar is " + intVar);
16:
17:
byteVar = (byte)shortVar;
18:
shortVar = (short)longVar;
19:
longVar = (int)intVar * (int)longVar;
20:
intVar = (short)intVar * (short)intVar;
21:
22:
System.out.println("byteVar is " + byteVar);
23:
System.out.println("shortVar is " + shortVar);
24:
System.out.println("longVar is " + longVar);
25:
System.out.println("intVar is " + intVar);
26:
}
27: }

run
byteVar is 127
shortVar is 32767
longVar is 100000
intVar is 300000
byteVar is -1
shortVar is -31072
longVar is -64771072
intVar is 766182400

long ( long L
) long
long value = 125;
long price = 200L;
int total = 0;
total = value * price;

value long price


integer
o
o

long L
bit 64 bit
int bit
32 bit

integer
o

42

int 0 Java
error exception

intro. to Java (FEU.faa)

Java

o
o

error Java
exception

% 0 error 0

2.8 (Floating Point Calculations)


integer
operator + - * /
1: /**
2:
Calculating with floating-point numbers
3: */
4: class FloatingPoint {
5:
public static void main(String[] args) {
6:
double weeklyPay = 1075 * 5;//1075 per day
7:
double extras = 1580;
8:
final double TAX_RATE = 8.5;//tax rate in percent
9:
10:
//calculate tax and income
11:
double tax = (weeklyPay + extras) * TAX_RATE / 100;
12:
double totalIncome = (weeklyPay + extras) - tax;
13:
14:
System.out.println("Tax = " + tax);
15:
System.out.println("Total income = " + totalIncome);
16:
}
17: }

FloatingPoint.java
1075 1580 8.5%
execute
Tax = 591.175
Total income = 6363.825

double tax = (weeklyPay + extras) * TAX_RATE / 100;



? code
1: /**
2:
Calculating floating-point with formatted output
3: */
4:
5: import java.text.*;
//for NumberFormat
6:
7: class FloatingPoint2 {
8:
public static void main(String[] args) {
9:
double weeklyPay = 1075 * 5;//1075 per day
10:
double extras = 1580;
11:
final double TAX_RATE = 8.5;//tax rate in percent
12:
13:
//set format output
14:
NumberFormat form = NumberFormat.getNumberInstance();
15:
form.setMaximumFractionDigits(2);
16:
17:
//calculate tax and income
18:
double tax = (weeklyPay + extras) * TAX_RATE / 100;
19:
double totalIncome = (weeklyPay + extras) - tax;
20:
21:
System.out.println("Tax = " + form.format(tax));
22:
System.out.println("Total income = " +
form.format(totalIncome));
23:
}

43

intro. to Java (FEU.faa)

2:

Java

NumberFormat form = NumberFormat.getNumberInstance();


form.setMaximumFractionDigits(2);

form.format(tax) form.format(totalIncome)

Tax = 591.18
Total income = 6,363.82

591.175 591.18 6363.825 6363.82


totalIncome , (comma)
method getNumbereInstance() setMaximumFractionDigits()
import class NumberFormat
method
method class DecimalFormat format
, (comma) ?
(FloatingPoint3.java)
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:

/**
Calculating floating-point with formatted output
*/
import java.text.*;

//for DecimalFormat

class FloatingPoint3 {
public static void main(String[] args) {
double weeklyPay = 1075 * 5;//1075 per day
double extras = 1580;
final double TAX_RATE = 8.5;//tax rate in percent
//set format output
DecimalFormat form = new DecimalFormat("#.00");
//calculate tax and income
double tax = (weeklyPay + extras) * TAX_RATE / 100;
double totalIncome = (weeklyPay + extras) - tax;
System.out.println("Tax = " + form.format(tax));
System.out.println("Total income = " + form.format(totalIncome));
}
}

Tax = 591.18
Total income = 6363.82

class DecimalFormat NumberFormat format

DecimalFormat form = new DecimalFormat("#.00);

, (comma)
Java 1.5
printf()

44

intro. to Java (FEU.faa)

24: }

2:

Java 1.5 printf()



1: /**
2:
Using printf() for formatted output
3: */
4:
5: class UsingPrintf {
6:
public static void main(String[] args) {
7:
double weeklyPay = 1075 * 5;//1075 per day
8:
double extras = 1580;
9:
final double TAX_RATE = 8.5;//tax rate in percent
10:
String total = "Total income = ";
11:
12:
//calculate tax and income
13:
double tax = (weeklyPay + extras) * TAX_RATE / 100;
14:
double totalIncome = (weeklyPay + extras) - tax;
15:
16:
System.out.printf("Tax = %.2f%n", tax);
17:
System.out.printf("%s %.2f", total, totalIncome);
18:
}
19: }

16 printf()
'%.2f'
'f' %n
" "
','
17 String
16 %s String
','
" "
2.8.1.1 (flag) printf()
(
)
1.
2.
3.
4.
5.

(-)
(+)
(0)
comma (,)
(

1: /**
2:
Using flags in printf()
3: */
4:
5: class FlagInPrintf {
6:
public static void main(String[] args) {
7:
8:
System.out.println("column:\t01234567890123456789");
9:
System.out.printf("\t%+d %d %n", 1234, 1234);
10:
System.out.printf("\t%-10.2f%n", 1234.567);
11:
System.out.printf("\t%+09d%n", 493);
12:
System.out.printf("\t%09d%n", 493);
13:
System.out.printf("\t%,d%n", 123456);
14:
System.out.printf("\t%,.2f%n", 1234.567);
15:
System.out.printf("\t%(d%n", -1234);
16:
System.out.printf("\t%(.1e%n", -493.0);
17:
}
18: }

45

intro. to Java (FEU.faa)

2.8.1 printf()


column:

01234567890123456789
+1234 1234
1234.57
+00000493
000000493
123,456
1,234.57
(1234)
(4.9e+02)

(column
flag
)
2.8.2 format() printf()
format() printf() code
16 17 UsingPrintf

System.out.format("Tax = %.2f%n", tax);


System.out.format("%s %.2f", total, totalIncome);


Tax = 591.18
Total income =

6363.83


2.6
2.6

%%
% String
%a, %A


%b, %B

%c, %C

%d

%e, %E

exponential notation
%f


%g, %G


%h, %H
(hash code)
%n

%o

%s, %S
String
%t, %T

%x, %X

2.8.3 System

System
out.println() out.printf() Java
1.5 import static import import

1: /**
2:
Display output without 'System'

46

intro. to Java (FEU.faa)

Java

3: */
4:
5: import static java.lang.System.out;
6:
7: class StaticImport {
8:
public static void main(String[] args) {
9:
String name = "Jennie Xumsai";
10:
int age = 9;
11:
12:
out.printf("%s is %s%n", name, age);
13:
14:
long maxLong = Long.MAX_VALUE;
15:
double maxDouble = Double.MAX_VALUE;
16:
out.printf("Maximum long: %d%n", maxLong);
17:
out.printf("Maximum double: %E%n", maxDouble);
18:
}
19: }

import static 5 Java


Java 'static field' 'out' method printf()
12, 16 17 'System'

Jennie Xumsai is 9
Maximum long: 9223372036854775807
Maximum double: 1.797693E+308

static import

2.9 (Mixed Type Calculations)


Java

integer

1: /**
2:
Demonstrates mixed-type calculations
3: */
4:
5: class FloatingPoint4 {
6:
public static void main(String[] args) {
7:
double hourlyPay = 85.50D;
//85.50 per hour
8:
int hoursPerDay = 8;
//8 hours per day
9:
int numberOfDays = 5;
//total days worked
10:
int extraHoursWorked = 15;
//overtime hours
11:
final double TAX_RATE = 8.5D; //tax rate in percent
12:
13:
//calculate weekly pay
14:
double weeklyPay = hourlyPay * hoursPerDay * numberOfDays;
15:
//calculate extra pay
16:
double extras = extraHoursWorked * (hourlyPay + (hourlyPay / 2.0));
17:
//calculate tax
18:
double tax = (weeklyPay + extras) * TAX_RATE / 100;
19:
//calculate total income
20:
double totalIncome = (weeklyPay + extras) - tax;
21:
22:
System.out.printf("Income before tax = %.2f%n", (weeklyPay + extras));
23:
System.out.printf("Tax = %.2f%n", tax);
24:
System.out.printf("Income after tax = %.4f%n", totalIncome);
25:
}
26: }

FloatingPoint4.java double integer


hoursPerDay, numberOfDays

47

intro. to Java (FEU.faa)

2:

extraHoursWorked integer hourlyPay, weeklyPay, extras, tax


totalIncome double
Java int double

Income before tax = 5343.75
Tax = 454.22
Income after tax = 4889.5313

()
o
o
o

double double

float float

long long



1: /**
2:
Demonstrates mixed-type calculations
3: */
4:
5: class MixedTypes {
6:
public static void main(String[] args) {
7:
double result = 0.0;
8:
int one = 1, two = 2;
9:
10:
result = 1.5D + one / two;
11:
12:
System.out.printf("Result is %.2f%n", result);
13:
}
14: }

2.0 Java 1.5

result = 1.5 + one / two;

one two int


int 0 Java 0 double
1.5 cast one double

1: /**
2:
Demonstrates mixed-type calculations
3: */
4:
5: class MixedTypes {
6:
public static void main(String[] args) {
7:
double result = 0.0;
8:
int one = 1, two = 2;
9:
10:
result = 1.5D + (double)one / two;
11:
12:
System.out.printf("Result is %.2f%n", result);
13:
}
14: }

2.0

48

intro. to Java (FEU.faa)

Java

cast cast

2.9.1 Autoboxing Unboxing
int, short, float
user object

myNum Integer myNumToo int
object
( java 1.5)
Integer myNum = new Integer(35);
int myNumToo = 35;

myNum = myNumToo; myNumToo = myNum;

Java 1.5 Autoboxing Unboxing



Boxing wrapper type (object
) Boolean, Byte, Short, Character, Integer, Long, Float, Double
Autoboxing
wrapper type unboxing
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:

/**
From wrapper type to primitives and vice versa
*/
import static java.lang.System.out;
class WrapPrim {
public static void main(String[] argas) {
Integer myInteger = new Integer(35);
int myInt = 4;
out.printf("MyInt = %d%n", myInt);
//boxing
myInt = myInteger;
out.printf("Now MyInt = %d%n", myInt);

double myD = 3.145;


//unboxing
Double myDouble = myD;
out.printf("myD = %.3f, myDouble = %.3f%n", myD, myDouble);

run
MyInt = 4
Now MyInt = 35
myD = 3.145, myDouble = 3.145

boxing 14 unboxing 19

Java
Integer num1 = new Integer(35);
int num2 = num1.intValue();
Integer num3 = Integer.valueOf(num2);

49

intro. to Java (FEU.faa)

2:

num1 Integer 35 num2 int int


num1 method intValue() class Integer num3 Integer
Integer int num2 valueOf() class
Integer 35
wrapper type Double Character
Java API Sun
2.10
int Java

2.10.1 BigInteger
Java class BigInteger
Java
1. Object class BigInteger
2. method

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:

/**
Big Integers Operations Demo
*/
import java.math.BigInteger;
class BigIntegerDemo {
public static void main(String[] args) {
BigInteger big1 = new BigInteger("999999999999999999999999999999");
BigInteger big2 = new BigInteger("999999999999999999999999999999");
BigInteger result;
//add big1 and big2
result = big1.add(big2);
System.out.println("big1 + big2 = " + result);
//subtract big1 and big2
result = big1.subtract(big2);
System.out.println("big1 - big2 = " + result);
//multiply big1 and big2
result = big1.multiply(big2);
System.out.println("big1 * big2 = " + result);

//divide big1 and big2


result = big1.divide(big2);
System.out.println("big1 / big2 = " + result);

big1
big1
big1
big1

+
*
/

big2
big2
big2
big2

=
=
=
=

1999999999999999999999999999998
0
999999999999999999999999999998000000000000000000000000000001
1

class BigDecimal BigInteger


50

intro. to Java (FEU.faa)

Java

2:


function
sine cosine tangent Java
function
function
Quadratic Equation ax2 + bx +
c = 0

x1 =

b + b 2 4ac
2a

x2 =

b b 2 4ac
2a

mathematical function square root Java method


Math.sqrt()
1: /**
2:
Calculating roots of a function
3: */
4:
5: class Quadratic {
6:
public static void main(String[] args) {
7:
double a, b, c;
8:
9:
//4x2 + 20x + 16 = 0
10:
a = 4;
11:
b = 20;
12:
c = 16;
13:
14:
//calculate determinant
15:
double det = Math.sqrt(b * b - 4 * a * c);
16:
17:
//calculate roots
18:
double x1 = (-b + det) / (2 * a);
19:
double x2 = (-b - det) / (2 * a);
20:
21:
System.out.printf("Root 1 = %.4f%n", x1);
22:
System.out.printf("Root 2 = %.4f", x2);
23:
}
24: }

Root 1 = -1.0000
Root 2 = -4.0000

Quadratic. java determinant


0 square root 0
b2 4ac

(if else)
Math.sqrt()
Mathematical function
1: /**
2:
Finding max and min
3: */
4:
5: class MaxMin {
6:
public static void main(String[] args) {

51

intro. to Java (FEU.faa)

2.11 Mathematical Functions Java

Java

int num1 = 58, num2 = 97, num3 = 15;


//finding maximum between num1, num2, and num3
int maxOfTwo = Math.max(num1, num2);
int maxOfAll = Math.max(maxOfTwo, num3);
//finding minimum between num1, num2, and num3
int minOfTwo = Math.min(num1, num2);
int minOfAll = Math.min(minOfTwo, num3);
System.out.printf("Maximum number is %d%n", maxOfAll);
System.out.printf("Minimum number is %d", minOfAll);
}

MaxMin.java method max() min()


integer 3 method
parameter integer
2 integer execute

Maximum number is 97
Minimum number is 15

method class Math


1: /**
2:
Other math functions
3: */
4:
5: class Maths {
6:
public static void main(String[] args) {
7:
double angle = 0.7853982; //45 degrees angle in radians
8:
9:
System.out.println("sin(45) is " + Math.sin(angle));
10:
System.out.println("cos(45) is " + Math.cos(angle));
11:
System.out.println("tan(45) is " + Math.tan(angle));
12:
13:
System.out.println("Absolute value of -456 is " + Math.abs(-456));
14:
System.out.println("2 to the 4th power is " + Math.pow(2D, 4D));
15:
System.out.println("2.345267 rounded to " + Math.round(2.345267));
16:
System.out.println("2.859 rounded to " + Math.round(2.859));
17:
System.out.println("The remainder of 3.25 / 2.25 is " +
Math.IEEEremainder(3.25, 2.25));
18:
System.out.println("The nearest integer of PI is " + Math.rint(Math.PI));
19:
}
20: }

Maths.java method class Math sine cosine tangent


45 0.7853982 radians
radians
method parameter radians
absolute -456 24
run
sin(45) is 0.7071068070684596
cos(45) is 0.7071067553046345
tan(45) is 1.0000000732051062
Absolute value of -456 is 456
2 to the 4th power is 16.0
2.345267 rounded to 2
2.859 rounded to 3
The remainder of 3.25 / 2.25 is 1.0
The nearest integer of PI is 3.0

method toRadians() degrees


radians

52

intro. to Java (FEU.faa)

7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20: }

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:

/**
Other math functions
*/
import java.text.DecimalFormat;
class Maths1 {
public static void main(String[] args) {
double angle = 45;
//45 degrees angle
double sin, cos, tan;
//set format output
DecimalFormat f = new DecimalFormat("0.00000");
//calculate sin, cos, and tan
sin = Math.sin(Math.toRadians(angle));
cos = Math.cos(Math.toRadians(angle));
tan = Math.tan(Math.toRadians(angle));
System.out.println("sin(" + angle + ") = " + f.format(sin));
System.out.println("cos(" + angle + ") = " + f.format(cos));
System.out.println("tan(" + angle + ") = " + f.format(tan));
}
}

Maths1.java
sin(45.0) = 0.70711
cos(45.0) = 0.70711
tan(45.0) = 1.00000

math function

1: /**
2:
Other math functions
3: */
4:
5: class Radius {
6:
public static void main(String[] args) {
7:
double radius;
8:
double area = 850.0;
9:
int meters, centimeters;
10:
11:
//calculate radius
12:
radius = Math.sqrt(area / Math.PI);
13:
14:
//convert to meters and centimeters
15:
meters = (int)Math.floor(radius);
16:
centimeters = (int)Math.round(100.0 * (radius - meters));
17:
18:
System.out.printf("Circle with area of %.2f %s", area, "square meters ");
19:
System.out.printf("has a radius of %d %s", meters, "meters and ");
20:
System.out.printf("%d %s%n", centimeters, "centimeters");
21:
}
22: }

floor() round()
centimeters meters radius run
Circle with area of 850.00 square meters has a radius of 16 meters and 45
centimeters

method 2.7

53

intro. to Java (FEU.faa)

2:

2.7 Mathematical Functions


Method
Function
sin(arg)
sine
cos(arg)
cosine
tan(arg)
tangent
asin(arg)
arc sine

Argument
double (radians)
double (radians)
double (radians)
double

acos(arg)

arc cosine

double

atan(arg)

arc tangent

double

atan2(arg1, arg2)

arc tangent of arg1


arg2

double

abs(arg)

absolute arg

max(arg1, arg2)

arg1
arg2
arg1
arg2

arg


arg

int long float


double
int long float
double
int long float
double
double

Result Type
double
double
double
double (radians
/2
/2)
double (radians
0.0
)
double (radians
/2
/2 )
double (radians

)

Argument

Argument

Argument
double

double

Double

min(arg1, arg2)
ceil(arg)
floor(arg)
round(arg)

integer
arg

float double

rint(arg)

integer
arg

arg1 arg2
root arg
arg1
arg2
e arg
log arg
0.0
1.0

double

int
argument
float long
double
double

double

double

double
double

double
double

double
double

double
double
double

IEEEremainder(arg1,
arg2)
sqrt(arg)
pow(arg1, arg2)
exp(arg)
log(arg)
Random()

2.12 (char)

Java

1: /**
2:
Using character data
3: */
4:
5: class Characters {

54

intro. to Java (FEU.faa)

Java

2:

public static void main(String[] args) {


char H, e, l, o;
H
e
l
o

=
=
=
=

72;
101;
108;
111;

//ASCII
//ASCII
//ASCII
//ASCII

for
for
for
for

'H'
'e'
'l'
'o'

System.out.printf("%c", H);
System.out.printf("%c", e);
System.out.printf("%c", l);
System.out.printf("%c", l);
System.out.printf("%c", o);
System.out.println(" World");
}

run Characters. java Hello World


Unicode H e l o
character operator
1: /**
2:
Using operators on characters
3: */
4:
5: class Characters1 {
6:
public static void main(String[] args) {
7:
char ch1 = 88, ch2 = 77;
8:
9:
System.out.printf("ch1 = %c%n", ch1);
10:
System.out.printf("ch2 = %c%n", ch2);
11:
12:
ch1 -= 23;
//Unicode for 'A'
13:
ch2 += 6;
//Unicode for 'S'
14:
15:
System.out.println("ch1 = " + ch1);
16:
System.out.println("ch2 = " + ch2);
17:
}
18: }

ch1 ch2 X M
ch1 ch2
ch1 23 ch2 6 A X
execute
ch1
ch2
ch1
ch2

=
=
=
=

X
M
A
S

Unicode
1: /**
2:
Unicode character
3: */
4:
5: class Characters2 {
6:
public static void main(String\u005B\u005D args) {
7:
char ch1 = '\u0058'; //unicode for 'X'
8:
char ch2 = '\u004D'; //unicode for 'M'
9:
char ch3 = '\u0041'; //unicode for 'A'
10:
char ch4 = '\u0053'; //unicode for 'S'
11:
12:
System.out.println("ch1 = " + ch1);
13:
System.out.println("ch2 = " + ch2);
14:
System.out.println("ch3 = " + ch3);
15:
System.out.println("ch4 = " + ch4);
16:
}
17: }

55

intro. to Java (FEU.faa)

6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21: }

run Characters1.java
Unicode Unicode


'?'
6 Unicode \u005B \u005D
[] Java []
2.7
Character Escape Sequences
( )
2.7 Character Escape Sequence
Escape Sequence

\ddd
(Octal)
\uxxxx

Unicode (Hexadecimal)

\'

' (Single quote)

\"

" (Double quote)

\\

\r

(Carriage return)

\n

(New line Linefeed)

\f

(Form feed)

\t

(Tab)

\b

2.13 boolean
boolean
boolean
boolean operator
Logical Operator
boolean operator
&&
||
&
|
!

Conditional AND
Conditional OR
Logical AND
Logical OR
Logical NOT

&& || Lazy Short Circuit


& |
operator && & &&
false false
false
operator || &&
true true
true

56

intro. to Java (FEU.faa)

Java

2:

operator ! boolean

Operator
boolean
<
>
<=

>=

==
!=

operator Relational operator



operator

1: /**
2:
Testing boolean operations
3: */
4:
5: class BooleanOp {
6:
public static void main(String[] args) {
7:
boolean A = true, B = false;
8:
9:
System.out.println("Conditional AND");
10:
System.out.println("F && F is " + (B && B));
11:
System.out.println("F && T is " + (B && A));
12:
System.out.println("T && F is " + (A && B));
13:
System.out.println("T && T is " + (A && A));
14:
15:
System.out.println("Conditional OR");
16:
System.out.println("F || F is " + (B || B));
17:
System.out.println("F || T is " + (B || A));
18:
System.out.println("T || F is " + (A || B));
19:
System.out.println("T || T is " + (A || A));
20:
21:
System.out.println("Logical AND");
22:
System.out.println("F & F is " + (B & B));
23:
System.out.println("F & T is " + (B & A));
24:
System.out.println("T & F is " + (A & B));
25:
System.out.println("T & T is " + (A & A));
26:
27:
System.out.println("Logical OR");
28:
System.out.println("F | F is " + (B | B));
29:
System.out.println("F | T is " + (B | A));
30:
System.out.println("T | F is " + (A | B));
31:
System.out.println("T | T is " + (A | A));
32:
33:
System.out.println("Logical NOT");
34:
System.out.println("!F is " + (!B));
35:
System.out.println("!T is " + (!A));
36:
}
37: }

A B true false
operator System.out.println()

Conditional AND
F && F is false
F && T is false

57

intro. to Java (FEU.faa)

operator & |

Java

Conditional OR
F || F is false
F || T is true
T || F is true
T || T is true
Logical AND
F & F is false
F & T is false
T & F is false
T & T is true
Logical OR
F | F is false
F | T is true
T | F is true
T | T is true
Logical NOT
!F is true
!T is false

Relational operator (BooleanOp2.java)


1: /**
2:
Using relational operators
3: */
4:
5: class BooleanOp2 {
6:
public static void main(String[] args) {
7:
int i = 5, j = 10;
8:
9:
System.out.println("i = " + i);
10:
System.out.println("j = " + j);
11:
System.out.println("i > j is " + (i > j));
12:
System.out.println("i < j is " + (i < j));
13:
System.out.println("i >= j is " + (i >= j));
14:
System.out.println("i <= j is " + (i <= j));
15:
System.out.println("i == j is " + (i == j));
16:
System.out.println("i != j is " + (i != j));
17:
System.out.println("(i < 10) && (j < 10) is " + ((i < 10) && (j < 10)) );
18:
System.out.println("(i < 10) || (j < 10) is " + ((i < 10) || (j < 10)) );
19:
}
20: }

BooleanOp2.java
operator int i
j 5 10
operator

run
i = 5
j = 10
i > j is false
i < j is true
i >= j is false
i <= j is true
i == j is false
i != j is true
(i < 10) && (j < 10) is false
(i < 10) || (j < 10) is true

operator && operator ||


( 2-4 2-5) p

58

intro. to Java (FEU.faa)

T && F is false
T && T is true

q 5 10 10 5

p = 5, q = 10

(p < q)

&&

p = 10, q = 5

(q <= 10)

(p < q)

&&

(q <= 10)

F
&& F

2- 4 &&

p = 5, q = 10

(p < q)

||

p = 10, q = 5

(q <= 10)

(p < q)

T ||
T

||

(q <= 10)

2-5 ||

2.8 operator && || & |


2.8
P
true
false
true
false

operator && || & |


Q
P && Q
P || Q
true
true
true
true
false
true
false
false
true
false
false
false

P&Q
true
false
false
false

P|Q
true
true
true
false

boolean operator
boolean
(condition)
true false true
false boolean operator
logic (logic and loop)

59

intro. to Java (FEU.faa)

2:

Java

bit operator
bit
operator shift
Java << >> >>>
2.9 operator shift << >> >>>
Operator

<<
operand1 << operand2
bit operand1
operand2 0 bit
>>
operand1 >> operand2
bit operand1
operand2 bit (sign bit)

>>>
operand1 >>> operand2
bit operand1
operand2 0 bit

13 >> 1
13 = 000011012 shift 1 bit 000001102 ( 6
10)
13 << 1
shift 1 bit 000110102 ( 26 10)
13 >>> 1
shift 1 bit 000001102 ( 6 10)
bit bit
bit ShiftLeftOp.java
1: /**
2:
Using left-shift operator
3: */
4:
5: class ShiftLeftOp {
6:
public static void main(String[]
7:
byte bits = 1;
8:
9:
System.out.println("Value of
10:
bits = (byte) (bits << 1);
11:
System.out.println("Value of
12:
bits = (byte) (bits << 1);
13:
System.out.println("Value of
14:
bits = (byte) (bits << 1);
15:
System.out.println("Value of
16:
bits = (byte) (bits << 1);
17:
System.out.println("Value of
18:
bits = (byte) (bits << 1);
19:
System.out.println("Value of
20:
bits = (byte) (bits << 2);
21:
System.out.println("Value of
22:
}
23: }

args) {
bits is " + bits);
bits is " + bits);
bits is " + bits);
bits is " + bits);
bits is " + bits);
bits is " + bits);
bits is " + bits);

bits byte bit



run
Value of bits is 1
Value of bits is 2
Value of bits is 4

60

intro. to Java (FEU.faa)

2.14 bit operator Shift Bitwise

Value of bits is 8
Value of bits is 16
Value of bits is 32

byte bit bit


bit ( 20) bits code
run
bits = (byte) (bits << 2);
System.out.println("Value of bits is " + bits);

run code bits -128


Java byte
127
Value
Value
Value
Value
Value
Value
Value

of
of
of
of
of
of
of

bits
bits
bits
bits
bits
bits
bits

is
is
is
is
is
is
is

1
2
4
8
16
32
-128

cast
Java bits int shift
( shift )
>> << bit >>
bit
128 >> 4 128/24 = 16
-256 >> 4 -256/24 = -16
bit << bit

128 << 1 128 * 21 = 256
16 << 2 16 * 22 = 64
bitwise operator bitwise AND (&),
bitwise OR (|) bitwise exclusive OR (XOR)
1: /**
2:
Show bitwise operations
3: */
4:
5: class BitwiseOperations {
6:
public static void main(String[]
7:
byte bits = 5;
8:
9:
System.out.println("Value of
10:
11:
//using bitwise AND
12:
bits = (byte)(bits & 5);
13:
System.out.println("Value of
14:
15:
//using bitwise OR
16:
bits = (byte)(bits | 7);
17:
System.out.println("Value of
18:
19:
//using bitwise exclusive OR
20:
bits = (byte)(bits ^ 4);
21:
System.out.println("Value of
22:
}
23: }

args) {
bits is " + bits);

bits is " + bits);

bits is " + bits);


(XOR)
bits is " + bits);

61

intro. to Java (FEU.faa)

2:

bitwise operator 2.10


2.10 bitwise operator &, |, ^
Operator

&
operand1 & operand2
bit 1
1
|
operand1 | operand2
bit 1
1
^
operand1 ^ operand2
bit 1
BitwiseOperations.java & 5 5 12
5 (00000101 & 00000101 = 00000101) 16 | 5 7
7 (00000101 | 00000111 = 00000111) 20 ^ 7
4 3 (00000111 ^ 00000100 = 00000011)

integer floating-point



Java method keyboard

keyboard (
)
2.15

Java 1.5 method
int float double char


C C++ code
String String String
[ Java 1.5
keyboard Scanner]
String String
Java String object ( object? object
)
People of Thailand

price_of_coffee
1234567890
23+popOfRock
String String
keyboard String
code Radius.java area keyboard

1: /**
2:
Reading data from keyboard
3: */
4: import java.io.*;
5:
6: class Radius2 {
7:
public static void main(String[] args) throws IOException {
8:
double radius, area;

62

intro. to Java (FEU.faa)

Java

2:

int meters, centimeters;


String inputString = null;
//prompt user for area of a circle
System.out.print("Enter area of a circle: ");
//get string from keyboard
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(in);
inputString = buffer.readLine();
//convert string to double
area = Double.parseDouble(inputString);
//calculate radius
radius = Math.sqrt(area / Math.PI);
//convert to meters and centimeters
meters = (int)Math.floor(radius);
centimeters = (int)Math.round(100.0 * (radius - meters));
System.out.print("Circle with area of " + area + " square meters ");
System.out.print("has a radius of " + meters + " meters and ");
System.out.println(centimeters + " centimeters");
}

Raadius2.java code String keyboard


System.out.print("Please enter area of a circle: ");
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(in);
String inputString = buffer.readLine();

user
byte (System.in) character
in buffer
character in String String (
buffer) String method readLine() buffer
String inputString
String String
keyboard (
)
String String
Radius2.java double
String double method parseDouble() class Double
keyboard method
area = Double.parseDouble(inputString);

code run
850 54
Please enter area of a circle: 850
Circle with area of 850.0 square meters has a radius of 16 meters and 45
centimeters
Please enter area of a circle: 54
Circle with area of 54.0 square meters has a radius of 4 meters and 15 centimeters

Radius2.java main(..)
throws IOException

63

intro. to Java (FEU.faa)

9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35: }

throws IOException main()


Java
I/O

( 7)
Radius2.java error
Radius2.java:16: unreported exception java.io.IOException; must be caught or
declared to be thrown
String inputString = buffer.readLine();
^
1 error

Java

must be caught or declared to be thrown


(1) catch
(2) throws Java
error

code
1: /**
2:
Reading data from keyboard with error detection
3: */
4:
5: import java.io.*;
6:
7: class Radius3 {
8:
public static void main(String[] args) throws IOException {
9:
double radius, area;
10:
int meters, centimeters;
11:
String inputString = null;
12:
13:
try {
14:
//prompt user for area of a circle
15:
System.out.print("Please enter area of a circle: ");
16:
17:
//get string from keyboard
18:
InputStreamReader in = new
InputStreamReader(System.in);
19:
BufferedReader buffer = new BufferedReader(in);
20:
inputString = buffer.readLine();
21:
}
22:
catch(IOException ioe) {}
23:
24:
//convert string to double
25:
area = Double.parseDouble(inputString);
26:
27:
//calculate radius
28:
radius = Math.sqrt(area / Math.PI);
29:
30:
//convert to meters and centimeters
31:
meters = (int)Math.floor(radius);
32:
centimeters = (int)Math.round(100.0 * (radius - meters));
33:
34:
System.out.print("Circle with area of " + area + " square meters ");
35:
System.out.print("has a radius of " + meters + " meters and ");
36:
System.out.println(centimeters + " centimeters");
37:
}
38: }


String inputString = null;

64

intro. to Java (FEU.faa)

Java

//prompt user for area of a circle


System.out.print("Please enter area of a circle: ");
try {
//get string from keyboard
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(in);
inputString = buffer.readLine();
}
catch(IOException ioe) {}

inputString

try {

}
catch(IOException ioe) {}

string block try


{} catch(IOException ioe) {} block try {}
code code catch(IOExcpetion ioe) {}
error error
Java


Enter try {..} catch()
{} Radius3.java
1: /**
2:
Reading data from keyboard with error detection
3: */
4: import java.io.*;
5:
6: class Radius4 {
7:
public static void main(String[] args) {
8:
double radius, area;
9:
int meters, centimeters;
10:
String inputString = null;
11:
12:
//prompt user for area of a circle
13:
System.out.print("Please enter area of a circle: ");
14:
try {
15:
//get string from keyboard
16:
InputStreamReader in = new InputStreamReader(System.in);
17:
BufferedReader buffer = new BufferedReader(in);
18:
inputString = buffer.readLine();
19:
20:
try {
21:
//convert string to double
22:
area = Double.parseDouble(inputString);
23:
24:
//calculate radius
25:
radius = Math.sqrt(area / Math.PI);
26:
27:
//convert to meters and centimeters
28:
meters = (int)Math.floor(radius);
29:
centimeters = (int)Math.round(100.0 * (radius - meters));
30:
31:
System.out.print("Circle with area of " +
area + " square meters ");
32:
System.out.print("has a radius of " +
meters + " meters and ");
33:
System.out.println(centimeters + " centimeters");
34:
}
35:
//catch empty string (user hits Enter)
36:
catch(Exception e) {
37:
System.out.println("Error! you must supply input");
38:
e.printStackTrace();

65

intro. to Java (FEU.faa)

2:

Java

System.exit(1);
}
}
//catch other I/O error - do nothing
catch(IOException ioe) { /* leave it to Java! */ }
}

Radius3.java try {} cath() {}



System.out.println("Error! you must
supply input");
1. error Java e.printStackTrace();
2. System.exit(1);
execute
Please enter area of a circle: < User Enter >
Error! you must supply input
java.lang.NumberFormatException: empty String
at sun misc FloatingDecimal.readJavaFormatString (Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at Radius4.main(Radius4.java:22)

Java
1 System.exit(1) 0
0 1
error code
error
2.15.1 Scanner
(
C Java)
Scanner
Scanner
keyboard keyboard
Scanner
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:

/**
Reading numbers via Scanner
*/
import java.util.Scanner;
import static java.lang.System.out;
class AddIntegers {
public static void main(String[] args) {
//setup input channel via command prompt
Scanner input = new Scanner(System.in);
int number1, number2;
int sum;
float average;
//prompt for two integers
out.print("Enter first integer: ");
number1 = input.nextInt();
out.print("Enter second integer: ");
number2 = input.nextInt();
//find sum and average

66

intro. to Java (FEU.faa)

39:
40:
41:
42:
43:
44:
45: }

2:

sum = number1 + number2;


average = sum / 2.0F;
//display results
out.printf("Sum of two integers is %d%n", sum);
out.printf("Average of two integers is %.2f%n", average);
}

11 command prompt Scanner


integer 19 21 method
nextInt() class Scanner method

integer nextInt()
float double nextFloat() nextDouble()
long short nextLong() nextShort()
next()
nextLine()
hasNext(), hasNextInt(),
hasNextDouble()
Class Scanner method Java
API
2.15.2 Dialog Box


InputDialog Method Java Swing
Swing method

InputDialog
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

/**
Reading input via InputDialog
*/
import javax.swing.*;
class InputTest {
public static void main(String[] args) {
//get name
String name = JOptionPane.showInputDialog("What is your name?");
//get age
String ageStr = JOptionPane.showInputDialog("Tell me you age.");
int age = Integer.parseInt(ageStr);
//send output to standard output device (console)
System.out.println("Hello " + name + " " +
age + " is very young!");
System.exit(0);
}
}

compile run

67

intro. to Java (FEU.faa)

24:
25:
26:
27:
28:
29:
30:
31: }

Prompt user

OK
dialog box

Cancel
dialog box

Peter Pan OK

OK console

Hello Peter Pan 42 is very young!

Inputtest.java 3 2 name ageStr


String user
String name = JOptionPane.showInputDialog ("What is your name?");
String ageStr = JOptionPane.showInputDialog ("Tell me your age.");

age string user int

(System.exit(0))
Java JOptionpane.showInputDialog
Java Thread InputDialog
console
InputDiaglog

MessageDialog user
1: /**
2:
Reading input via InputDialog
3:
Sending output via MessageDialog
4: */
5: import javax.swing.*;

68

intro. to Java (FEU.faa)

Java

6:
7: class OutputTest {
8:
public static void main(String[] args) {
9:
//get name
10:
String name = JOptionPane.showInputDialog("What is your name?");
11:
12:
//get age
13:
String ageStr = JOptionPane.showInputDialog("Tell me you age.");
14:
int age = Integer.parseInt(ageStr);
15:
age += 5;
16:
17:
JOptionPane.showMessageDialog(null,
18:
"Hello " + name + ", " +
19:
" 5 years from now you will be " + age +
20:
".\nWhich is still very young!",
21:
"Output",
22:
JOptionPane.INFORMATION_MESSAGE);
23:
24:
System.exit(0);
25:
}
26: }

OutputTest.java InputTest.java

JOptionPane.showMessageDialog(null,
"Hello " + name + ", " +
" 5 years from now you will be " + age +
".\nWhich is still very young!",
"Output",
JOptionPane.INFORMATION_MESSAGE);

user Dialog Window showMessageDialog()


parameter 4
1.
2.
3.
4.

Component
Object message
string title MessageDialog
Message

Component null ( scope ) Object


message
"Hello " + name + ", " +
" 5 years from now you will be " + age +
".\nWhich is still very young!",

String title MessageDialog "Output"


message (INFORMATION_MESSAGE)
message icon MessageDialog
run ()

MessageDialog message
"\n" int

69

intro. to Java (FEU.faa)

2:

MessageDialog ( age) string



Java

keyboard
dialog box
( dialog box
)

3 (loop)
2.16 enum
Java 1.5 enum
final
enum enum

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

/**
Shows simple usage of enum
*/
enum Season {SUMMER, RAINNY, WINTER};
class UseOfEnum {
public static void main(String[] args) {
//printing values of enum
System.out.println("Seasons in Thailand are: " +
Season.SUMMER + ", " +
Season.RAINNY + ", and " +
Season.WINTER);
}
}

enum enum enum


{ {
enum Season
3 SUMMER, RAINNY, WINTER }
enum
enum (.)
enum
Season.WINTER

enum
Java
UseOfEnum.java
System.out.println("SUMMER = " + Season.SUMMER.ordinal() + "\n" +
"RAINNY = " + Season.RAINNY.ordinal() + "\n" +
"WINTER = " + Season.WINTER.ordinal());

70

intro. to Java (FEU.faa)

Java

2:

Seasons in Thailand are: SUMMER, RAINNY, and WINTER


SUMMER = 0
RAINNY = 1
WINTER = 2

Season.SUMMER SUMMER

Java

enum

primitive datatype Java



(casting) method
error
bit dialog box

1. final
2. 5, 5.0, '5', "5", "5.0"
3.
3.1.
3.2.
3.3.
3.4.
3.5.

System.out.println("4" + 4);
System.out.println('4' + 4);
System.out.println("4" + 4 + 4);
System.out.println("4" + (4 + 4));
System.out.println('4' + 4 + 4);

4.
4.1.
4.2.
4.3.
4.4.

System.out.println("Value is %f %e\n", 45.25, 45.25);


System.out.println("Value is %5.4f %5.4e\n", 45.25, 45.25);
System.out.println("%4b%n", (4 > 5));
System.out.println("%6s\n", "Java");

5. cast cast
char c = 'A';
in = (int)c;
boolean b = true;
in = (int)b;
float f = 500.44f;
in = (int)f;
double d = 500.44d;
in = (int)d;

71

intro. to Java (FEU.faa)

int x = 65;
char c = (char)x;
int v = 1000;
Boolean b = (Boolean)v;
6. x 1
6.1.
6.2.
6.3.
6.4.
6.5.
6.6.
6.7.
6.8.

(x > 1) & (x++ > 1)


(x > 1) && (x++ > 1)
x >> 1
x << 1
x >>> 1
x^1
x&1
x|1

7.
double x = 4.5;
double y = -45.25;
int p = 12;
int q = 2;
7.1.
7.2.
7.3.
7.4.
7.5.
7.6.
7.7.
7.8.
7.9.
7.10.

x + p * y / (p y) * x
p % (p q)
(int) y
(int) p
Math.round(x)
(int) Math.round(y)
-2 * y + (int) x
q/p
p%q
y * y y + (x * (int) x)

8. int keyboard 2 double


2 4

9. Java
9.1.
9.2.
9.3.
9.4.

a + bc / 2
a(a c) + b(b c) (c(c a) / d)
b2 4ac
(4/3)2 / 2

9.5.

T xM
q= 1
+ T2
Dk

10. Celsius Fahrenheit


keyboard
Celsius =

72

5
(Fahrenheit 32)
9

intro. to Java (FEU.faa)

Java

11. Fahrenheit Celsius


keyboard
12. keyboard mile

13. keyboard
( 1 365 )
14. int 5

15.

16.
beer 1 beer 1 (24
) barley 1 200
barley beer

17. long (digit) 10 12


,
3
18.
(perimeter)
19. keyboard
20. double 5 keyboard

21. 865,000
7,600
21.1.
21.2.
21.3.

(cubic mile mile3)


(cubic mile)

22. double xxx.xxxx 123.4567


keyboard
long long
long
23. integer 0 10

number square cube


0
0
0
1
1
1
2
4
8
3
9
27
4
16
64
5
25 125
6
36 216
7
49 343
8
64 512
9
81 729
10
100 1000

73

intro. to Java (FEU.faa)

2:

24. 4 JOptionPane.showInputDialog
JOptionPane.messageDialog
25. JOptionPane 19
26. (lower case)
(upper case) method Java ( ASCII
)
27.
true
false
Can edges 1, 2, and 1 form a triangle? False
Can edges 2, 2, and 1 form a triangle? True
[
]
28. 0 1000
345 12
[ operator % operator /
654 % 10 = 4 654 / 10 = 65]
29. JOptionPane 20
JOptionPane string
double 5
string

input

method class StringTokenizer package


java.util.StringTokenizer ( 3)

74

intro. to Java (FEU.faa)

Java

Вам также может понравиться