Java Programming Basics: Identifiers, Types, Variables, Operators, and Control Flow
Java Programming Basics: Identifiers, Types, Variables, Operators, and Control Flow
had to be reliable
UNIX - X-Windows
Web interest came along later Java Virtual Machine 2
1
1
CSD Univ. of Crete Fall 2012
Simple
Stripped-down version of C/C++ minus all the confusing,
troublesome features of C/C++
Object-oriented
Promotes good software engineering by
facilitating code reuse
Platform-independent
Executable
code is bytecode that can run run any
machine. Compile once, run everywhere. 3
Portable
Works
the same on all machines.
“WORA”, or write once run anywhere
Multithreaded
Programs can handle many operations simultaneously
Secure
Bytecode verification on loading (not just compilation)
Applet code runs in 'sandbox' with significant
restrictions 4
2
2
CSD Univ. of Crete Fall 2012
Just in Time
Java Virtual
Java
Another software tool, called an Code
Machine
interpreter
interpreter translates bytecode into Generator
machine language and executes it
The JVM is a software layer that Run-Time System
provides translation between Java
byte codes and the native Machine
operating system code
6
3
3
CSD Univ. of Crete Fall 2012
Bytecode
AL_CODE: Method 1
Like Machine code but machine Method="HelloWorld.main"(#24)
Signature="([Ljava/lang/String;)V"(#26)
independent Access=public,static (0x0009)
VM interprets each bytecode Attribute Count=1
Attribute="Code"(#20)
and executes it in the system’s Length=51
Max Stack=2
machine opcode Max Locals=1
VM inner loop Code Length=9
0x00000000 B20008 getstatic
do { (#8) java/lang/System.out
0x00000003 1201 ldc
fetch an opcode byte (#1) "Hello World"(#34)
0x00000005 B60007 invokevirtual
execute an action depending (#7) java/io/PrintStream.println
on the value of the opcode 0x00000008 B1 return
Exception Handler Entries=0
} while (there is more to do); Attribute="LineNumberTable"(#17)
Length=6
Each VM is machine dependent Entry Count=1
Start=0x00000000 Line Number=5
Just in Time (JIT) code generator Attribute="LocalVariableTable"(#15)
can improve the performance of Length=12
Entry Count=1
Java Applications by compiling Start=0x00000000 Effective Length=9
Slot=0
bytecode to machine code before Name="args"(#35)
execution Signature="[Ljava/lang/String;"(#36) 7
javac java
Text Editor
Compiler Interpreter
Bytecodes
Source Code
myfile.class
myfile.java
Run Applet
afile.html
appletviewer
4
4
CSD Univ. of Crete Fall 2012
10
5
5
CSD Univ. of Crete Fall 2012
Java Applets
Web browser
Java
interpreter
Local computer
11
Java History
1990 The group was code named The
Patrick Naughton threatens to leave Sun Green Project
Scott McNeally CEO of Sun asks Goal was to develop a system
Naughton to write up list of problems that was compact and simple -
with Sun and what should be done driven by consumer electronics
• “Tell me what you would do if you 1991
were God.” Green was a solution looking for
Naughton’s suggestions a problem
• hire an artist to pretty up Sun’s Gosling realised that C++ wasn’t
uninspired interfaces reliable enough for communica-
ting consumer electronics and
• pick a single programming toolkit developed the language Oak
• focus on a single windows Naughton was interested in the
technology user interface and developed
• lay off just about everybody in the multimedia animations to work
existing windows group with Oak
McNeally agrees to Naughton’s The Green team’s ambition was
suggestions and gives Naughton, to build a device that was an
James Gosling and Mike Sheridan $1 interface to cyberspace in colour
million and one year to deliver and 3-D written in Oak 12
6
6
CSD Univ. of Crete Fall 2012
Java History
1992 While Naughton worked on the next
Demoed first device made of bits killer-app, WebRunner, a web
and pieces from handheld TVs and browser
Nintendo GameBoys called *7 1995
(Star 7) a wireless PDA Oak is renamed Java and is posted
to the web including source code
Sun set up wholly owned
Fearing Java’s popularity Microsoft
subsidiary as FirstPerson Inc. announces Blackbird
1993 First demo of WebRunner displaying
Oak was used to create a set-top a web page as well as an Applet
box for interactive TV Marc Andreessen licences Java for
use in the Netscape Navigator web
Marc Andreessen and Eric Bina browser
from NCSA release the first version 1996 - JavaTM 1.0
of the Mosaic web browser 1997 - JavaTM 1.1
1994 1998 - JavaTM 1.2 - aka Java 2 Platform
With no shipping product the focus 2000 - JavaTM 2 Rel.1.3Stand.Ed.(J2SE)
moved to personal computers 2002 - JavaTM 2 Rel. 1.4 J2SE
Gosling went back to reprogram 2004 - JavaTM 2 Rel. 1.5 - aka Java 5 Pl.
Oak for the internet 2006 - JavaTM 2 Rel. 1.6 - aka Java 6 Pl.
13
Versions of Java
Java 1.0 Java 1.1 Java 1.2 Java 1.3 Java 1.4 Java 1.5
8 packages 23 packages 59 packages 77 packages 103 packages 131 packages
212 classes 504 classes 1520 classes 1595 classes 2175 classes 2656 classes
New Events JFC/Swing JNDI Regular Exp javax.activity,
Logging javax.
Inner class Drag and Java Sound Assertions
NIO management
Drop java.nio, javax.imageio,
Object Timer
Serialization Java2D javax.net, javax.print,
javax.security, org.w3c
Jar Files CORBA
javax.naming, javax.sound,
International javax.transaction
Reflection
JDBC javax.accessibility, javax.swing, org.omg
RMI
7
7
CSD Univ. of Crete Fall 2012
15
8
8
CSD Univ. of Crete Fall 2012
18
9
9
CSD Univ. of Crete Fall 2012
Programs
Types
Vassilis Objects float Salary = 78234.0F;
the int Age = 32;
Teacher
Person
Attributes:
Name
Age
Grade Salary
Hire
Students
Vassilis
of CS252 Methods:
at CSD Grade();
IncreaseSalary();
Bits (the int 32)
0000 0000 0000 0000 0000 0000 0010 0000
19
10
10
CSD Univ. of Crete Fall 2012
Java Program
Class MyProgram { Class B {
main() Class A { methodB1()
{ methodA1() {
statement1 { }
statement2 statement1 methodB2()
statement3 statement2 {
Q statement3 }
} Q methodB3()
method1() } }
{ methodA2()
Q {
Q Class C {
} Q
method2() }
} }
}
21
11
11
CSD Univ. of Crete Fall 2012
A Program
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
23
Functions
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
24
12
12
CSD Univ. of Crete Fall 2012
Functions
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
25
Functions
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
(Almost) every Java program must have one and only one main()
function
26
13
13
CSD Univ. of Crete Fall 2012
Functions
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
Statements
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
28
14
14
CSD Univ. of Crete Fall 2012
Java Separators
29
White Spaces
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
Spaces, blank lines, and tabs are collectively called white space and are
used to separate words and symbols in a program
Extra white space is ignored, so a valid Java program can be formatted
in many different ways
Programs should be formatted to enhance readability, using consistent
indentation 30
15
15
CSD Univ. of Crete Fall 2012
Objects
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
31
Strings
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
32
16
16
CSD Univ. of Crete Fall 2012
Preprocessor Directives
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
33
Preprocessor Directives
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
34
17
17
CSD Univ. of Crete Fall 2012
Preprocessor Directives
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
void indicates that this function does not return a value to the object
that calls it
35
Preprocessor Directives
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
args can be used in the main function to pass parameters from the
operating system command line
36
18
18
CSD Univ. of Crete Fall 2012
Comments
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
37
Comments
19
19
CSD Univ. of Crete Fall 2012
Java Identifiers
39
Java Identifiers
Identifiers are the words a programmer uses in a program
Most identifiers have no predefined meaning except as specified by
the programmer
Rules...
An identifier can be made up of letters, digits, the underscore
character (__), and the dollar sign ($
$)
The first character must be any non-digit from the Unicode standard
Subsequent characters may include digits
Avoid using underscore and $ for the first character
Java is case sensitive, therefore Total and total are different
identifiers
Three types of identifiers:
words that we make up ourselves
words that are reserved for special purposes in the language
words that are not in the language, but were used by other
programmers to make the library 40
20
20
CSD Univ. of Crete Fall 2012
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
42
21
21
CSD Univ. of Crete Fall 2012
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
43
/* Display a message */
class hello {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
44
22
22
CSD Univ. of Crete Fall 2012
46
23
23
CSD Univ. of Crete Fall 2012
System.out.println(“Hello World!”)
Information provided
object method
to the method
(parameters)
47
48
24
24
CSD Univ. of Crete Fall 2012
50
25
25
CSD Univ. of Crete Fall 2012
Data Types
A data type is defined by a set of values and the operators you can
perform on them
Each value stored in memory is associated with a particular data type
islowercase
isuppercase
Character
isdigit
26
26
CSD Univ. of Crete Fall 2012
0x0021 … 0x3041 …
0x05B0 …
0x77CD …
…
54
27
27
CSD Univ. of Crete Fall 2012
0x21 …
…0xB9
55
28
28
CSD Univ. of Crete Fall 2012
Declaration Declaration
Give a type and a name
Instantiation Instantiation
Give a name a location in memory
• Automatic with primitives
Assignment Assignment
Set or change the value
Initialization
Variable Declaration
The Java programming language is a strongly typed language
every variable and every expression has a type that is known at
compile time (as opposed to runtime)
Syntax
58
29
29
CSD Univ. of Crete Fall 2012
Variable Declaration
1006 Decimal
char ch; 1007
short number; 1008
... 1009 72 ch
ch = 'H'; 100A 100 number
number = 100 100B
... 100C
100D
59
Variable Declaration
1006 Binary
char ch; 1007
short number; 1008
... 1009 01001000 ch
ch = 'H'; 100A 01100100 number
number = 100 100B
... 100C
100D
60
30
30
CSD Univ. of Crete Fall 2012
Variable Declaration
1006 Hex
char ch; 1007
short number; 1008
... 1009 48 ch
ch = 'H'; 100A 64 number
number = 100 100B
... 100C
100D
61
31
31
CSD Univ. of Crete Fall 2012
Assignment Conversions
Assignment conversion occurs when a value of one type is assigned to
a variable of another
Only widening conversions can happen via assignment
double d = 123.45F;// OK
float f = 123.45; // Not OK
byte b = 128; // Not OK
long l = 123; // OK Floating point
constants are assumed
to be double, by
default! 63
Arithmetic Promotions
int i=37;
double x=27.475;
System.out.println(“i+x=“+(i+x));
Output:
i+x=64.475
64
32
32
CSD Univ. of Crete Fall 2012
double None
float double
long float, double
int long, float, double
char int, long, float, double
short int, long, float, double
byte short, int, long, float, double
boolean None
65
Output:
66
33
33
CSD Univ. of Crete Fall 2012
67
byte b = (byte) a;
0000000011111010
Discarded Bits
68
34
34
CSD Univ. of Crete Fall 2012
-1 in decimal
byte b = (byte) c;
0000000011111111
Discarded Bits
69
Output:
70
35
35
CSD Univ. of Crete Fall 2012
Output:
71
72
36
36
CSD Univ. of Crete Fall 2012
The null type has one value, the null reference, represented by the
literal null,
null which is formed from ASCII characters
Usually the null type is ignored and we pretend that null is merely a
special literal that can be of any reference type
73
74
37
37
CSD Univ. of Crete Fall 2012
75
76
38
38
CSD Univ. of Crete Fall 2012
Java Operators
77
What’s an Operator?
Operators are tokens that trigger some computation when applied to
variables and other objects
Arithmetic, logical, and bit-level operators
Class access operators
The Java operators are formed from ASCII characters:
() / < ^
++ % > |
-- + <= &&
! - >= ||
~ << == ?:
instance of >> != =
* >>> & op= 78
39
39
CSD Univ. of Crete Fall 2012
Unary Operators
79
Unary Operators
Operator
80
40
40
CSD Univ. of Crete Fall 2012
Unary Operators
☺ x
81
Unary Operators
☺ x
Operand
82
41
41
CSD Univ. of Crete Fall 2012
Unary Operators
☺ x
x ☺
83
Unary Operators
Group expression
()
Unary plus
+
Unary minus
-
84
42
42
CSD Univ. of Crete Fall 2012
Unary Operators
Bitwise complement
~
Logical negation
!
Pre- or Post-increment
++
Pre- or Post-decrement
--
85
When used alone in a statement, the prefix and postfix forms are basically
equivalent
That is, count++; is equivalent to ++count;
86
43
43
CSD Univ. of Crete Fall 2012
Unary Operators
i = 0; i 1
count = 2 + i++; count 2
i = 0; i 1
count = 2 + ++i; count 3
87
Binary Operators
88
44
44
CSD Univ. of Crete Fall 2012
Binary Operators
x ☺ y
89
Binary Operators
Operator
x ☺ y
Operand Operand
90
45
45
CSD Univ. of Crete Fall 2012
Binary Operators
91
Binary Operators
= Assignment
92
46
46
CSD Univ. of Crete Fall 2012
Binary Operators
= Assignment
93
Binary Operators
= Assignment
94
47
47
CSD Univ. of Crete Fall 2012
Binary Operators
= Assignment
Not an
LVALUEcat = dog + 1; legal
95
Binary Operators
= Assignment
1 + cat = dog;
96
48
48
CSD Univ. of Crete Fall 2012
Binary Operators
= Assignment
Not an
LVALUE
cat = dog + 1; legal
97
Binary Operators
= Assignment
This is an
LVALUE
cat = dog + 1; legal
1 + (cat = dog)
dog); Not what
you want!
98
49
49
CSD Univ. of Crete Fall 2012
Binary Operators
class Test {
public static void main(String[] args) {
int result, val_1, val_2;
result = (val_1 = 1) + (val_2 = 2);
System.out.println("val_1 = "+val_1);
System.out.println("val_2 = "+val_2);
System.out.println("result = "+result);
}
val_1 = 1
} val_2 = 2
result = 3
99
Binary Operators
Expressions involving only integers are evaluated using integer
arithmetic
float result;
int i,j; result 2.0
i=25; j=10;
result = i/j;
100
50
50
CSD Univ. of Crete Fall 2012
Binary Operators
Expressions involving only integers are evaluated using integer
arithmetic
float result;
int i,j; result 2.5
i=25; j=10;
result =
(float) i/j;
101
51
51
CSD Univ. of Crete Fall 2012
Binary Operators
Assignment
Assign sum
+=
Assign difference
-=
Assign product
*=
Assign quotient
/=
Assign remainder
%=
103
Binary Operators
Assignment
Compound operators provide a convenient shorthand
int i;
i = i + 5;
i += 5;
104
52
52
CSD Univ. of Crete Fall 2012
Binary Operators
Relational
Less than
<
Greater than
>
Less than or equal to
<=
Greater than or equal to
>=
105
Binary Operators
Relational
Equal to
= =
Not equal to
!=
106
53
53
CSD Univ. of Crete Fall 2012
Equality Testing
Identity or simple equality
Two variables refer to the same object or String
Value equality
Two object variables have the same contents
Test for identity using the equality operators
For value equality use the equals() method defined on Java Objects
Example:
if ( nameString.equals(“Hi”) ) { }
107
108
54
54
CSD Univ. of Crete Fall 2012
109
Binary Operators
Logical
Logical AND
&&
Logical OR
||
110
55
55
CSD Univ. of Crete Fall 2012
Binary Operators
Expressions connected by && and || are evaluated from left to right
111
Binary Operators
Bitwise
Shift left
<<
Shift right
>>
Shift right with zero extension
>>>
One’s complement
~
Bitwise AND
&
Bitwise XOR
^
Bitwise OR
| 112
56
56
CSD Univ. of Crete Fall 2012
Binary Operators
Bitwise
The right sift The right sift operator
operator >> >>> does not preserves
preserves the the sign but rather fills
sign the vacated positions
with zeros
byte b = 3; // 00000011 in binary (byte is 8 bits)
b >> 1; // 00000001 in binary, 1 in decimal
b << 1; // 00000110 in binary, 6 in decimal
b = -3; // 11111101 in 2’s complement
b >> 1; // 11111110 in binary, -2 in decimal
b >>> 1; // 01111110 in binary, 126 in decimal
113
Ternary Operators
☺
114
57
57
CSD Univ. of Crete Fall 2012
Ternary Operators
Operator
☺
115
Ternary Operators
x ☺ y z
116
58
58
CSD Univ. of Crete Fall 2012
Ternary Operators
Conditional
“if a then x, else y”
a?x:y
result = (x<y) ? x : y;
117
Mixing Operators
class Test {
public static void main(String[] args) {
char cv;
@ int iv1 = 64;
64
cv = (char) iv1;
System.out.println("cv:" + cv);
System.out.println("iv1:" + iv1);
}
} cv:@
iv1:64
118
59
59
CSD Univ. of Crete Fall 2012
Mixing Operators
class Test {
public static void main(String[] args) {
double fv1, fv2;
Floating point
int iv1 = 123;
constants are
fv1 = iv1/50; assumed to be
fv2 = iv1/50.0; double, by default!
System.out.println("fv1:" + fv1);
System.out.println("fv2:" + fv2);
}
} fv1:2.0
fv2:2.46
119
Operator Precedence
120
60
60
CSD Univ. of Crete Fall 2012
multiplicatative operators * / %
Lower
additive operators + -
assignment operators =
121
Operators Associativity
( ) ++ (postfix) -- (postfix) Left to right
+ (unary) - (unary) ++ (prefix) -- (prefix) ! Right to left
* / % Left to right
+ - Left to right
< <= > >= Left to right
= = != Left to right
&& Left to right
|| Left to right
= += -= *= /= etc. Right to left
122
61
61
CSD Univ. of Crete Fall 2012
Operator Precedence
Expression Result
2 + 3 * 4 / 2 8
3 * 13 + 2 41
(3 * 13) + 2 41
3 * (13 + 2) 45
4 * (11 - 6) * (-8 + 10) 40
(5 * (4 - 1)) / 2 7
5 + 12 / 5 - 10 % 3 6
3 1 4 2 123
124
62
62
CSD Univ. of Crete Fall 2012
The IF Statement
if (condition) { false
condition
statement(s);
} true
If the boolean condition is
true, the statement is statement
executed; if it is false, the
statement is skipped
Selection statements
provides basic decision
making capabilities
125
The IF Illustrated
The if statement
Need a ONE WAY
refreshing if ( youNeedALift( ) )
lift?
{
tryJavaMatic(chickenSoup);
}
JavaMatic
126
63
63
CSD Univ. of Crete Fall 2012
A WarningQ
WRONG! CORRECT!
if( i == j ) if( i == j ) {
if ( j == k ) if ( j == k )
System.out.print( System.out.print(
“i equals k”); “i equals k”);
else }
System.out.print( else
“i is not equal to System.out.print(“i
j”); is not equal to j”);
// Correct!
128
64
64
CSD Univ. of Crete Fall 2012
65
65
CSD Univ. of Crete Fall 2012
The body of a while loop must eventually make the condition false
If not, it is an infinite loop, which will execute until the user
interrupts the program
132
66
66
CSD Univ. of Crete Fall 2012
false
133
Jumbo's
Jumbalaya
(Serves 1) do
144 Crawdads
1 Pint Pepper Sauce
{
12 Ripe Limes
1 Box black licorice
AddSalt( );
Combine ingredients in Taste( );
small saucepan.
Simmer over low heat } while ( needsMoreSalt( ));
for 6 hrs.
Salt to taste
Serve hot
Yes 134
67
67
CSD Univ. of Crete Fall 2012
ONE WAY
Need a No
refreshing lift?
JavaMatic
136
68
68
CSD Univ. of Crete Fall 2012
137
69
69
CSD Univ. of Crete Fall 2012
Java C++
Single inheritance Multipleinheritance
C data type not supported C data type supported
• struct, union, pointer
Command line arguments Command line arguments
• args • argc, argv
String String
• First-class object • character array
Exception handling Exception handling
• Try-Catch-Finally • Try-Catch
Garbage collection No garbage collection
No operator overloading Operator overloading
139
Java Overview
140
70
70