Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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 HelloWorld Hello world! HelloWorld.java T HE US N ATIONAL V IRTUAL O BSERVATORY

2 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 HelloWorld Hello world! HelloWorld.java T HE US N ATIONAL V IRTUAL O BSERVATORY

3 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)

4 7 September 2006NVO Summer School 2006 - Aspen Quick Tour of a Java Program see 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() { }

5 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 class per file. Quick Tour of a Java Program see Hello.java

6 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 class per file. Every class is part of a package. Quick Tour of a Java Program see Hello.java

7 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 class per file. Every class is part of a package. Declare other classes well be using Quick Tour of a Java Program see Hello.java

8 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 class per file. Every class is part of a package. Declare other classes well be using Comments! Quick Tour of a Java Program see Hello.java

9 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 class per file. Every class is part of a package. Declare other classes well be using Special commenting style for producing extractable documentation Comments! Quick Tour of a Java Program see Hello.java

10 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 class per file. Every class is part of a package. Declare other classes well be using Member fields hold a class internal data Special commenting style for producing extractable documentation Comments! Quick Tour of a Java Program see Hello.java

11 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 class per file. Every class is part of a package. Declare other classes well be using Member fields hold a class Internal data Constructor function is called to when a Hello object is created. Special commenting style for producing extractable documentation Comments! Quick Tour of a Java Program see Hello.java

12 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 Program see Hello.java

13 7 September 2006NVO Summer School 2006 - Aspen Quick Tour of a Java Program see 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(); }

14 7 September 2006NVO Summer School 2006 - Aspen Quick Tour of a Java Program see Hello.java Methods! A main method turns a class into an 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(); }

15 7 September 2006NVO Summer School 2006 - Aspen Quick Tour of a Java Program see Hello.java Methods! A main method turns a class into an application. Heres how you create 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(); }

16 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 Program see Hello.java Methods! A main method turns a class into an application. Heres how you create a Hello object. Heres how you call a Hello method.

17 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 Program see Hello.java Methods! A main method turns a class into an application. Heres how you create a Hello object. Heres how you call a Hello method. Dont forget: –Every executable statement ends in a semicolon (;) –Methods and classes are enclosed in braces ({ })

18 7 September 2006NVO Summer School 2006 - Aspen Packages and the CLASSPATH Every class belongs to a package –Package names define a namespace Allows classes with the same name can come from different packages and used in the same program –Package names are hierachical and imply a directory structure net.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

19 7 September 2006NVO Summer School 2006 - Aspen Packages and the CLASSPATH Every class belongs to a package –Package names define a namespace Allows classes with the same name can come from different packages and used in the same program –Package names are hierachical and imply a directory structure net.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

20 7 September 2006NVO Summer School 2006 - Aspen Types, Classes, and Objects Primitive types boolean, float, double, int, long, short, byte, enum, void Class = data + functions on that data Java-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 concept e.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 references int a = b; // not a reference: a copy of bs value is put into a Hello myhello = greeting; // no copy of the data is made –Never need to explicitly delete objects: Garbage Collection!

21 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)

22 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 allowed Hello 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

23 7 September 2006NVO Summer School 2006 - Aspen Interacting with Objects Whats this ? –automatic variable referring to current object public void setWho(String who) { this.who = who; } Whats null ? –Special value for object variables that do not point to an instantiated object –Default value for objects String name; // Equivalent String name = null; // Equivalent if (name == null) { … } –NullPointerException : an error thrown if one attempts to use. on a object = null if (name.length() > 0) { // Ouch! Throws an error if name=null … }

24 7 September 2006NVO Summer School 2006 - Aspen Interacting with Objects Whats static ? –Data/method shared by all instances of a class Often used to declare constant data public 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! … }

25 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 array int[] b = new int[4]; // length of 4, values set to 0 words = new String[3]; // length of 4; each value is null words = new String[] { the, quick, brown, fox }; –An array index is zero-based: a[0] is the 1 st element –Arrays are objects Contain public member called length for(int i=0; i < b.length; b++) { b[i] = i; } –Multidimensional arrays same as in C Array classes Defined in java.util package e.g., Vector, ArrayList, Stack –Can only hold non-primitive values

26 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 array int[] b = new int[4]; // length of 4, values set to 0 words = new String[3]; // length of 4; each value is null words = new String[] { the, quick, brown, fox }; –An array index is zero-based: a[0] is the 1 st element –Arrays are objects Contain public member called length for(int i=0; i < b.length; b++) { b[i] = i; } –Multidimensional arrays same as in C Array classes Defined in java.util package e.g., Vector, ArrayList, Stack –Can only hold non-primitive values

27 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)

28 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) { –Its incredibly easy!

29 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 –Cant be instantiated themselves; must be subclassed Some functions are defined but dont 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 Whats the use of a class/interface that doesnt provide implementations for all its methods?

30 7 September 2006NVO Summer School 2006 - Aspen How to extend a class through inheritance 1.Use extends in the class definition public class SpiralGalaxy extends Galaxy { } 2.Add any new data members 3.Add constructors –Constructors are not inherited; however, you can call the parents 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 parents version public Population getStellarPopulation() { Population pop = super.getStellarPopulation() … // manipulate population return pop; }

31 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() { … }

32 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 waymore 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 exceptions 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)

33 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 waymore 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 exceptions 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)

34 7 September 2006NVO Summer School 2006 - Aspen Polymorphism Whats the use of a class/interface that doesnt provide implementations for all its methods? You can refer to a specific subclass instance using a more generic reference FileWriter out = new FileWriter(file); or Writer 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

35 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

36 7 September 2006NVO Summer School 2006 - Aspen Common Exceptions NullPointerException The 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. NoClassDefFoundError The usual explanation: Your CLASSPATH does not include the indicated class or package How to fix it: Adjust your CLASSPATH; make sure it includes all the directories or jar files needed. ArrayIndexOutOfBoundsException The usual explanation: While accessing array elements via [], e.g. a[i], the index i = a.length How to fix it: Look for the use of [] in the indicated line; the exception message gives the value of the offending index.

37 7 September 2006NVO Summer School 2006 - Aspen Handling Exceptions in code Use a try-catch block try { // 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 exceptions 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

38 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 RuntimeException s Ex: NullPointerException function user must either –Enclose the method call in a try-catch block, or –Add exception to calling functions throws clause

39 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 RuntimeException s Ex: NullPointerException function user must either –Enclose the method call in a try-catch block, or –Add exception to calling functions throws clause

40 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/ http://terapix.iap.fr/cplt/docs/libVOTable/ VOTable Parser in ANSI C –VO-Indias VOTable Parsers in C++: http://vo.iucaa.ernet.in/~voi/cplusparser.htm http://vo.iucaa.ernet.in/~voi/cplusparser.htm Streaming and non-streaming versions Wrappers & Containers –For leveraging legacy code or high-end resources –IRAFs 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


Download ppt "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."

Similar presentations


Ads by Google