Title: Lecture 5 Java Introduction
1Lecture 5Java Introduction
- CPE 401 / 601Computer Network Systems
slides are modified from Ricky Sethi
2So what the heck is Java (besides coffee, that
is)?
- A programming language.
- Syntax and constructs are very similar to C
- A virtual platform
- Java Virtual Machine is a software machine or
hypothetical chip - Since its virtual, it can be implemented on
any hardware - Cross-platform distribution achieved via .class
binary file of bytecodes (instead of
machine-dependent machine code) ? Write Once, Run
Anywhere - A class library
- Standard APIs for GUI, data storage, processing,
I/O, and networking.
3Getting Java Brewing
- Download the latest Java SDK from
http//java.sun.com - The SDK is a command-line based set of tools
- A Text Editor
- Web-browser thats java-enabled (optional)
- Some introductory links/guides/tutorials
- http//developer.java.sun.com/developer/onlineTrai
ning/Programming/BasicJava1/compile.html - http//www.horstmann.com/ccc/c_to_java.pdf
- http//www.csd.uu.se/datalogi/cmtrl/oopj/vt-2000/s
lides/OOPJ-1-04.pdf
4Mechanics of Writing Java Programs
- Create a Java source file.
- Must have the .java extension and contain only
one public class. - Compile the source file into a bytecode file.
- The Java compiler, javac, takes your source file
and translates its text into instructions that
the Java Virtual Machine (Java VM) can
understand. The compiler puts these instructions
into a .class bytecode file. - Run the program contained in the bytecode file.
- The Java VM is implemented by a Java interpreter,
java. This interpreter takes your bytecode file
and carries out the instructions by translating
them into instructions that your computer can
understand.
5Putting it all together
public class Hello public static void
main(String args)
System.out.println(Hello, world!)
- Put in Hello.java
- Compile with javac Hello.java
- Creates Hello.class
- Run with java Hello
6Applications vs. Applets
- A Java application
- Is a standalone program
- Is interpreted by the Java Virtual Machine and
run using the java command - Contains a main() method.
- A Java applet
- Runs within a Java-enabled Web browser
- extends the Applet or JApplet class (Inheritance)
- Contains an init() or a paint() method (or both).
- To create an applet, you'll perform the same
basic steps - Create a Java source file (NameOfProgram.java)
and an HTML file (NameOfHTMLFile.html) - Compile the source file (NameOfProgram.class)
- Run the program (either using java NameOfProgram
or appletviewer NameOfHTMLFile.html)
7Java notes for C programmers
- Everythings an object
- Every object inherits from java.lang.Object
- No code outside of the class definition!
- No global variables (use static variables
instead) - Single inheritance only
- Instead, implement interfaces
- All classes are defined in .java files
- One top level public class per file
- The file has to have the same name as the public
class! - Syntax is similar (control structures are very
similar). - Primitive data types are similar
- But a bool is not an int
- To print to stdout, use System.out.println()
8Why Java?
- Network Programming in Java is very different
than in C/C - much more language support
- Networking is at the core of the language
- well defined error handling
- no global variables
- no struct, union types, gotos, enums, bitfields,
typedefs - no pointers! (garbage collection)
- Threads are part of the language.
- some support for common application level
protocols (HTTP).
9Requisite First Program (Application Version)
- Put in HelloWorld.java
- public class HelloWorld
- public static void main(String args)
- System.out.println("Hello World")
-
-
10Compiling and Running
compile
HelloWorld.java
javac HelloWorld.java
source code
HelloWorld.class
run
java HelloWorld
bytecode
11So whats going on? The Java bytecode and
interpreter at work!
- Bytecode is an intermediate representation of the
program (the class file) - Think of it as the machine-code for the Java
Virtual Machine - The Java interpreter (java) starts up a new
Virtual Machine - The VM starts executing the users class by
running its main() method
12Requisite First Program (Applet Version)
- Put in HelloWorld.java
- import java.awt.Graphics
- public class HelloWorld extends
java.applet.Applet - public void paint(Graphics g)
- g.drawString("Hello World, 35, 15)
-
-
- Put in test.html
- lthtmlgt
- lttitlegtTest the appletlt/titlegt
- ltbodygt
- lth3gtTest the appletlt/h3gt
- ltapplet codeHelloWorld.class height200
width300gt - lt/appletgt
- lt/bodygtlt/htmlgt
13Java Language Basics
not an int!
- Data types same as in C (except bool)
- bool,char,byte,short,int,long,float,
double,string, etc. - Operators (same as C)
- Assignment , , -, ,
- Numeric , -, , /, , , --,
- Relational . !, lt, gt, lt, gt,
- Boolean , , !
- Bitwise , , , , ltlt, gtgt,
- Control Structures ? more of what you expect
- conditional if, if else, switch
- loop while, for, do
- break and continue
14Classes, References, Packages
- Classes and Objects
- All Java statements appear within methods, and
all methods are defined within classes. - Java classes are very similar to C classes
(same concepts). - Instead of a standard library, Java provides a
lot of Class implementations or packages - What are packages?
- You can organize a bunch of classes and
interfaces into a package (or library of classes) - defines a namespace that contains all the
classes. - Use the import keyword to include the packages
you need - import java.applet.
- You need to use some java packages in your
programs - java.io (for Files, etc.), java.util (for
Vectors, etc.) - References
- No pointers ? everythings a reference!
- classes, arrays
15Exceptions
- When a program carries out an illegal action, an
exception is generated. - Terminology
- throw an exception signal (in the method header)
that some condition or error has occurred but we
want to pass the buck and not deal with it. - catch an exception deal with the error (or
whatever) ourselves inside the function/method. - Catch it using a try/catch block (next slide).
- In Java, exception handling is necessary
- forced by the compiler ? compilation errors!
- Except for RunTimeExceptions
16Try/Catch/Finally
- try
- // code that can throw an exception
- catch (ExceptionType1 e1)
- // code to handle the exception
- catch (ExceptionType2 e2)
- // code to handle the exception
- catch (Exception e)
- // code to handle other exceptions
- finally
- // code to run after try or any catch
This block is always run
17Exception Handling
- Exceptions take care of handling errors
- instead of returning an error, some method calls
will throw an exception. - Can be dealt with at any point in the method
invocation stack. - But if no method in the hierarchy handles it,
results in an unchecked exception which generates
a compiler error (unless its a RunTimeException) - Forces the programmer to be aware of what errors
can occur and to deal with them.
18Defining a Class
- One top level public class per .java file.
- Typically end up with many .java files for a
single program with at least one containing a
static public main() method (if theyre
applications). - Class name must match the file name!
- The compiler/interpreter use class names to
figure out what the file name is. - Classes have these three features
- A constructor thats used to allocate memory for
the object, initiailize its elements, and return
a reference to the object - Methods (function members)
- Fields (data members)
19A Sample Class
- public class Point
- public Point(double x, double y)
- this.x x this.yy
-
- public double distanceFromOrigin()
- return Math.sqrt(xxyy)
-
- private double x,y
20Objects and new
- You can declare a variable that can hold an
object Point p - But this doesnt create the object! You have to
use newPoint p new Point(3.1,2.4) - new allocates memory and the garbage collector
reclaims unused memory
21Using Java objects
- Just like C
- object.method() or object.field
- BUT, never like this (no pointers!)
- object-gtmethod() or object-gtfield
- Event driven model
- Objects register to receive (and respond to)
certain messages like button presses, mouse
clicks, etc. (e.g., mouseUp(), mouseDown(),
keyUp(), keyDown())
22Strings are special
- You can initialize Strings like this
- String blah "I am a literal "
- Or this ( String operator)
- String foo "I love " CET375"
- Or this ( new operator)
- String foo new String(Yummy FooBars!)
23Arrays
- Arrays are supported as a second kind of
reference type (objects are the other reference
type). - Although the way the language supports arrays is
different than with C, much of the syntax is
compatible. - however, creating an array requires new
- Index starts at 0.
- Arrays cant shrink or grow.
- e.g., use Vector instead.
- Each element is initialized.
- Array bounds checking (no overflow!)
- ArrayIndexOutOfBoundsException
- Arrays have a .length
- You can use array literals like C/C (no need
for new keyword)
24Array Examples
- int x new int1000
- byte buff new byte256
- float mvals new float1010
- int values
- int total0
- for (int i0iltvalue.lengthi)
- total valuesi
-
- String names Joe, Sam
25Reference Types
- Objects and Arrays are reference types
- Primitive types are stored as values
- Reference type variables are stored as references
(pointers that we cant mess with)
int x3 int yx Point p new
Point(2.3,4.2) Point t p
There are two copies of the value 3 in memory
There is only one Point object in memory!
26Passing arguments to methods
- Primitive types the method gets a copy of the
value. Changes wont show up in the caller ?
Pass by value - Reference types the method gets a copy of the
reference, the method accesses the same object?
Pass by reference - There is no pass by pointers!
27Comparing Reference Types
- Comparison using means
- Are the references the same?
- Do they refer to the same object?
- Sometimes you just want to know if two
objects/arrays are identical copies. - Use the .equals() method
- You need to write this for your own classes!
- All objects and arrays are references!
28Inheritance
- Use the extends keyword to inherit from a super
(or parent) class - No multiple inheritance
- Use implements to implement multiple interfaces
(abstract, virtual classes) - Use import instead of include (not exactly the
same but pretty close) to include packages
(libraries)
29Concurrent Multi-threaded Programming
- Java is multithreaded!
- Threads are easy to use.
- Two ways to create new threads
- Extend java.lang.Thread
- Override run() method.
- Implement Runnable interface
- Include a run() method in your class.
- Usually, youll implement the Runnable interface
- How to implement the Runnable interface
- Add a public void start() function
- This is where youll initialize the thread and
start() it - Add a public void stop() function
- This is where youll set the boolean stopFlag to
true - Add a public void run() function
- This is where youll call repaint() to paint each
new frame and handle any synchronized variables
or methods
30The synchronized Statement
- Instead of mutex (a binary semaphore), use
synchronized - synchronized ( object )
- // critical code here
-
- Also, declare a method as synchronized
- synchronized int blah(String x)
- // blah blah blah
-
- Can also use wait() and notify() to put threads
on hold and wake them up again (e.g., to
implement a pause or suspend feature) - Must be called within a synchronized block
31Using Documentation Comments
- Documentation comments are delimited by / and
/ - javadoc automatically generates documentation
- Copies the first sentence of each documentation
comment to a summary table - Write the first sentence with some care!
- For each method/class, supply
- _at_param followed by the parameter name and a short
explanation - _at_return followed by a description of the return
value - _at_author for author info, etc.
- Need to use javadoc author for this
32javadoc
Must come immediately before the class, method,
etc.
- The Java Standard calls for every class, every
method, every parameter, and every return value
to have a comment - Write the method comments first!
- If you cant explain what a class or method does,
you arent ready to implement it! - How to create HTML documentation
- Type javadoc .java in the directory containing
your source code - This produces one HTML file for each class and an
index.html file - Documenation is together with code!