7 september 2006nvo summer school 2006 - aspen java: a survival guide (and a bit about c/c++) ray...
Post on 27-Mar-2015
213 Views
Preview:
TRANSCRIPT
7 September 2006NVO Summer School 2006 - Aspen
Java: a Survival Guide(and a bit about C/C++)
Ray Plante
/** * say hello to the world */public class HelloWorld { public static void main(String[] args) { System.out.println(”Hello world!”); }}
> javac HelloWorld.java> java HelloWorldHello world!
HelloWorld.java
THE US NATIONAL VIRTUAL OBSERVATORY
7 September 2006NVO Summer School 2006 - Aspen
Java: a Survival Guide(and a bit about C/C++)
Ray Plante
/** * say hello to the world */public class HelloWorld { public static void main(String[] args) { System.out.println(”Hello world!”); }}
> javac HelloWorld.java> java HelloWorldHello world!
HelloWorld.java
THE US NATIONAL VIRTUAL OBSERVATORY
7 September 2006NVO Summer School 2006 - Aspen
Goals
• Be able to read summer school Java code and understand what it does.
• Understand enough Java syntax to make simple changes or extensions to existing code
• Know how to build and run Java code.
• Recognize some common programming errors
Warning: some exercise instructions contain errors (on purpose)
7 September 2006NVO Summer School 2006 - Aspen
Quick Tour of a Java Programsee Hello.java package nvoss.basicjava;
import java.io.Writer;import java.io.*;
/** * a Hello World class and application */public class Hello implements Cloneable {
private String who = "world"; // a default value is set
/** * create a Hello instance * @param toWho a name for who we are saying hello to */ public Hello(String toWho) { who = toWho; }
/** * create a Hello instance */ public Hello() { }
7 September 2006NVO Summer School 2006 - Aspen
package nvoss.basicjava;
import java.io.Writer;import java.io.*;
/** * a Hello World class and application */public class Hello implements Cloneable {
private String who = "world"; // a default value is set
/** * create a Hello instance * @param toWho a name for who we are saying hello to */ public Hello(String toWho) { who = toWho; }
/** * create a Hello instance */ public Hello() { }
Define one classper file.
Quick Tour of a Java Programsee Hello.java
7 September 2006NVO Summer School 2006 - Aspen
package nvoss.basicjava;
import java.io.Writer;import java.io.*;
/** * a Hello World class and application */public class Hello implements Cloneable {
private String who = "world"; // a default value is set
/** * create a Hello instance * @param toWho a name for who we are saying hello to */ public Hello(String toWho) { who = toWho; }
/** * create a Hello instance */ public Hello() { }
Define one classper file.
Every class is part of a package.
Quick Tour of a Java Programsee Hello.java
7 September 2006NVO Summer School 2006 - Aspen
package nvoss.basicjava;
import java.io.Writer;import java.io.*;
/** * a Hello World class and application */public class Hello implements Cloneable {
private String who = "world"; // a default value is set
/** * create a Hello instance * @param toWho a name for who we are saying hello to */ public Hello(String toWho) { who = toWho; }
/** * create a Hello instance */ public Hello() { }
Define one classper file.
Every class is part of a package.
Declare other classeswe’ll be using
Quick Tour of a Java Programsee Hello.java
7 September 2006NVO Summer School 2006 - Aspen
package nvoss.basicjava;
import java.io.Writer;import java.io.*;
/** * a Hello World class and application */public class Hello implements Cloneable {
private String who = "world"; // a default value is set
/** * create a Hello instance * @param toWho a name for who we are saying hello to */ public Hello(String toWho) { who = toWho; }
/** * create a Hello instance */ public Hello() { }
Define one classper file.
Every class is part of a package.
Declare other classeswe’ll be using
Comments!
Quick Tour of a Java Programsee Hello.java
7 September 2006NVO Summer School 2006 - Aspen
package nvoss.basicjava;
import java.io.Writer;import java.io.*;
/** * a Hello World class and application */public class Hello implements Cloneable {
private String who = "world"; // a default value is set
/** * create a Hello instance * @param toWho a name for who we are saying hello to */ public Hello(String toWho) { who = toWho; }
/** * create a Hello instance */ public Hello() { }
Define one classper file.
Every class is part of a package.
Declare other classeswe’ll be using
Special commentingstyle for producingextractable documentation
Comments!
Quick Tour of a Java Programsee Hello.java
7 September 2006NVO Summer School 2006 - Aspen
package nvoss.basicjava;
import java.io.Writer;import java.io.*;
/** * a Hello World class and application */public class Hello implements Cloneable {
private String who = "world"; // a default value is set
/** * create a Hello instance * @param toWho a name for who we are saying hello to */ public Hello(String toWho) { who = toWho; }
/** * create a Hello instance */ public Hello() { }
Define one classper file.
Every class is part of a package.
Declare other classeswe’ll be using
Member fieldshold a class’ internal data
Special commentingstyle for producingextractable documentation
Comments!
Quick Tour of a Java Programsee Hello.java
7 September 2006NVO Summer School 2006 - Aspen
package nvoss.basicjava;
import java.io.Writer;import java.io.*;
/** * a Hello World class and application */public class Hello implements Cloneable {
private String who = "world"; // a default value is set
/** * create a Hello instance * @param toWho a name for who we are saying hello to */ public Hello(String toWho) { who = toWho; }
/** * create a Hello instance */ public Hello() { }
Define one classper file.
Every class is part of a package.
Declare other classeswe’ll be using
Member fieldshold a class’ Internal data
Constructor functionis called to when a Hello object is created.
Special commentingstyle for producingextractable documentation
Comments!
Quick Tour of a Java Programsee Hello.java
7 September 2006NVO Summer School 2006 - Aspen
/** * return the name of who is being greeted */ public String getWho() { return who; }
/** * set the name of who is being greeted */ public void setWho(String name) { who = name; }
/** * say hello to the world */ public static void main(String[] args) {
Hello greeter = new Hello(); greeter.sayHello(); }}
Quick Tour of a Java Programsee Hello.java
7 September 2006NVO Summer School 2006 - Aspen
Quick Tour of a Java Programsee Hello.java
Methods!
/** * return the name of who is being greeted */ public String getWho() { return who; }
/** * set the name of who is being greeted */ public void setWho(String name) { who = name; }
/** * say hello to the world */ public static void main(String[] args) {
Hello greeter = new Hello(); greeter.sayHello(); }}
7 September 2006NVO Summer School 2006 - Aspen
Quick Tour of a Java Programsee Hello.java
Methods!
A main methodturns a class intoan application.
/** * return the name of who is being greeted */ public String getWho() { return who; }
/** * set the name of who is being greeted */ public void setWho(String name) { who = name; }
/** * say hello to the world */ public static void main(String[] args) {
Hello greeter = new Hello(); greeter.sayHello(); }}
7 September 2006NVO Summer School 2006 - Aspen
Quick Tour of a Java Programsee Hello.java
Methods!
A main methodturns a class intoan application.
Here’s how youcreate a Hello object.
/** * return the name of who is being greeted */ public String getWho() { return who; }
/** * set the name of who is being greeted */ public void setWho(String name) { who = name; }
/** * say hello to the world */ public static void main(String[] args) {
Hello greeter = new Hello(); greeter.sayHello(); }}
7 September 2006NVO Summer School 2006 - Aspen
/** * return the name of who is being greeted */ public String getWho() { return who; }
/** * set the name of who is being greeted */ public void setWho(String name) { who = name; }
/** * say hello to the world */ public static void main(String[] args) {
Hello greeter = new Hello(); greeter.sayHello(); }}
Quick Tour of a Java Programsee Hello.java
Methods!
A main methodturns a class intoan application.
Here’s how youcreate a Hello object. Here’s how you
call a Hello method.
7 September 2006NVO Summer School 2006 - Aspen
/** * return the name of who is being greeted */ public String getWho() { return who; }
/** * set the name of who is being greeted */ public void setWho(String name) { who = name; }
/** * say hello to the world */ public static void main(String[] args) {
Hello greeter = new Hello(); greeter.sayHello(); }}
Quick Tour of a Java Programsee Hello.java
Methods!
A main methodturns a class intoan application.
Here’s how youcreate a Hello object. Here’s how you
call a Hello method.
Don’t forget:– Every executable statement ends in a semicolon (“;”)– Methods and classes are enclosed in braces (“{ }”)
7 September 2006NVO Summer School 2006 - Aspen
Packages and the CLASSPATH• Every class belongs to a package
– Package names define a namespaceAllows classes with the same name can come from different packages and used in
the same program
– Package names are hierachical and imply a directory structurenet.ivoa.adql => net/ivoa/adql
• Class file must appear in a directory implied by package name
• Classpath– A list of directories that Java searches to find classes– Usually set with environment variable CLASSPATH
• Linux/MacOS/Unix: colon separated• Windows: semi-colon separated
– Package directories must be relative to one of the classpath directories
– Instead of a directory, can also give path to a “jar” file• Like a tar or zip file, but contains Java class files
• Executing a class as an application– Remember: class must contain a main() method– Must provide full name of class, including package
java nvoss.basicjava.Hello
7 September 2006NVO Summer School 2006 - Aspen
Packages and the CLASSPATH• Every class belongs to a package
– Package names define a namespaceAllows classes with the same name can come from different packages and used in
the same program
– Package names are hierachical and imply a directory structurenet.ivoa.adql => net/ivoa/adql
• Class file must appear in a directory implied by package name
• Classpath– A list of directories that Java searches to find classes– Usually set with environment variable CLASSPATH
• Linux/MacOS/Unix: colon separated• Windows: semi-colon separated
– Package directories must be relative to one of the classpath directories
– Instead of a directory, can also give path to a “jar” file• Like a tar or zip file, but contains Java class files
• Executing a class as an application– Remember: class must contain a main() method– Must provide full name of class, including package
java nvoss.basicjava.Hello
7 September 2006NVO Summer School 2006 - Aspen
Types, Classes, and Objects
• Primitive typesboolean, float, double, int, long, short, byte, enum, void
• Class = data + functions on that dataJava-speak: data are “members”, functions are “methods”
– A complex type beyond “primitive” types• Can create variables of the particular class type• Variables have multi-faceted values• Functions provide “contract” for accessing the data
– Class represents a logical concepte.g. Point, Image, VOTable, Stack, Class…
– All classes implicitly inherit from the generic Object class
• Object = class data values assigned to a variable– Created with new: Java-speak: often called a class
instance
Hello greeting = new Hello(”world”);Hello insult = new Hello(”dork”);
– All object variables are referencesint a = b; // not a reference: a copy of b’s value is put into aHello myhello = greeting; // no copy of the data is made
– Never need to explicitly delete objects: Garbage Collection!
7 September 2006NVO Summer School 2006 - Aspen
Constructors
• Special methods used to initialize data in an object– Named after class name, no return type– Called implicitly via new – Executed after any initialization statements
• Constructors can be overloaded– Multiple versions with different inputs
Hello greeting = new Hello(); // calls public Hello() Hello insult = new Hello(”dork”); // calls public Hello(String)
7 September 2006NVO Summer School 2006 - Aspen
Interacting with Objects
• “Outside” users of an Object can only access its “public” members & methods– marked with public modifier– Use . operator:
Point pt = new Point(4, 5);System.out.println(”Position: ” + pt.x + ”, ” + pt.y);pt.move(3, 3);
– Most classes hide their internal data • private: accessible only inside class• protected: accessible both internally and to subclasses• Public access methods provided to manipulate internal
data, if allowedHello greeting = new Hello();greeting.setWho(”Dave”);System.out.println(”addressee is now ” + greeting.getWho());
– If data is read-only, no “set” method is defined» e.g., String is immutable, has no set methods
7 September 2006NVO Summer School 2006 - Aspen
Interacting with Objects
• What’s this?– “automatic” variable referring to current object public void setWho(String who) { this.who = who; }
• What’s null?– Special value for object variables that do not point to
an instantiated object– Default value for objects
String name; // EquivalentString name = null; // Equivalentif (name == null) { …}
– NullPointerException: an error thrown if one attempts to use . on a object = nullif (name.length() > 0) { // Ouch! Throws an error if name=null …}
7 September 2006NVO Summer School 2006 - Aspen
Interacting with Objects
• What’s static?– Data/method shared by all instances of a class
• Often used to declare constant datapublic class Hello { public static final String DEFAULT = ”world”; String who = DEFAULT; …}
– Do not need to create an instance to access static data/method.
• Use class name to access static data or method System.out.println(” The default addressee is: ” + Hello.DEFAULT); String[] args = new String[0]; Hello.main(args); // call the static main() method directly
– Static method cannot access non-static data!public static void main(String[] args) { System.out.println(”addressee = ” + who); // ERROR! …}
7 September 2006NVO Summer School 2006 - Aspen
Arrays
• Arrays can be made of a primitive or class type– Declaring an array
int[] a;String[] words;
– Instantiating & initializing an arrayint[] b = new int[4]; // length of 4, values set to 0words = new String[3]; // length of 4; each value is nullwords = new String[] { ”the”, ”quick”, ”brown”, ”fox” };
– An array index is zero-based: a[0] is the 1st element– Arrays are objects
• Contain public member called lengthfor(int i=0; i < b.length; b++) { b[i] = i;}
– Multidimensional arrays same as in C
• Array classes Defined in java.util packagee.g., Vector, ArrayList, Stack
– Can only hold non-primitive values
7 September 2006NVO Summer School 2006 - Aspen
Arrays
• Arrays can be made of a primitive or class type– Declaring an array
int[] a;String[] words;
– Instantiating & initializing an arrayint[] b = new int[4]; // length of 4, values set to 0words = new String[3]; // length of 4; each value is nullwords = new String[] { ”the”, ”quick”, ”brown”, ”fox” };
– An array index is zero-based: a[0] is the 1st element– Arrays are objects
• Contain public member called lengthfor(int i=0; i < b.length; b++) { b[i] = i;}
– Multidimensional arrays same as in C
• Array classes Defined in java.util packagee.g., Vector, ArrayList, Stack
– Can only hold non-primitive values
7 September 2006NVO Summer School 2006 - Aspen
Java Packages
• Standard Java packages start with “java”– java.lang: the core classes
• Useful classes: String, System, Object, Math• Primitive wrapper classes: Integer, Double, Boolean, Char,
etc.– Other useful standard packages
• java.util: Vector, ArrayList, Hashtable, StringTokenizer• java.io: File, FileReader, FileWriter, etc.• java.net: URL
• Importing classes – You can refer to a class by its full name: java.net.URL– If you want to refer to a class using the shortened name
(e.g. URL), you must import it.• E.g. import java.net.URL;• import java.net.*; imports everything from java.net• You do not have to import
– Classes from the same package as the one be defined– Classes from java.lang (import java.lang.*; is implicit done by
compiler)
7 September 2006NVO Summer School 2006 - Aspen
Creating Your own API docs
• javadoc produces high-quality API documentation– Extracts specially marked comments
• Class, data member, and method descriptions
/** 2 asterisks * return the name of who is being greeted */public String getWho() { /* this is not extracted */
• Special tags within comments
/** * create a Hello instance * @param toWho a name for who we are saying hello to */public Hello(String toWho) {
– It’s incredibly easy!
7 September 2006NVO Summer School 2006 - Aspen
Extending classes through inheritance
• Subclass = an existing class + modifications– Subclass inherits data & methods of parent class– Subclass can add additional data & methods– Subclass replace or override inherited methods– Single inheritance: subclass can only extend one parent class, but…– Can be a chain of subclasses
• All classes inherit from Object
• Abstract class– Can’t be instantiated themselves; must be subclassed
• Some functions are defined but don’t have implementations• Ex: Writer -- how the writing is done depends on what is being written
to
• Interface = set of functions with no implementations, no data– A class implements an interface– A class can implement multiple interfaces
• a kind of multiple intheritance
What’s the use of a class/interface that doesn’t provide implementations for all its methods?
7 September 2006NVO Summer School 2006 - Aspen
How to extend a class through inheritance
1. Use extends in the class definitionpublic class SpiralGalaxy extends Galaxy {}
2. Add any new data members3. Add constructors
– Constructors are not inherited; however, you can call the parent’s constructor:
public SpiralGalaxy(String name) { super(name); // will call Galaxy(String)}
– If super constructor not called explicitly, the compiler inserts a super()
4. Add new and/or overriding methods– An overriding method may call parent’s version
public Population getStellarPopulation() { Population pop = super.getStellarPopulation() … // manipulate population return pop;}
7 September 2006NVO Summer School 2006 - Aspen
Implementing interfaces
1. List interface being supported with implements
public class SpiralGalaxy extends Galaxy
implements ClusterComponent
{
}
2. Provide implementations of methods in interface
public double getDarkMass() {
…
}
7 September 2006NVO Summer School 2006 - Aspen
Exceptions – an Intro
• Exception = specialized objects that can be thrown when an error occurs
if (greeter == null) throw new NullPointerException(”No Hello provided”);
– Different types of exceptions are used for different types of errors
• When throw is used…– Execution of the current function stops*– The exception is passed to the caller of the function*
*unless caught along the way—more on this later
• Exceptions travel up the call-stack until it is caught – If it reaches the top of the call stack, Java will:
• Print the exception’s error message• Print the call stack it traveled through
Exception in thread "main" java.lang.NullPointerException: No Hello provided at nvoss.basicjava.Hello.main(Hello.java:91) at nvoss.basicjava.FrenchHello.main(FrenchHello.java:40)
7 September 2006NVO Summer School 2006 - Aspen
Exceptions – an Intro
• Exception = specialized objects that can be thrown when an error occurs
if (greeter == null) throw new NullPointerException(”No Hello provided”);
– Different types of exceptions are used for different types of errors
• When throw is used…– Execution of the current function stops*– The exception is passed to the caller of the function*
*unless caught along the way—more on this later
• Exceptions travel up the call-stack until it is caught – If it reaches the top of the call stack, Java will:
• Print the exception’s error message• Print the call stack it traveled through
Exception in thread "main" java.lang.NullPointerException: No Hello provided at nvoss.basicjava.Hello.main(Hello.java:91) at nvoss.basicjava.FrenchHello.main(FrenchHello.java:40)
7 September 2006NVO Summer School 2006 - Aspen
Polymorphism
What’s the use of a class/interface that doesn’t provide implementations for all its methods?
• You can refer to a specific subclass instance using a more generic reference
FileWriter out = new FileWriter(file);
orWriter out = new FileWriter(file); // ok
public void sayHello(Writer out) { … }
Hello greeter = new Hello();
greeter.sayHello(out);
– Okay because FileWriter is a type of Writer
• You can also refer to a class instance by its Interface name• A Class or Interface is a “contract”
– It guarantees support for a set of methods
7 September 2006NVO Summer School 2006 - Aspen
Tips for debugging exceptions
• Recompile your code with –g option– Inserts line numbers into printed stack traces
• Find first line in stack trace that refers to a function in your code– Is your function the first in the stack trace?
• Line number provides exact location where error occurred • Root cause of the error may be somewhere else
– Is your function not the first in the stack trace?• Line number gives location where you call another
function• There is probably something wrong with the objects you
have passed to the function
• jdb, the Java Debugger, can be very useful
7 September 2006NVO Summer School 2006 - Aspen
Common Exceptions
• NullPointerExceptionThe usual explanation:
• an object variable has been set to null; later, an attempt is made to access its contents, usually via the . operator (e.g. var.get())
How to fix it: • go to the designated line number and look for an variable using the . operator; that
will be the null variable• If your class is not at the top of the call stack, look for variables that are being passed
into the function; one of these will be null.
• NoClassDefFoundErrorThe usual explanation:
• Your CLASSPATH does not include the indicated class or packageHow to fix it:
• Adjust your CLASSPATH; make sure it includes all the directories or jar files needed.
• ArrayIndexOutOfBoundsExceptionThe usual explanation:
• While accessing array elements via [], e.g. a[i], the index i < 0 or >= a.lengthHow to fix it:
• Look for the use of [] in the indicated line; the exception message gives the value of the offending index.
7 September 2006NVO Summer School 2006 - Aspen
Handling Exceptions in code
• Use a try-catch blocktry { // code that might generate an error}catch (MalformedURLException ex) { … // ex holds the exception}catch (ConnectException ex) { …}catch (Exception ex) { …}
– Each catch block handles a different type of failure– When the exception type matches a catch block,
• The exception’s upward traversal halts• The catch block is executed• If block does not throw its own exception, execution outside the try-catch
block continues
– catch block gives you a chance to …• Recover from the error• Clean up (e.g. close open files)• Print a message to the user• Ignore a non-fatal error• Throw an exception of a different type
7 September 2006NVO Summer School 2006 - Aspen
The throws clause
• A function must indicate what exceptions it might throw
public void loadData(Reader in)
throws IOException, ParseException
{ … }
– Except for RuntimeExceptionsEx: NullPointerException
• function user must either – Enclose the method call in a try-catch block, or– Add exception to calling function’s throws clause
7 September 2006NVO Summer School 2006 - Aspen
The throws clause
• A function must indicate what exceptions it might throw
public void loadData(Reader in)
throws IOException, ParseException
{ … }
– Except for RuntimeExceptionsEx: NullPointerException
• function user must either – Enclose the method call in a try-catch block, or– Add exception to calling function’s throws clause
7 September 2006NVO Summer School 2006 - Aspen
VO Software in C/C++
• Development in C/C++ has lagged behind other languages• Native libraries
– libVOTable: http://terapix.iap.fr/cplt/docs/libVOTable/ VOTable Parser in ANSI C
– VO-India’s VOTable Parsers in C++: http://vo.iucaa.ernet.in/~voi/cplusparser.htm
Streaming and non-streaming versions
• Wrappers & Containers– For leveraging legacy code or high-end resources– IRAF’s VO Services: accessing IRAF capabilities via Web Serivces
for VO applications– NESSSI: Gateway for deploying VO applications on the TeraGrid– Starlink: integrated support for VO formats, services– VOclient: in development
top related