Lecture 11
Lecture 11
1
What is Java?
• A programming language.
• A platform
– A virtual machine (JVM) definition.
– Runtime environments in diverse
hardware.
• A class library
– Standard APIs for GUI, data storage,
processing, I/O, and networking.
2
Why Java?
4
More for C++ folks
5
First Program
6
Compiling and Running
javac HelloWorld.java
HelloWorld.java
compile
run
source code
bytecode
7
Java bytecode and interpreter
• bytecode is an intermediate
representation of the program (class).
9
The Language
• Data types
• Operators
• Control Structures
• Classes and Objects
• Packages
10
Java Data Types
11
Other Data Types
12
Type Conversions
• conversion between integer types and
floating point types.
– this includes char
• No automatic conversion from or to the
type boolean
• You can force conversions with a cast –
same syntax as C/C++.
int i = (int) 1.345;
13
Operators
15
Exceptions
• Terminology:
– throw an exception: signal that some
condition (possibly an error) has occurred.
– catch an exception: deal with the error (or
whatever).
18
Concurrent Programming
• Java is multithreaded!
– threads are easy to use.
• Two ways to create new threads:
– Extend java.lang.Thread
• Overwrite “run()” method.
– Implement Runnable interface
• Include a “run()” method in your class.
• Starting a thread
– new MyThread().start();
– new Thread(runnable).start();
19
The synchronized Statement
• Java is multithreaded!
– threads are easy to use.
• Instead of mutex, use synchronized:
synchronized ( object ) {
// critical code here
}
20
synchronized as a modifier
21
Classes and Objects
22
Defining a Class
23
Sample Class
public class Point {
public double x,y;
public Point(double x, double y) {
this.x = x; this.y=y;
}
public double distanceFromOrigin(){
return Math.sqrt(x*x+y*y);
}
}
24
Objects and new
25
Using objects
26
Strings are special
27
Arrays
28
Array Examples
29
Notes on Arrays
• index starts at 0.
• arrays can’t shrink or grow.
• each element is initialized.
• array bounds checking (no overflow!)
– ArrayIndexOutOfBoundsException
• Arrays have a .length
30
Array Example Code
int[] values;
int total=0;
31
Array Literals
32
Reference Types
33
Primitive vs. Reference Types
int x=3;
There are two copies of
int y=x; the value 3 in memory
35
Example
int sum(int x, int y) {
x=x+y;
return x;
}
void increment(int[] a) {
for (int i=0;i<a.length;i++) {
a[i]++;
}
}
36
Comparing Reference Types
37
Packages
38
Importing classes and packages
• Instead of #include, you use import
• You don’t have to import anything, but
then you need to know the complete
name (not just the class, the package).
– if you import java.io.File you can
use File objects.
– If not – you need to use java.io.File
objects.
39
Sample Code
40
End of Lecture
• Next Lecture
– More Java programming Techniques
– Java Applets
41