Chap1. A Quick Tour of Java Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. Prof. Hyoung-Joo Kim
Dec 20, 2015
Chap1. A Quick Tour of JavaChap1. A Quick Tour of Java
SNU-OOPSLA-Lab.
Prof. Hyoung-Joo Kim
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 2
Contents(1)Contents(1)
1.1 Getting Started 1.2 Variables 1.3 Comments in Code 1.4 Named Constants 1.5 Flow of Control 1.6 Classes and Objects 1.7 Methods and Parameters 1.8 Arrays
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 3
Contents(2)Contents(2)
1.9 String Objects 1.10 Extending a Class 1.11 Interfaces 1.12 Exceptions 1.13 Packages 1.14 The Java Infrastructure 1.15 Other Topics Briefly Noted
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 4
1.1 1.1 Getting StartedGetting Started
Class and Object Class
a factory with blueprints and instructions to build gadgets two members
field : data and making up the state of the object or class method : collection of statements that operate on the fields
Objects gadgets the factory makes instances of the class
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 5
““Hello, World”(1)Hello, World”(1)
String objects the main method’s only parameter
System.out.println println method on the System class’s out object
main one of a few special method in Java when run, main can create objects, evaluate expressions,
invoke other methods, etc.
class HelloWorld { public static void main (String[] args) { System.out.println(“Hello, world”); }}
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 6
““Hello, World”(2)Hello, World”(2)
Compilation $ javac HelloWorld.java $ ls HelloWorld.class HelloWorld.class Java compiler(javac) compiles the source into Java
bytecodes
Execution $ java HelloWorld Hello, World
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 7
1.2 1.2 VariablesVariables
Every variable must have a type Java has no “default” types
Primitive data types booleaneither true or false char 16-bit Unicode 1.1 character byte 8-bit integer ( signed ) short 16-bit integer ( signed ) int 32-bit integer ( signed ) long 64-bit integer ( signed ) float 32-bit floating point ( IEEE 754-1985 ) double 64-bit floating point ( IEEE 754-1985 )
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 8
““Fibonacci” Program(1)Fibonacci” Program(1)
Class Fibonacci {/** Print out the Fibonacci sequence for values < 50 */ public static void main(String[] args) { int lo = 1; int hi = 1; System.out.println(lo); while(hi < 50) { System.out.println(hi); hi = lo + hi; // new hi lo = hi - lo; // new lo is (sum - old lo) I.e., the old hi } }}
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 9
““Fibonacci” Program(2)Fibonacci” Program(2)
Compilation & Execution $ javac Fibonacci.java $ ls Fibonacci.class Fibonacci.class $ java Fibonacci 1 1 2 3 5...
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 10
1.3 1.3 Comments in CodeComments in Code Three styles of comments
// comment characters from // to the end of the line are ignored
/* comment */ character between /* and the next */ are ignored, including line
terminators \r, \n, or \r\n
/** comment */ documentation comment ( for short, doc comment ) characters between /** and the next */ are ignored, including line
terminators a tool called javadoc extracts documentation comments and
generates HTML documentation
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 11
1.4 1.4 Named ConstantsNamed Constants
Why do programmer prefer named constants? a form of documentation easy to maintain program
Named constants are created by declaring a variable as static and final providing its initial value
class CircleStuff {static final double = 3.1416;
}
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 12
1.4.1 1.4.1 Unicode CharactersUnicode Characters
You write Java code in Unicode - an international character set standard
Unicode characters are 16 bits and provide a character range large enough to write the major language
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 13
1.5 1.5 Flow of Control(1)Flow of Control(1)
Decide which statements are executed Similar to C-derived programming language (e.g.,
C, C++…) Think of output of running next prograrm!
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 14
1.5 1.5 Flow of Control(2)Flow of Control(2)
class ImprovedFibonacci {/** Print out the first few Fibonacci numbers, marking events with a ‘*’ */ static final int MAX_INDEX = 10; public static void main(String[] args) { int lo =1, hi =1; String mark; System.out.println(“1: “ + lo); for(int i=2; i < MAX_IINDEX; i++) { if(hi%2 == 0) mark = “ *”; else mark =“”; System.out.println(I + “: “ + hi + mark); hi = lo + hi; // new hi lo = hi - lo; /* new lo is (sum - old lo) I.e., the old hi */} } }
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 15
1.6 1.6 Classes and ObjectsClasses and Objects
Relationship between classes and objects an object have a type that type is the object’s class
Each class has two kinds of members fields - data variables associated with a class and its
objects methods - contain executable code of a class
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 16
1.6.1 1.6.1 Creating Objects(1)Creating Objects(1)
Creating objects (= instantiations) objects are created using new keyword newly created objects are allocated within heap objects are accessed via object references
instantiation, instance, instance variable creating an object from a class definition is instantiation created objects are called instances the fields in objects are instance variables
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 17
1.6.1 1.6.1 Creating Objects(2)Creating Objects(2)
class Point { public double x, y;
public static void main(String[] args) { Point lowerLeft = new Point(); // creating objects Point upperRight = new Point(); lowerLeft.x = 0.0; lowerLeft.y = 0.0; upperRight.x = 10.0; upperRight.y = 10.0; }}
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 18
1.6.2 1.6.2 Static or Class Fields(1)Static or Class Fields(1)
Static(class) fields known as class variables shared among all objects of a class declared by static keyword
Non-static (per-object) fields each object has distinct fields from other object
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 19
1.6.2 1.6.2 Static or Class Fields(2)Static or Class Fields(2)
class Point { public double x, y; public static Point origin = new Point(); public static void main(String[] args) { System.out.println("Origin.x = " + Point.origin.x); System.out.println("Origin.y = " + Point.origin.y); }}
Origin.x = 0.0Origin.y = 0.0
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 20
1.6.3 1.6.3 The Garbage CollectorThe Garbage Collector
Unreferenced Java objects are automatically reclaimed by a garbage collector
The garbage collector runs in the background and tracks object references
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 21
1.7 1.7 Methods and ParametersMethods and Parameters
Methods and parameters methods - operations of a class parameters - arguments of methods
Implementation hiding benefits of object orientation
Data encapsulation hiding data behind methods so that it is inaccessible to
other objects
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 22
1.7.1 1.7.1 Invoking a Method(1)Invoking a Method(1)
To invoke a method, provide an object reference and the method name,
separated by a dot(.)
To return more than one value, create an object to hold return values and return that
object
receiving object ( for short, receiver) the object on which the method is invoked
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 23
1.7.1 1.7.1 Invoking a Method(2)Invoking a Method(2)class Point { public double x, y;
public double distance(Point that){ double xdiff, ydiff; xdiff = x - that.x; ydiff = y - that.y; return Math.sqrt(xdiff *xdiff + ydiff*ydiff); }
public static void main(String[] args) { Point lowerLeft = new Point(); Point upperRight = new Point(); lowerLeft.x = 0.0; lowerLeft.y = 0.0; upperRight.x = 10.0; upperRight.y = 10.0; double d = lowerLeft.distance(upperRight); System.out.println("distance = " + d); }}
distance = 14.142….
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 24
1.7.2 1.7.2 The The thisthis Reference Reference
Implicit reference named “this” a reference to the current(receiving) object
class Point { public double x, y;
public void move(double x, double y) { this.x = x; this.y = y; }}
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 25
1.7.3 1.7.3 Static or Class MethodsStatic or Class Methods Static(class) methods
declared using static keyword shared among on static fields of all instance object can’t directly access non-static members
Non-static(per-object) methods each object has distinct method from other instance
class AnIntegerNamedX { static private int x; static public int getX() { return x; } static public void setX(int newX) { x = newX; }}
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 26
1.8 1.8 Arrays(1)Arrays(1)
Array a collection of variables all of the same type Array size is fixed and provided from the length field of
array object an IndexOutOfBoundsException is thrown
in case of using an index outside the bounds of the array
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 27
1.8 1.8 Arrays(2)Arrays(2)
class Deck {
final int DECK_SIZE = 52;
card[] cards = new Card[DECK_SIZE];
public void print() {
for (int i=0; i< cards.length; i++)
System.out.println( cards[i] );
}
}
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 28
1.9 1.9 String Objects(1)String Objects(1)
String class provide language-level support for initialization provide a variety of methods String objects are immutable
str = “redwood”; // ….. Do do something with str…. str = “oak”; /* give a new value to object reference str, not to
the contents of the string */
StringBuffer class provide for mutable strings
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 29
1.9 1.9 String Objects(2)String Objects(2)class BetterStringsDemo { public static void main(String[] args) { String myName = "Petronius"; String occupation = "Reorganization Specialist"; myName = myName + " Arbeiter"; myName += " "; myName += "(" + occupation + ")"; System.out.println("Name = " + myName); }}
Name = Petronius Arbeiter (Reorganization Specialist)
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 30
if (oneStr.equals(twoStr))
foundDuplicate(oneStr, twoStr);
1.9 1.9 String Objects(3)String Objects(3)
equals method compare two String objects to see if they have the
same contents
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 31
1.10 1.10 Extending a Class(1)Extending a Class(1)
Subclass inherit all the fields and methods of superclass if providing new implementation of inherited methods,
then overrides the behavior of superclass
class Point { public double x, y; public void clear(){ x = 0.0; y = 0.0; }}
class Pixel extends Point {
Color color ;
public void clear() {
super.clear();
color = null; }
}
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 32
1.10 1.10 Extending a Class(2)Extending a Class(2)Point Class
x()
y()
clear()
double xdouble y
set()
Pixel Class
Pixel extends Point
x()
y()
clear()
double xdouble y
set()
Color color
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 33
1.10.1 1.10.1 The The Object Object ClassClass
Classes that do not explicitly extend any other class implicitly extend the Object class
All object references are polymorphically of Object class, so Object class is the generic class for references that can refer to objects of any class
The Object class defines several methods
Object oref = new Pixel();oref = “Some String”
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 34
1.10.2 1.10.2 Invoking Methods from Invoking Methods from SuperclassSuperclass
super vs this super - reference things from superclass this - reference things from the current object
To invoke a method uses the actual type of the object, not the type of the
object reference
Point point = new Pixel(); point.clear(); // uses Pixel’s clear(), not Point’s clear()
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 35
1.11 1.11 Interfaces(1)Interfaces(1)
Interfaces similar to a class, but with only declarations of its
methods implementation details of the methods are irrelevant the class that implements the interface is responsible for
the specific implementation Class’s supertypes are
superclass that it extends interfaces that it implements all the supertypes of those classes and interfaces
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 36
Void processValues(String[] names, Lookup table) { for(int i=0; i<names.length; i++) { Object value = table.find(names[i]); if(value != null) processVaule(names[i], value);} }
1.11 1.11 Interfaces(2)Interfaces(2)
Code that uses references to Lookup objects and get the expected results, no matter the actual type of the object
interface Lookup {/** Return the value associated with the name, * or null if there is no such value */ Object find(String nam); }
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 37
class SimpleLookup implements Lookup { private String[] Names; private Object[] Values;
public Object find(String name) { for( int i=0; i<names.length; i++ ) {
if( Names[i].equals(name) ) return Values[i];
} return null; // not found } // ….}
1.11 1.11 Interfaces(3)Interfaces(3)
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 38
1.12 1.12 Exceptions(1)Exceptions(1)
Java uses checked exceptions to manage error handling
Checked exceptions force you to consider what to do with errors where they
may occur in the code exception is an object, with type, methods,and data
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 39
1.12 1.12 Exceptions(2)Exceptions(2)
Exception object generally derived from the Exception class, which
provides a string field to describe the error all exceptions is extensions of Throwable class, which
is the superclass of Exception
Exception Handling try-catch-finally sequence finally - clean up from either the normal code path or
the exception code path
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 40
1.12 1.12 Exceptions(3)Exceptions(3)
class IllegalAverageException extends Exception { }
class MyUtilities { public double averageOf ( double[] vals, int i, int j ) throws IllegalAverageException {
try{ return ( vals[i] + val[j] ) / 2;} catch ( IndexOutOfBoundsException e ){
throw new illegalAverageException();}
}}
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 41
1.13 1.13 Packages(1)Packages(1)
Solution for name-conflicts use a “package prefix” at the front of every class
it isn’t a complete solution
Packages have a set of types and subpackages as members package names are hierarchical and separated by dots in case of using a package
use its fully qualified name import all or part of the package
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 42
1.13 1.13 Packages(2)Packages(2)
When using part of a package
class Date1 { public static void main(String[] args) { java.util.Date now = new java.util.Date(); System.out.println(now);}
import java.util.Date;class Date2 { public static void main(String[] rgs){ Date now = new Date(); System.out.println(now);}
use fully qualified name
import all or part of the package
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 43
1.13 1.13 Packages(3)Packages(3)
Convention of naming packages complete solution for name collision use reversed Internet domain name of the organization
to prefix the package name. e.g., COM.acme.package, KR.ac.snu.oopsla.package
package com.sun.games;
class Card { // ………… }
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 44
1.14 1.14 The Java InfrastructureThe Java Infrastructure
Java is designed to maximize portability Java virtual machine
assign each application its own runtime runtime - isolate applications from each other and provide a
security model
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 45
1.15 1.15 Other Topics Briefly NotedOther Topics Briefly Noted
Applet Java program that runs on the browser of client
platform Make a class that extends the Applet class Make methods named as init, start, stop, destroy There is no main method Use other classes and utilities as the Java application
program
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 46
1.15 1.15 Other Topics Briefly NotedOther Topics Briefly Noted
Applet examplepublic class Simple extends Applet { StringBuffer buffer; public void init() { buffer = new StringBuffer(); addItem("initializing... "); } public void start() { addItem("starting... "); } public void stop() { addItem("stopping... "); } public void destroy() { addItem("preparing for unloading..."); }
void addItem(String newWord) { System.out.println(newWord); buffer.append(newWord); repaint(); } public void paint(Graphics g) { g.drawRect(0, 0, size().width - 1, size().height - 1); g.drawString(buffer.toString(), 5, 15); }}
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 47
1.15 1.15 Other Topics Briefly NotedOther Topics Briefly Noted
RMI(Remote Method Invocation : At Server Part) Designing a Remote Interface
import java.rmi.*;import java.rmi.server.*;import java.io.Serializable;
public interface Task extends Remote { TaskObject getTaskObjcet() throws RemoteException;}
public interface TaskObject extends Serializable { type1 task1(); type2 task2(); ………..}
import java.rmi.*;
public class Server{ public static void main(String args[]){ if(System.getSecurityManager() == null){ System.setSecurityManager(new RMISecurityManager()); } try{ TaskImpl task = new TaskImpl(); Naming.rebind(“Task”, task); }catch(Exception e){ ………………..; }}
rmiregistryrmiregistry 사용사용
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 48
1.15 1.15 Other Topics Briefly NotedOther Topics Briefly Noted
RMI(Remote Method Invocation : At Client Part) Use the same interface as the server Use following code to invoke remote object
……………..if(System.getSecurityManager() == null) System.setSecurityManager()(new RMI…());String url = “rmi://server_address”;try{ Task t = (Task)Naming.lookup(“Task”); TaskObject to = t.getTaskObject();}catch(Exception e){ ………..}
rmiregistryrmiregistry 사용사용
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 49
1.15 1.15 Other Topics Briefly NotedOther Topics Briefly Noted
Servlet Make Servlet script like CGI script
generic code are the shape of following
Object declarations (like other Java applications)Object declarations (like other Java applications)
out.println(“<HTML>”);out.println(“<HTML>”);out.println(“<HEAD><TITLE> …. </TITLE></HEAD>”);out.println(“<HEAD><TITLE> …. </TITLE></HEAD>”);
………………………………..
out.println(“</HTML>”);out.println(“</HTML>”);
Chap1. A Quick Tour of Java
SNU-OOPSLA-Lab. 50
1.15 1.15 Other Topics Briefly NotedOther Topics Briefly Noted
Java & XML Many XML parsers are implemented by Java DOM : Use Object Model
Makes a model (like tree structure) Provide traversal methods
SAX : Event Driven XML Parser Makes a event handler class Makes the methods to be invoked when an event occur SAX parser invokes an appropriate method when an event
occur