Java: a Survival Guide and a bit about CC - PowerPoint PPT Presentation

1 / 40
About This Presentation
Title:

Java: a Survival Guide and a bit about CC

Description:

Hello world! HelloWorld.java. THE US NATIONAL VIRTUAL OBSERVATORY. 7 September 2006 ... a Hello World class and application. public class Hello implements Cloneable ... – PowerPoint PPT presentation

Number of Views:77
Avg rating:3.0/5.0
Slides: 41
Provided by: raymond90
Learn more at: http://www.us-vo.org
Category:
Tags: bit | guide | hello | java | survival

less

Transcript and Presenter's Notes

Title: Java: a Survival Guide and a bit about CC


1
Java a Survival Guide(and a bit about C/C)
THE US NATIONAL VIRTUAL OBSERVATORY
  • Ray Plante

HelloWorld.java
javac HelloWorld.java java HelloWorld Hello
world!
2
Java a Survival Guide(and a bit about C/C)
THE US NATIONAL VIRTUAL OBSERVATORY
  • Ray Plante

HelloWorld.java
javac HelloWorld.java java HelloWorld Hello
world!
Let's try Exercise 0
3
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
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
  • _at_param toWho a name for who we are
    saying hello to
  • /
  • public Hello(String toWho)
  • who toWho

5
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
  • _at_param toWho a name for who we are
    saying hello to
  • /
  • public Hello(String toWho)
  • who toWho

Define one class per file.
6
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
  • _at_param toWho a name for who we are
    saying hello to
  • /
  • public Hello(String toWho)
  • who toWho

Every class is part of a package.
Define one class per file.
7
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
  • _at_param toWho a name for who we are
    saying hello to
  • /
  • public Hello(String toWho)
  • who toWho

Every class is part of a package.
Declare other classes well be using
Define one class per file.
8
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
  • _at_param toWho a name for who we are
    saying hello to
  • /
  • public Hello(String toWho)
  • who toWho

Every class is part of a package.
Comments!
Declare other classes well be using
Define one class per file.
9
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
  • _at_param toWho a name for who we are
    saying hello to
  • /
  • public Hello(String toWho)
  • who toWho

Every class is part of a package.
Comments!
Declare other classes well be using
Define one class per file.
Special commenting style for producing extractable
documentation
10
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
  • _at_param toWho a name for who we are
    saying hello to
  • /
  • public Hello(String toWho)
  • who toWho

Every class is part of a package.
Comments!
Declare other classes well be using
Define one class per file.
Member fields hold a class internal data
Special commenting style for producing extractable
documentation
11
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
  • _at_param toWho a name for who we are
    saying hello to
  • /
  • public Hello(String toWho)
  • who toWho

Every class is part of a package.
Comments!
Declare other classes well be using
Define one class per file.
Member fields hold a class Internal data
Special commenting style for producing extractable
documentation
Constructor function is called to when a Hello
object is created.
12
Quick Tour of a Java Programsee Hello.java
13
Quick Tour of a Java Programsee Hello.java
/ 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()
Methods!
14
Quick Tour of a Java Programsee Hello.java
/ 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()
Methods!
A main method turns a class into an application.
15
Quick Tour of a Java Programsee Hello.java
/ 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()
Methods!
A main method turns a class into an application.
Heres how you create a Hello object.
16
Quick Tour of a Java Programsee Hello.java
/ 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()
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
Quick Tour of a Java Programsee Hello.java
/ 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()
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
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

19
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

Let's try Exercise 1
20
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)

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

24
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 String0
  • Hello.main(args) // call the static main()
    method directly
  • Static method cannot access non-static data!

25
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 int4 // length of 4, values
    set to 0
  • words new String3 // length of 4 each
    value is null
  • words new String the, quick, brown,
    fox
  • An array index is zero-based a0 is the 1st
    element
  • Arrays are objects
  • Contain public member called length
  • for(int i0 i
  • bi i

26
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 int4 // length of 4, values
    set to 0
  • words new String3 // length of 4 each
    value is null
  • words new String the, quick, brown,
    fox
  • An array index is zero-based a0 is the 1st
    element
  • Arrays are objects
  • Contain public member called length
  • for(int i0 i
  • bi i

Let's try Exercise 2
27
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
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
  • _at_param toWho a name for who we are saying
    hello to
  • /
  • public Hello(String toWho)
  • Its incredibly easy!

29
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
How to extend a class through inheritance
  • Use extends in the class definition
  • public class SpiralGalaxy extends Galaxy
  • Add any new data members
  • 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()
  • Add new and/or overriding methods
  • An overriding method may call parents version
  • public Population getStellarPopulation()
  • Population pop super.getStellarPopulation()

31
Implementing interfaces
  • List interface being supported with implements
  • public class SpiralGalaxy extends Galaxy
  • implements ClusterComponent
  • Provide implementations of methods in interface
  • public double getDarkMass()

32
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.NullPointerEx
    ception No Hello provided
  • at nvoss.basicjava.Hello.main(Hello.java9
    1)

33
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.NullPointerEx
    ception No Hello provided
  • at nvoss.basicjava.Hello.main(Hello.java9
    1)

Let's try Exercises 3 4
34
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
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
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. ai,
    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
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

38
The throws clause
  • A function must indicate what exceptions it might
    throw
  • public void loadData(Reader in)
  • throws IOException, ParseException
  • Except for RuntimeExceptions
  • Ex NullPointerException
  • function user must either
  • Enclose the method call in a try-catch block, or
  • Add exception to calling functions throws clause

39
The throws clause
  • A function must indicate what exceptions it might
    throw
  • public void loadData(Reader in)
  • throws IOException, ParseException
  • Except for RuntimeExceptions
  • Ex NullPointerException
  • function user must either
  • Enclose the method call in a try-catch block, or
  • Add exception to calling functions throws clause

Let's try Exercise 5
40
VO Software in C/C
  • Development in C/C has lagged behind other
    languages
  • Native libraries
  • libVOTable http//terapix.iap.fr/cplt/docs/libVOT
    able/
  • VOTable Parser in ANSI C
  • VO-Indias 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
  • 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
Write a Comment
User Comments (0)
About PowerShow.com