In104 Java Review is

advertisement
In104
Java Review
Java is an object-oriented programming language. Programming in Java is essentially to
create new classes.
A simple example:
public class Hello
{
public static void main (String[] args)
{
System.out.println ("Hello, the program is invoked with "
+ args.length + " parameter(s).");
}
}
Use javac for compilation.
> javac Hello.java
Use java for execution.
> java Hello
Hello, the program is invoked with 0 parameter(s).
> java Hello 1 2 3
Hello, the program is invoked with 3 parameter(s).
1
In104
Java Review
One of the prominent features of Java is its
capability of executing programs on the World
Wide Web. Therefore portability is a central
issue. Java is platform independent.
The Java compiler javac translates Java source
code into Java bytecode, which is architecture
neutral.
A Java interpreter (e.g.
executes the bytecode.
java)
translates and
Or a bytecode compiler may translate the bytecode into a particular machine language for efcient execution.
2
In104
Java Review
Java is accompanied by a huge set of supporting libraries (APIs - application programming
interfaces). Each library contains packages of
class hierarchies.
Some example packages of the standard Java
standard class library:
java.applet
java.awt
java.io
java.math
...
Except for classes in package java.lang, we
should either give fully qualied names or use
import for when using classes in other packages.
java.util.Vector v = new java.util.Vector();
import java.util.Vector;
Vector v = new Vector();
3
In104
Java Review
Programmers are quite free to create names
for new classes, variables and methods.
The names should be descriptive and readable.
Java is case sensitive. Programmers should be
consistent when creating the names.
Class names should start with a capital letter;
Variable/method names should start with
a small letter.
4
In104
Java Review
Like well chosen identier names, well written
comments are essential for human comprehension of source code.
// this is the first type of comments
/* this is the second type */
Remember to place meaningful comments around
in Java programs.
Also remember to use white spaces wisely to
achieve a nice layout of the source codes.
5
In104
Java Review
Java has 8 primitive data types
float
byte
int
boolean
double
short
long
char
Everything else is represented using objects.
Each primitive data type has its associated
wrapper class.
A Java variable holds either a primitive value
or a reference to an object.
Objects are dened by classes and created by
the new operator.
Objects are accessed through references. A
reference variable may be empty (has value
null). An object can have multiple references.
6
In104
Java Review
When all the references to an object are lost,
by either going out of scope or reassignment,
that particular object can no longer contribute
to the program and therefore becomes \garbage".
Java performs automatic garbage collection.
When the last reference to an object is lost, the
object becomes a candidate for garbage collection. Java periodically removes those objects
and reclaims their allocated memory space.
7
In104
Java Review
A Java array is an ordered list of values. In
Java, arrays are objects.
Each value of an array has an integer index,
starting from 0.
int[] a = new int[2];
a[0] = 1;
a[1] = 2;
// or equivalently
int[] a = { 1, 2 };
The size of an array is xed after construction.
Use length to check the size of an array.
Class Vector of the java.util package is similar
to an array, but allows dynamical change of size
and free insertion and removal of elements.
However, each element of a Vector must be
an object. Primitive data must rst be transformed into their wrapper objects.
Gain of exibility at the loss of eÆciency.
8
In104
Java Review
Class Hashtable from the java.util package
can be used for storing objects that each is
associated with a key, which is also an object.
Hashtable is in fact another type of dynamic
array whose special storage allows for faster
retrieval of a desired object.
Hashtable holidays = new Hashtable ();
holidays.put ("Christmas", new Date (2000,12,25));
holidays.put ("New Year", new Date (2001,1,1));
Date d = (Date) holidays.get ("Christmas");
9
In104
Java Review
A Java class consists of denitions of data and
methods that operate on those data.
A method can take parameters. All parameters
are passed by value. An object is passed into
a method by sending a copy of its reference.
public class ParamTest
{
public static void main (String[] args)
{
int i = 1;
int[] a = { 1, 1 };
increase (i,a);
System.out.println ("i="+i+" a[0]="+a[0]);
}
}
static void increase (int i, int[] a)
{
i++;
a[0]++;
a = new int[2];
a[0] = a[1] = 3;
}
10
In104
Java Review
The static modier associates a variable or
method with a class rather than a particular
object.
Normally, each object has its own data space.
However, static variables are shared among all
instances of a class.
Static methods, also called class methods, can
be invoked through the class itself, no need to
instantiate an object.
Math.sqrt(27);
Static methods can only make use of local variables or static members of the class they belong to.
11
In104
Java Review
A constant is similar to a variable, except that
it keeps the same value throughout its existence.
Denition of a constant is indicated by final:
final double PI = 3.14159;
final int max_num_students = 300;
Use of contants makes code more readable and
facilitates easy change later if desired.
12
In104
Java Review
Java Exceptions
A Java exception is an object dening an unusual or erroneous situation, which is recoverable.
An exception is thrown by a program or the
runtime environment, and can be caught and
handled appropriately if desired.
Java has a predened set of exceptions. The
set can be extended by a user.
13
In104
Java Review
Three ways of processing an exception:
1. not handle it at all,
2. handle the exception where it occurs,
3. handle the exception at another point in
the program.
Each catch clause on a try statement handles
a particular kind of exception.
If an exception is not caught and handled where
it occurs, it is propagated to the calling method.
14
In104
Java Review
I/O in Java works with dierent input and output streams. A stream is an ordered sequence
of bytes.
The java.io package contains class hierarchies
for handling dierent types of streams:
InputStream
mat)
- input byte-wise (binary for-
OutputStream
Reader Writer
- output byte-wise
input character-wise (ascii format)
- output character-wise
15
In104
Java Review
An example of opening a local text le:
import java.io.*;
String fn = "/hom/in104/www_docs/Quotes/tickers.in104";
String line;
try {
FileReader fr = new FileReader (fn);
BufferedReader inFile = new BufferedReader (fr);
line = inFile.readLine();
while (line != null) {
// ...
line = inFile.readLine();
}
}
catch (FileNotFoundException exception) {
System.out.println ("File "+fn+" is not found.");
}
catch (IOException exception) {
System.out.println (exception);
}
16
In104
Java Review
An example of opening a text le at a URL:
import java.net.URL;
import java.io.*;
URL url;
String line;
try {
url=new URL("http://www.ifi.uio.no/~in104/Quotes/tickers.in104");
InputStreamReader ir=new InputStreamReader(url.openStream());
BufferedReader inFile = new BufferedReader(ir);
line = inFile.readLine();
while (line != null) {
// ...
line = inFile.readLine();
}
}
catch (java.net.MalformedURLException exception) {
System.out.println (exception);
}
catch (IOException exception) {
System.out.println (exception);
}
17
In104
Java Review
Class StringTokenizer is useful for extracting
meaningful pieces from a character string. We
assume that the meaningful pieces are seperated by delimiters (white space, tab etc.)
String line1 = "1.2|4.5|3.3";
String line2 = "";
StringTokenizer tokenizer
= new StringTokenizer (line1,"|");
while (tokenizer.hasMoreTokens()) {
line2 += " " + tokenizer.nextToken();
}
System.out.println (line2);
18
Download