Download Java Examples

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Examples
Java Language Constructs
CS 884 (Prasad)
Java Examples
1
Java Program Organization
• Compilation Unit = File
• Package = Directory
– A Java program is a set of compilation
units organized using a package
hierarchy (that is, as a forest of trees).
– A compilation unit is a set of class and
interface declarations.
– Every compilation unit belongs to a
unique (possibly unnamed) Java package.
CS 884 (Prasad)
Java Examples
2
• Every file (compilation unit) can have at
most one public class.
• The definition of public class PC must be
in a file named PC.java.
– Set environment variables CLASSPATH and PATH appropriately.
• To compile:
> javac PC.java
• To run:
> java PC
• To run applets: > netscape PC.html
> appletviewer PC.html
CS 884 (Prasad)
Java Examples
3
Class Declaration
– Fields / Instance Variables (Holds state)
• x, y
– Constructors (Initializes state)
• Point
– Methods (Proc/Func) (State Transformer/Observer)
• move
– Class Variables (Global to all instances)
• count
– Local Variables / Formal Parameters
CS 884 (Prasad)
Java Examples
4
Interface Declaration
interface Table {
boolean isEmpty();
void insert(Object x, int key);
Object lookUp(int key);
}
– An interface specifies constants and signatures
of the methods.
– An interface can extend several superinterfaces.
CS 884 (Prasad)
Java Examples
5
Class implements Interface
import java.util.Hashtable;
class Index implements Table {
HashTable v = new Hashtable();
public boolean isEmpty() {
return v.isEmpty(); }
public void insert(Object x, int key) {
v.put(new Integer (key) , x); }
public Object lookUp(int key) {
return v.get(new Integer ( key ) ); }
}
CS 884 (Prasad)
Java Examples
6
Abstract Classes
• Classes must implement all methods.
• Interfaces must specify only the signatures
of the methods.
• Abstract classes can implement some
methods, leaving the rest to subclasses.
• Interfaces and abstract classes cannot be
instantiated (to create objects).
CS 884 (Prasad)
Java Examples
7
Arrays
• Index Range: 0 to (length - 1).
• Each array object is of fixed size, permitting
index checking at run-time.
•
•
•
•
int [] [] twoD = new int [8] [];
Point [] points = {new Point(5, 5), null };
twoD[1] = new int [2];
twoD[1][0] = points[0].x;
CS 884 (Prasad)
Java Examples
8
• Declaration
– int[]
intArray;
– field intArray initialized to null, by default.
• Creation
– intArray = new int[5];
– intArray = { 0, 2, 4, 3*2, 4+4 };
• Multi-dimensional array
– double [][] iA = { { 1, 0 }, null };
• Java runtime verifies that array indices are
in the correct range.
CS 884 (Prasad)
Java Examples
9
Traditional First Program
public class HelloWorld {
public static void main(String [] args) {
System.out.println(“Hello World”);
}
}
– javac HelloWorld.java
– java HelloWorld a b c
CS 884 (Prasad)
Java Examples
10
Another Example Program
class EchoArgs {
public static void main(String[] args){
for (int i = 0; i < args.length; i++)
System.out.print( args[i] );
System.out.println( “ ”);
};
}
– javac
EchoArgs.java
– java
EchoArgs a 23 c abc
– java
EchoArgs
CS 884 (Prasad)
Java Examples
11
4
“a”
“23”
args
“c”
(local variable
on stack)
CS 884 (Prasad)
“abc”
(array object
on heap)
Java Examples
(string objects
on heap)
12
class PascalTriangle {
public static void main( String[] args ) {
n = Integer.parseInt( args[0] );
int [] [] pT = new int [n + 1] [];
pT[0] = new int[1];
// first row
pT[0][0] = 1;
for (int i = 1; i <= n; i++) {// rows 2 to n+1
pT[i] = new int [i + 1];
pT[i][0] = 1;
pT[i][i] = 1;
for (int j = 1; j < i ; j++ ) {
pT[i][j] = pT[i-1][j-1] + pT[i-1][j];
}
}
}
CS 884 (Prasad)
Java Examples
13
3
1
1
2
1
pT
1
3
(local variable
on stack)
CS 884 (Prasad)
(int array objects
on heap)
1
(array object
on heap)
Java Examples
2
1
14
Array type : “unconstrained”
• Define matrix operations in terms of structure of
the array (dimensionality); size is implicit.
• Vector dot-product that works for two equal length
single-dimension array with same type elements.
• Matrix multiplication : Dimension compatibility
checked at run-time.
• length field of an array object used :
– to control loops.
– to allocate storage for local variables.
• Type is unconstrained, but each object/instance has a
fixed size. (E.g., String type vs String object )
• Cf. Ada Unconstrained array types.
CS 884 (Prasad)
Java Examples
15
Exceptions
• Abnormal condition may be signaled by throw-ing
an exception. (Cf. Returning error (status) code that
can be ignored by caller.)
• To deal with abnormal situation, the caller can
provide an appropriate handler using try-catch
construct.
• In Java, Checked Exceptions must be handled
explicitly or propagated explicitly. (Errors and
Unchecked Exceptions are propagated implicitly, if
not handled explicitly.)
CS 884 (Prasad)
Java Examples
16
Visibility of names
• Private:
• class
• Default:
• package (not just compilation unit)
• Protected:
• package and subclasses (in other packages).
• Public:
• where-ever the package is visible.
CS 884 (Prasad)
Java Examples
17
Java Development Kit
•
•
•
•
•
•
•
java.lang (contains Threads)
java.io (contains StreamTokenizer)
java.awt (Abstract Windowing ToolKit)
java.net (Support for TCP/IP, HTTP)
java.applet (To run code via Browser)
java.util (Standard Utilities)
javac, java, javadoc
CS 884 (Prasad)
Java Examples
18
Tokens
• Whitespace
• blank
• tab
• newline
• Keywords (reserved)
• Identifiers
• Literals
• 25, 2.5 (int/float)
• Comment
• // ...
• /* ... */
• /** ... */
• Separators
– 09 is not an integer.
• true, false (boolean)
• ‘a’, \u0061, \n (char)
• Operators
• +, >, &&, etc
• (, ), [, ], etc
CS 884 (Prasad)
Java Examples
19
Character Strings
class String
class StringBuffer
(Cf. array of characters)
Based on 2-byte Unicode characters
CS 884 (Prasad)
Java Examples
20
class String
vs
class StringBuffer
• immutable
• mutable
– contents of String
instance unchangeable
– cannot insert or
append characters
• fixed length
• s.length()
– number of characters in
the string
CS 884 (Prasad)
– contents of
StringBuffer
instance
modifiable
• growable
– grows automatically
when characters added
• sb.length()
• sb.capacity()
– total allocated capacity
Java Examples
21
String literals and concatenation
• String s = “abc”;
• System.out.println( s + “def” );
– “+” stands for string concatenation.
– Built-in operator overload.
• Left associativity of “+”
(s +
3 + 5)
evaluates to
(s + (3 + 5)) evaluates to
(5 + 3 + s)
evaluates to
“abc35”.
“abc8”.
“8abc”.
• Assignment
s += 25;
CS 884 (Prasad)
Java Examples
22
String conversions
• class Object
•
supports toString()-method
to convert a class instance into a printable
string form: classname@hashcode
toString() can be overridden.
public String toString() { ... };
• println/print
methods in System.out, the
“+”-expressions, and the “+= ”-statements
invoke toString() implicitly, to coerce an
instance to a string.
CS 884 (Prasad)
Java Examples
23
TYPE
TO
STRING
FROM
STRING
String.valueOf(boolean)
new Boolean(String).
booleanValue()
int
String.valueOf(int)
Integer.parseInt(String)
long
String.valueOf(long)
Long.parseInt(String)
String.valueOf(float)
new Float(String).
floatValue()
String.valueOf(double)
new Double(String).
doubleValue()
boolean
float
double
CS 884 (Prasad)
Java Examples
24
Comparison
• “abc”.equals(“abc”)
is
true.
• “abc”.equalsIgnoreCase(“ABC”)
• (s == s)
is
• (“abc” + s ==
is
true.
true.
“abc” + s)
is
false.
• s1.compareTo(s2)
• negative: s1 lexicographically precedes s2
• zero:
s1
is equal
s2
• positive: s1 lexicographically follows
s2
CS 884 (Prasad)
Java Examples
25
Interning
package testPackage;
class Test {
public static void main(String[] args) {
String hello = "Hello", lo = "lo";
System.out.print((hello == "Hello") + " ");
System.out.print((Other.hello == hello) + " ");
System.out.print((ext.Other.hello == hello)+" ");
System.out.print((hello == ("Hel"+"lo")) + " ");
System.out.print((hello == ("Hel"+lo)) + " ");
System.out.println(hello == ("Hel"+lo).intern());
}
}
class Other { static String hello = "Hello"; }
package ext;
public class Other { static String hello = "Hello"; }
Result of execution:
true true true true false true
CS 884 (Prasad)
Java Examples
26
Assignment
String s = “abc”;
s += 2+3+5;
s.equals(“abc10”) == true
s.equals(“abc235”) == false
(Recall that “+” is left-associative.)
Type E1;
E1 += E2;
E1 = (Type) ((E1) + (E2))
CS 884 (Prasad)
Java Examples
27
Useful Methods
– String t = “abca”;
– String s = new String(t);
• s.charAt(2)
• s.indexOf(‘a’)
• s.indexOf(“bc”)
• s.indexOf(‘a’,2)
• s.lastIndexOf(‘a’)
is
is
is
is
is
‘c’.
0.
1.
3.
3.
• regionMatches, startsWith, endsWith, etc.
– Pure ASCII applications can be inefficient
because Java uses 16-bit Unicode characters.
CS 884 (Prasad)
Java Examples
28
Motivation for Strong Typing
• Type declarations provide extra information
associated with an identifier. This redundant
info. enables mechanical detection of errors.
• In practice, a number of logical and
typographical errors manifest themselves as
type errors. Thus, strongly typed languages
allow construction of reliable programs.
• In OOPLs, the type tags associated with
objects aid in the impl. of dynamic binding,
polymorphism, and safe conversions.
CS 884 (Prasad)
Java Examples
29
Typing
variable
reference
(text)
(pointer)
• Static Typing (e.g., Ada)
object
(memory)
• type(variable) = type(object)
• compile-time checking : efficient
• Dynamic Typing (e.g., Scheme)
• variables type-less; objects carry type tags
• run-time type-checking : flexible
CS 884 (Prasad)
Java Examples
30
• Typing in OOPL (E.g., Java, Eiffel, C++, …)
• type(object/reference) is-a-subtype-of
type(variable).
• In Java, a variable of class C, can hold a reference to
an instance (object) of a subclass of C.
– Type correctness guaranteed at compile-time.
• Efficient and secure.
– Dynamic binding dispatches each call to the
appropriate code, at run-time.
• Flexible handling of heterogeneous data.
CS 884 (Prasad)
Java Examples
31