Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Java Lecture 1
Introduction
John Black
CS 425
Overview
• Java is:
–
–
–
–
–
Like C/C++
Object-Oriented
Interpreted
Portable
Multi-Threaded
Types of Java Programs
• Standalone (has main())
• Applet
– A dynamically loaded class (so no main())
– Special environment (browser or applet viewer)
– Restricted (memory, disk access, screen area)
• Servlet
– Java program which runs on Server
– Dynamically loaded (so no main() again)
Standalone Java Program
• Collection of “class” files
– Each class file has one public class
– This class is the same as the filename of this
class file
– Exactly one file contains main()
– Prototype for main() is
public static void main(String args[])
(You can’t omit the parameters or the interpreter will
consider this a different method!!)
More on main()
• Notice that main has type void
– Cannot “return(val)” from main()
– Use System.exit(val) instead
• Interpreter runs until main() exits and then
waits for all threads to complete before
terminating
Example: echo.java
echo.java:
public class echo {
public static void main(String argv[]) {
for (int i=0; i < argv.length; i++)
System.out.print(argv[i] + “ “);
System.out.print(“\n”);
System.exit(0);
}
}
You can find this example on the web page.
Compiling and Running
• Say we have this echo class in a file called
echo.java
% javac echo.java
// compiles
% ls echo.class
// is the class file there?
echo.class
% java echo hello world // now run it!
hello world
%
The CLASSPATH variable
• All public classes are in different files, so
how does the compiler find them?
– class file containing main() must import them
import echo;
– javac looks in directories indicated in
CLASSPATH environment variable
ex. % setenv CLASSPATH /home/jrb/java/classes:.
set CLASSPATH C:\java\classes;.
CLASSPATH (cont.)
• If javac doesn’t find class file, it makes one
– If echo.class doesn’t exist and echo.java does,
javac compiles echo.java for you
• At run-time classes must be available also
% java echo
// looks for echo.class in
// CLASSPATH list
• All classes used must be available for java
interpreter at run-time
Packages
• A package is a set of associated classes
– Package names are words separated by dots
ex: java.lang.String.substring()
package
class
method
– System classes (like java.lang.String) are
automatically found by the compiler/interpreter
– User-defined packages must be in a directory
within CLASSPATH following package name
Packages (cont.)
– Ex: cs425.std.echo
must be in a directory cs425/std rooted in some
CLASSPATH directory
• The “package” statement must appear first
– The package statement tells the compiler which
package this class belongs to
– If no package statement, classes are placed in a
default package
Packages (cont.)
• Semantics of Packages
– A class can access any other class in the same
package (public or non-public)
– A class can access any non-private fields or
methods in the other classes of the package
• Let’s look at an example.
The import Statement
• import provides a shorthand for class names
• Details:
– must appear after optional “package” statement
– has two forms:
• import utils.echo; // import just this class
• import utils.*;
// import all classes in this pkg
– let’s you refer to classes directly by class name
– import java.lang.*; is automatic
A Brief Tour of java.lang
• java.lang is the package containing the
“core classes” of the language (kind of like
the stdlib of C)
Contains routines to manipulate: Boolean,
Character, Numbers, Strings, has Math routines,
Threading library, Exception Handling
• Check the JDK 1.1 API doc for details
Storage Classifiers for Classes
• All classes in a package are visible to all others in
that same package. You can’t change this!
• Other than “public” your only other option for
declaring a class is <nothing>; this means the class
is visible only within the same package.
• Only one class may be declared public in a given
java source file.
Visibility of Class Members
• Storage classes for class members (ie,
variables and methods)
– private: only members of the same class
– package: only classes within the same package
(this is the default)
– protected: only classes within the same package
or any subclass of host class
– public:
visible everywhere
Comments and Preprocessor
• Three comment styles, but we’ll use only 2:
– /* comment */
– // comment
nesting not allowed
just like C++
• There is no preprocessor
– No #include, #define, #if, etc.
Declaring Constants
• Use “static final” to declare constants
– ex: public final class Math {
public static final double PI = 3.141592653589…;
}
• Always use all CAPS for constants
• (Note: we can use Math.PI instead of
java.lang.Math.PI. Why?)
Primitive Data Types
Type
boolean
char
byte
short
int
long
float
double
Contains
true/false
Unicode
Signed int
Signed int
Signed int
Signed int
IEEE 754
IEEE 754
Default
false
\u0000
0
0
0
0
0.0
0.0
Size
1 bit
16 bits
8 bits
16 bits
32 bits
64 bits
32 bits
64 bits
Primitive Data Types (cont.)
• boolean type; assume int i and boolean b
– i = (i != 0);
– i = (i != 0) ? 1 : 0;
– b = (i != 0);
// illegal!
// that’s more like it
// that’s ok too
• char type
– just like C: ‘h’ is a char
– the usual escape codes: ‘\n’, ‘\”’, etc.
Primitive Data Types (cont.)
• Integer Types
– All integer types are signed
– long literals are signaled by appending l or L
• Floating Point Types
– for float literals append f or F
– for double literals append d or D
The String type
• Unlike C, “String” is a supplied type in Java
– Note that it is not a primitive type, but has extra
support nonetheless (for convenience)
– Note the capitalization: String is a class
(What package is the class in?)
– String literals are enclosed in quotes: “hi”
(This automatically creates a String object.)
Reference Data Types
• If it’s not primitive, it’s an object or array
– Passing a primitive type is by value
int i = 2;
j = i; j = 3;
// i = = 2, j = = 3
– Passing a reference type is by reference
Button p, q; p = new Button();
q = p;
// q refers to same object as p
p.setLabel(“Ok”);
String s = q.getLabel();
// s contains “Ok”
Pop Quiz on Object References
• Does this work?
public void swap(Object a, Object b) {
Object temp = a;
a = b;
b = temp;
}
• Does Not Work! Each parameter is passed
in as the value of a reference, these values
are rearranged with no outside effects!
Misc. Reference Issues
• If a and b are objects, what does a = = b
mean? (Use strcmp() or equals() instead)
• How do you copy objects (no copy
constructors in java)
• No pointers at all! (Fewer bugs!?)
• null is a reserved keyword, not a value
which is #defined to 0
A First Look at Objects
• Object Creation:
– Window w;
// does NOT create an object
– Window w = new Window();
// this does
– Special shortcut for Strings:
String s = “This creates a string”;
// The above is shorthand for
// String s = new String(“This creates a string”);
• Object members accessed with ‘.’ operator
What about Arrays?
• Arrays are objects, but with special syntax:
– byte b[] = new byte[10]; // no constructor
// Elements initialized to default for this datatype
– char c[] = {‘h’,’i’};
// initialize to ‘h’ ‘i’
• In both cases, array is dynamically allocated
• Initialization values need not be constant
since array is allocated and initialized at
runtime
More on Arrays
• Access array elements with arr[x] as usual
– Bounds-checking done at runtime; is this good?
– To get an array’s length, use arr.length
(“length” is the only field allowed for array objects
and is declared “final” so you cannot change it)
• Quiz: what does this declaration do?
byte[] row, column, matrix[];
More on Strings
• The String class is immutable
– Use class StringBuffer if you want to change
the contents of a string:
StringBuffer sb = new StringBuffer(“Hi”);
• Strings are NOT arrays (so don’t use s[x])
• String concatenation is done with +
System.out.println(“hi there, “ + name);
Common String Methods
Assume s and t are Strings and i and j are ints;
(strings indices start at 0)
s.length()
s.charAt(i)
s.equals(t)
s.compareTo(t)
s.indexOf(t)
s.lastIndexOf(t)
s.substring(i)
s.substring(i,j)
// # chars in string
// return character at index i of s
// returns true iff s and t are equal
// return strcmp(s,t) (ie, -1, 0, 1)
// return index of first t within s
// return index of last t within s
// return String from index i to end, incl
// return String from index i to j-1, incl
Operators
• Basically the same as C; table on the web
– + is String concatenation; for primitive types
operands are implicitly converted
– Note >> is with sign extension; >>> is not
– o instanceof C returns true if o is object of
class C (or subclass of C); true means o is
assignable to objects of type C
– boolean & and | do not short-circuit
Statements
• if/else, while, do/while same as in C
• switch statement is the same also (case labels must
be constants or “final” variables)
• for loops are different from C in two ways:
– comma separated init and increment sections:
for (i=0, j=0; i+j < 10; i++, j++)
– loop declarations in init section:
for (int i=0, j=0; …)
Labeled break Statement
• Used alone, “break” works the same as in C
• But in Java we can have labels attached
test: for (j=0; j < 10; j++) {
for (i=0; i < 10; i++) {
if (a[i][j] == null)
break test;
// break out of BOTH loops
}
}
Labeled continue Statement
• Used alone, “continue” works just like in C
• In Java, we can have labels:
resume: for (j=0; j < 10; j++) {
for (i=0; i < 10; i++) {
if (a[i][j] == null)
continue resume;
}
}
The synchronized Statement
• Used to synchronize multiple threads which
share data
• Syntax: synchronized (expr) statement
• expr must resolve to an object or array
public static void SortIntArray(int[] a) {
synchronized (a) {
// sort the array
}
}
Exceptions, Exceptions...
• An exception in Java is much like C++: a
signal that some important event (like an
error) has occurred
– To “throw” an exception is to signal that it has
occurred
– To “catch” an exception is to handle this
occurrence
Exceptions Propagate
• If an exception is not caught within a local
block, it propagates
– First propagates through enclosing blocks
– Then propagates up the method call stack
– If propagates all the way to main() and main()
does not catch it, the java interpreters prints an
error msg and a stack trace
• Well-designed code has centralized
exception-handling!
Exception Objects
• An exception is an object
– Its class is some subclass of java.lang.Throwable
– Two common subclasses are java.lang.Error and
java.lang.Exception
– java.lang.Error indicates a serious problem (eg,
out of memory) and should not be caught
– Subclasses of java.lang.Exception are often
caught and recovered from (eg, the exception
java.lang.ArrayAccessOutOfBounds)
Exceptions (cont.)
• Since an exception is an object, it has fields
– To get a description, call Throwable.getMessage()
• Handling is done via try/catch/finally
try {
// some block of code
} catch (SomeException e1) {
// handle SomeException or a subclass of this type
} finally {
// always execute this code
}
Exceptions (cont.)
• A try block is followed by zero or more
catch blocks
– exception is caught by the first catch() which
matches in type
• finally clause should do clean-up work
– a finally block is always executed if any part of
the try block is executed, even if exit is via a
break, continue, or return statement
Exceptions (cont.)
• “Normal Exceptions” must be caught or
propagated by your methods
public void open_file() throws IOException {
// code that might cause an uncaught java.io.IOException
}
• Some exceptions you don’t have to declare
– eg, InternalError (that would be ridiculous)
– How do we know when we have to declare it?
• Just try it and let the compiler tell you
Exceptions (cont.)
• To generate your own exceptions, use
Throw
– Often the exception object is allocated as it is
thrown:
throw new MyException(“bad thing happened”);
• Let’s look at a detailed example.
Conclusion