Professional Documents
Culture Documents
Part 1:
Java as an Object-oriented
Programming Language
Java History
JDK Evolutions
J2SE, J2ME, and J2EE
13/03/2015
JDK Editions
Java Standard Edition (J2SE)
J2SE can be used to develop client-side standalone applications or
applets.
13/03/2015
13/03/2015
Compiling a program
Execute (java)
byte code
(Hello.class)
output
Program execution
Syntax
10
Syntax Errors
Java is case-sensitive
Hello and hello are not the same
1 Public class Hello {
2
public static void main(String[] args) {
3
System.out.println("Hello, world!");
4
}
5 }
compiler output:
1 error found:
File: Hello.java [line: 1]
Error: Hello.java:1: class, interface, or enum
expected
12
System.out.println
System.out.println: A statement to print a line of
output to the console.
pronounced print-linn
Two ways to use System.out.println:
System.out.println("<message>");
Prints the given message as a line of text to the
console.
System.out.println();
Prints a blank line to the console.
13
14
Primitive types
Java has eight primitive types. Here are two examples:
Name Description
int
integers
double
real numbers
Examples
42, -3, 0, 926394
3.4, -2.53, 91.4e3
15
Discrete
Types
byte
short
int
long
Continuous Types
float
double
Non-numeric Types
boolean
char
16
Representation
Bits
Bytes
#Values
boolean
true or false
N/A
char
a or 7 or \n
16
216 = 65,536
byte
,-2,-1,0,1,2,
28 = 256
short
,-2,-1,0,1,2,
16
216 = 65,536
int
,-2,-1,0,1,2,
long
,-2,-1,0,1,2,
> 18 quintillion
float
32
double
64
18
Examples:
"hello" + 42 is "hello42"
1 + "abc" + 2
is "1abc2"
"abc" + 1 + 2
is "abc12"
1 + 2 + "abc
is "3abc"
"abc" + 9 * 3 is "abc27" (what happened here?)
"1" + 1
is "11"
4 - 1 + "abc
is "3abc"
"abc" + 4 - 1causes a compiler error. Why?
19
Overflow example
int n = 2000000000;
System.out.println(n * n);
// output: -1651507200
the result of n*n is 4,000,000,000,000,000,000 which needs 64-bits:
Declaring variables
To create a variable, it must be declared.
Variable declaration syntax:
<type> <name>;
Identifiers: Keywords
default
do
double
else
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
NB: Because Java is case-sensitive, you could technically use Class or cLaSs
as identifiers, but this is very confusing and thus strongly discouraged.
22
Shorthand
<variable>++;
<variable>--;
Examples:
int x = 2;
x++;
// x = x + 1;
// x now stores 3
23
if/else statements
24
The if statement
if statement: A control structure that executes a block of
statements only if a certain condition is true.
General syntax:
if (<test>) {
<statement(s)> ;
}
25
26
if (<test>) {
<statement(s)> ;
} else {
<statement(s)> ;
}
Example:
if (gpa >= 3.0) {
System.out.println("Welcome to Temple!");
} else {
System.out.println("Try applying to Penn.");
}
27
28
<statement(s)> ;
} else if (<test>) {
<statement(s)> ;
} else {
<statement(s)> ;
}
Example:
if (number > 0) {
System.out.println("Positive");
} else if (number < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
29
30
31
Boolean Arithmetic
32
//just like
//just like
int i = 2;
int x = y*2;
33
Relational expressions
Relational expressions have
numeric arguments and
boolean values.
Meaning
Example
Value
==
equals
1 + 1 == 2
true
!=
3.2 != 2.5
true
<
less than
10 < 5
false
>
greater than
10 > 5
true
<=
false
>=
true
34
>=
>=
>=
>=
3 + 5 * (7 - 1)
3 + 5 * 6
3 + 30
33
Logical operators
Logical operators have
boolean arguments and
boolean values
Operator
&&
Description
and
Example
(9 != 6) && (2 < 3)
||
or
(2 == 3) || (-1 < 5)
not
!(7 > 0)
Result
true
36
Boolean expressions
What is the result of each of the following expressions?
int x = 42;
int y = 17;
int z = 25;
Class Constants
A class constant is a variable
whose scope is the entire class, and
whose value can never change after it has been initialized.
To give it the right scope, simply declare it right inside the class:
public class MyClass {
public static final int myConstant = 4;
}
39
General syntax:
Example:
Control Structure
The for loop is a control structurea syntactic
structure that controls the execution of other
statements.
Example:
Shampoo hair. Rinse. Repeat.
41
Example:
for (int i = 1; i <= 4; i++) {
System.out.println(i + " squared is " + (i * i));
}
Output:
1
2
3
4
squared
squared
squared
squared
is
is
is
is
1
4
9
16
42
43
Loop walkthrough
Code:
for (int i = 1; i <= 3; i++) {
System.out.println(i + " squared is " + (i * i));
}
Output:
i:
1 squared is 1
2 squared is 4
3 squared is 9
44
Loop example
Code:
System.out.println("+----+");
for (int i = 1; i <= 3; i++) {
System.out.println("\\
/");
System.out.println("/
\\");
}
System.out.println("+----+");
Output:
+----+
\
/
/
\
\
/
/
\
\
/
/
\
+----+
45
The initial and final values for the loop counter variable can be arbitrary
expressions:
Example:
for (int i = -3; i <= 2; i++) {
System.out.println(i);
}
Output:
-3
-2
-1
0
1
2
Example:
for (int i = 1 + 3 * 4; i <= 5248 % 100; i++) {
System.out.println(i + " squared is " + (i * i));
}
46
47
Errors in coding
ERROR: Loops that never execute.
for (int i = 10; i < 5; i++) {
System.out.println("How many times do I print?");
}
Output:
1
2
3
4
5
2 3 4 5 6 7 8 9 10
4 6 8 10 12 14 16 18 20
6 9 12 15 18 21 24 27 30
8 12 16 20 24 28 32 36 40
10 15 20 25 30 35 40 45 50
50
Output:
**********
**********
**********
**********
**********
**********
51
Output:
*
**
***
****
*****
******
52
Output:
1
22
333
4444
55555
666666
53
Output:
1
22
333
4444
55555
54
Key idea:
outer "vertical" loop for each of the lines
inner "horizontal" loop(s) for the patterns within each line
55
Nested loops
First, write the outer loop from 1 to the number of lines desired.
for (int line = 1; line <= 5; line++) {
...
}
56
Nested loops
Make a table:
....1
...2
..3
.4
5
value displayed
Answer:
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (line * -1 + 5); j++) {
System.out.print(".");
}
System.out.println(line);
}
57
Errors in coding
while loops
59
Definite loops
definite loop: A loop that executes a known number of
times.
The for loops we have seen so far are definite loops.
Examples:
Print "hello" 10 times.
Find all the prime numbers up to an integer n.
60
Indefinite loops
indefinite loop: A loop where it is not obvious in advance
how many times it will execute.
We often use language like
"Keep looping as long as or while this condition is still true."
"Don't stop repeating until the following happens."
Examples:
Print random numbers until a prime number is printed.
Continue looping while the user has not typed "n" to quit.
61
while loop
<statement(s)>;
Example:
int number = 1;
while (number <= 200) {
System.out.print(number + " ");
number *= 2;
}
Output:
1 2 4 8 16 32 64 128
62
63
Example
Finds and prints a number's first factor other than 1:
Scanner console = new Scanner(System.in);
System.out.print("Type a number: ");
int number = console.nextInt();
int factor = 2;
while (number % factor != 0) {
factor++;
}
System.out.println("First factor: " + factor);
Sample run:
Type a number: 91
First factor: 7
64
65
Solution:
int i = 1;
while (i <= 10) {
System.out.println(i + " squared = " + (i * i));
i++;
}
66
Exercise: digitSum
Write a class named DigitSum that reads an integer from
the user and prints the sum of the digits of that number.
You may assume that the number is non-negative.
Example:
29107
prints 2+9+1+0+7 or 19
67
Solution: digitSum
import java.util.Scanner;
public class DigitSum {
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
int n = keyboard.nextInt();
int sum = 0;
while (n > 0) {
sum += n % 10;
// add last digit to sum
n = n / 10;
// remove last digit
}
System.out.println(sum = + sum);
}
}
68
Random numbers
69
Description
returns a random integer
<min>
Random questions
Given the following declaration, how would you get:
Random rand = new Random();
72
Random solutions
Given the following declaration, how would you get:
Exercise: Die-rolling
Write a program that simulates the rolling of two six-sided
dice until their combined result comes up as 7.
Sample run:
Roll: 2
Roll: 3
Roll: 5
Roll: 1
Roll: 4
You won
+ 4 =
+ 5 =
+ 6 =
+ 1 =
+ 3 =
after
6
8
11
2
7
5 tries!
74
Solution: Die-rolling
import java.util.*;
}
}
75
Scanner objects
76
Interactive programs
We have written programs that print console output.
It is also possible to read input from the console.
The user types the input into the console.
The program uses the input to do something.
Such a program is called an interactive program.
77
Scanner
Constructing a Scanner object to read the console:
Scanner <name> = new Scanner(System.in);
Example:
Scanner console = new Scanner(System.in);
78
Scanner methods
Some methods of Scanner:
Method
nextInt()
Description
reads and returns user input as an int
79
80
Input tokens
token: A unit of user input, as read by the Scanner.
Tokens are separated by whitespace (spaces, tabs, new lines).
How many tokens appear on the following line of input?
23 John Smith
42.0 "Hello world"
When the token doesn't match the type the Scanner tries to read,
the program crashes.
Example:
System.out.print("What is your age? ");
int age = console.nextInt();
Sample Run:
What is your age? Timmy
InputMismatchException:
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
...
81
Importing classes
Java class libraries: A large set of Java classes available
for you to use.
Classes are grouped into packages.
To use the classes from a package, you must include an
import declaration at the top of your program.
Scanner is in a package named java.util
82
A complete program
import java.util.*;
}
}
Sample Run:
What is your first name? Marty
How old are you? 12
Marty is 12. That's quite old!
83
Sample Run:
Please type three numbers: 8 6 13
The average is 9.0
Notice that the Scanner can read multiple values from one line.
84