Академический Документы
Профессиональный Документы
Культура Документы
o
o
o
o
o
o
o
Java
public class ClassName {
public static void main(String[] args) {
program statements
}
}
(memory) compiler
(address offset)
integer ( 2, 45, 90
) double float (
2.35, 3.00 )
compiler compiler
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
datatype identifier
datatype Java datatype
(primitive datatype) (reference
type) class object
Java primitive datatype 8 4
( 2.2)
1
22
Java
1.
2.
3.
4.
(Logical) boolean
(Textual) char
(Integral) byte, short, int, long
(Floating point) double float
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
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
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
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
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
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;
26
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;
2.4 final
PI
Java user
(reserved word) final
27
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
149, 600,000 (1.496 x 108)
(electron mass)
28
Java
// 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
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
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
31
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
Java
j
j
j
j
*
/
%
k
k
k
k
=
=
=
=
3
10
2
1
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;
operators
" + i);
" + i);
" + i);
" + i);
" + i);
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
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
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
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);
36
"" Java +
(System.out) " "
Java
System.out.println("30 + 45 = " + (30 + 45));
value
total
total
value
2-3
total += value;
+=
() operator
2.5
37
2:
2.5 operator
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
14 ()
38
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;
code
value = (++count) + (++value);
(?)
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++;
39
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
40
Java
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16: }
cast
cast
ByteShort.java Java compile
total = numScooters + numChoppers;
total = (short)(numScooters + numChoppers);
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
41
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;
long L
bit 64 bit
int bit
32 bit
integer
o
42
int 0 Java
error exception
Java
o
o
error Java
exception
% 0 error 0
FloatingPoint.java
1075 1580 8.5%
execute
Tax = 591.175
Total income = 6363.825
? 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
2:
Java
form.format(tax) form.format(totalIncome)
Tax = 591.18
Total income = 6,363.82
/**
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
, (comma)
Java 1.5
printf()
44
24: }
2:
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
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
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
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: }
Jennie Xumsai is 9
Maximum long: 9223372036854775807
Maximum double: 1.797693E+308
static import
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: }
47
2:
()
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
48
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;
/**
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);
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
2:
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);
big1
big1
big1
big1
+
*
/
big2
big2
big2
big2
=
=
=
=
1999999999999999999999999999998
0
999999999999999999999999999998000000000000000000000000000001
1
50
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
Root 1 = -1.0000
Root 2 = -4.0000
51
Java
52
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
2:
Argument
double (radians)
double (radians)
double (radians)
double
acos(arg)
arc cosine
double
atan(arg)
arc tangent
double
atan2(arg1, arg2)
double
abs(arg)
absolute arg
max(arg1, arg2)
arg1
arg2
arg1
arg2
arg
arg
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
Java
2:
=
=
=
=
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");
}
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
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)
\'
\"
\\
\r
(Carriage return)
\n
\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
56
Java
2:
operator ! boolean
Operator
boolean
<
>
<=
>=
==
!=
A B true false
operator System.out.println()
Conditional AND
F && F is false
F && T is false
57
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
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
58
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 ||
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
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);
60
Value of bits is 8
Value of bits is 16
Value of bits is 32
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);
61
2:
&
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
Java
2:
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
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: }
Java
String inputString = null;
64
Java
inputString
try {
}
catch(IOException ioe) {}
65
2:
Java
System.exit(1);
}
}
//catch other I/O error - do nothing
catch(IOException ioe) { /* leave it to Java! */ }
}
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
39:
40:
41:
42:
43:
44:
45: }
2:
/**
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
24:
25:
26:
27:
28:
29:
30:
31: }
Prompt user
OK
dialog box
Cancel
dialog box
Peter Pan OK
OK console
(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
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);
Component
Object message
string title MessageDialog
Message
MessageDialog message
"\n" int
69
2:
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
Java
UseOfEnum.java
System.out.println("SUMMER = " + Season.SUMMER.ordinal() + "\n" +
"RAINNY = " + Season.RAINNY.ordinal() + "\n" +
"WINTER = " + Season.WINTER.ordinal());
70
Java
2:
Season.SUMMER SUMMER
Java
enum
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.
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
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.
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)
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
72
5
(Fahrenheit 32)
9
Java
13. keyboard
( 1 365 )
14. int 5
15.
16.
beer 1 beer 1 (24
) barley 1 200
barley beer
73
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
74
Java