Extra Java Crash Course

download Extra Java Crash Course

of 41

Transcript of Extra Java Crash Course

  • 8/8/2019 Extra Java Crash Course

    1/41

    Java Crash CourseA Tutorial Introduction for C++ Programmers

  • 8/8/2019 Extra Java Crash Course

    2/41

  • 8/8/2019 Extra Java Crash Course

    3/41

    Getting Java Brewing1. Download the latest Java SDK from http://java.sun.com

    The SDK is a command-line based set of tools2. A Text Editor: our choice is, of course, Emacs!

    3. Web-browserthats java-enabled (optional)

    4. IDE like BlueJ from http://www.bluej.org or JCreator fromhttp://www.jcreator.com (optional)

    5. Some introductory links/guides/tutorials: http://developer.java.sun.com/developer/onlineTraining/Programming/BasicJava1/c

    ompile.html

    http://www.horstmann.com/ccc/c_to_java.pdf

    http://www.csd.uu.se/datalogi/cmtrl/oopj/vt-2000/slides/OOPJ-1-04.pdf

    http://java.sun.com/http://www.bluej.org/http://www.jcreator.com/http://developer.java.sun.com/developer/onlineTraining/Programming/BasicJava1/compile.htmlhttp://developer.java.sun.com/developer/onlineTraining/Programming/BasicJava1/compile.htmlhttp://www.horstmann.com/ccc/c_to_java.pdfhttp://www.csd.uu.se/datalogi/cmtrl/oopj/vt-2000/slides/OOPJ-1-04.pdfhttp://www.csd.uu.se/datalogi/cmtrl/oopj/vt-2000/slides/OOPJ-1-04.pdfhttp://www.csd.uu.se/datalogi/cmtrl/oopj/vt-2000/slides/OOPJ-1-04.pdfhttp://www.csd.uu.se/datalogi/cmtrl/oopj/vt-2000/slides/OOPJ-1-04.pdfhttp://www.csd.uu.se/datalogi/cmtrl/oopj/vt-2000/slides/OOPJ-1-04.pdfhttp://www.csd.uu.se/datalogi/cmtrl/oopj/vt-2000/slides/OOPJ-1-04.pdfhttp://www.csd.uu.se/datalogi/cmtrl/oopj/vt-2000/slides/OOPJ-1-04.pdfhttp://www.csd.uu.se/datalogi/cmtrl/oopj/vt-2000/slides/OOPJ-1-04.pdfhttp://www.horstmann.com/ccc/c_to_java.pdfhttp://developer.java.sun.com/developer/onlineTraining/Programming/BasicJava1/compile.htmlhttp://developer.java.sun.com/developer/onlineTraining/Programming/BasicJava1/compile.htmlhttp://www.jcreator.com/http://www.bluej.org/http://java.sun.com/
  • 8/8/2019 Extra Java Crash Course

    4/41

    Mechanics of Writing Java Programs

    Create a Java source file.Must have the .java extension andcontain only one public class.

    Compile the source file into a bytecode file.The Javacompiler, javac, takes your source file and translates its text into

    instructions that the Java Virtual Machine(Java VM) can understand.The compiler puts these instructions into a .class bytecode file.

    Run the program contained in the bytecode file.TheJava VM is implemented by a Java interpreter, java. This interpreter

    takes your bytecode file and carries out the instructions by translating

    them into instructions that your computer can understand.

  • 8/8/2019 Extra Java Crash Course

    5/41

    Putting it all together

    public class Hello {

    public static void main(String args[]) {

    System.out.println(Hello, world!);

    }

    }

    1. Put in: Hello.java

    2. Compile with: javac Hello.java

    Creates Hello.class

    3. Run with: java Hello

  • 8/8/2019 Extra Java Crash Course

    6/41

    Applications vs. Applets A Java application:

    Is a standaloneprogram

    Is interpretedby the Java Virtual Machine and run using the javacommand

    Contains a main() method.

    A Java applet:

    Runs withina Java-enabled Web browser

    extends the Applet or JApplet class (Inheritance)

    Contains an init() or a paint() method (or both).

    To create an applet, you'll perform the same basic steps:

    1. Createa Java source file (NameOfProgram.java) and an HTMLfile (NameOfHTMLFile.html)

    2. Compilethe source file (NameOfProgram.class)

    3. Runthe program (either using java NameOfProgram(application) or appletviewer NameOfHTMLFile.html

    (applet))

  • 8/8/2019 Extra Java Crash Course

    7/41

    Java notes for C++ programmers Everythings an object

    Every object inherits from java.lang.Object

    No code outside of the class definition!

    No global variables (use static variables instead)

    Single inheritance only

    Instead, implementinterfaces

    All classes are defined in .java files

    One top level public class per file

    The file has to have the same name as the public class!

    Syntax is similar (control structures are very similar).

    Primitive data types are similar

    But a bool is not an int

    To print to stdout, use System.out.println()

  • 8/8/2019 Extra Java Crash Course

    8/41

    Requisite First Program (ApplicationVersion)

    Put in HelloWorld.java:

    public class HelloWorld {

    public static void main(String args[]) {

    System.out.println("Hello World");

    }

    }

  • 8/8/2019 Extra Java Crash Course

    9/41

    Compiling and Running

    HelloWorld.java javac HelloWorld.java

    java HelloWorld

    HelloWorld.class

    compile

    run

    bytecode

    source code

  • 8/8/2019 Extra Java Crash Course

    10/41

    So whats going on?The Java bytecode and interpreter at work!

    Bytecodeis an intermediate representation of theprogram (the class file)

    Think of it as the machine-code for the Java Virtual

    Machine

    The Java interpreter (java) starts up a newVirtual Machine

    The VM starts executing the users class byrunning itsmain() method

  • 8/8/2019 Extra Java Crash Course

    11/41

    Put in HelloWorld.java:

    import java.awt.Graphics;public class HelloWorld extends java.applet.Applet {

    public void paint(Graphics g) {

    g.drawString("Hello World, 35, 15);

    }

    }

    Put in test.html:

    Test the applet

    Test the applet

    Requisite First Program (Applet Version)

  • 8/8/2019 Extra Java Crash Course

    12/41

    Cool Applet Methods

    Basic methods on Applet

    init(): called once for your applet start(): called every time you enter the page

    stop(): called every time you leave the page

    destroy(): called when your page is discarded

    Funky methods on Applet

    AudioClipgetAudioClip(URL url): gets audioClip object (playwith audioClip.play())

    Image getImage(URL url): starts asynchronous image loading

    java.net.URL constructor takes normal string argument (used tostore URLs)

    void showDocument(URL url): tells browser to load new

    document void showStatus(String msg): writes to browser status line

    Applet repainting paint(): defaults to nothing

    update(): clears screen, callspaint()

    repaint(): passes events to Motif/Win32dont override/change this

  • 8/8/2019 Extra Java Crash Course

    13/41

    Java Language Basics

    Data types same as in C++ (except bool)

    bool,char,byte,short,int,long,float,

    double,string, etc.

    Operators (same as C++)

    Assignment: =, +=, -=, *=,

    Numeric: +, -, *, /, %, ++, --,

    Relational: ==. !=, , =,

    Boolean: &&, ||, !

    Bitwise: &, |, ^, ~, ,

    Control Structures more of what you expect:

    1. conditional: if, if else, switch

    2. loop: while, for, do

    3.break and continue

  • 8/8/2019 Extra Java Crash Course

    14/41

    Classes, References, & Packages Classes and Objects

    All Java statements appear within methods, and all methods are

    defined within classes. Java classes are very similar to C++ classes (same concepts). Instead of a standard library, Java provides a lot of Class

    implementations or packages

    What are packages? You can organize a bunch of classes and interfaces into a package

    (or libraryof classes) defines a namespacethat contains all the classes.

    Use the import keyword to includethe packages you need import java.applet.*;

    You need to use some java packages in your programs

    java.awt (Abstract Windowing Toolkit), java.io (for Files, etc.), java.util(for Vectors, etc.)

    References No pointerseverythings a reference! classes arrays

  • 8/8/2019 Extra Java Crash Course

    15/41

  • 8/8/2019 Extra Java Crash Course

    16/41

    Exceptions

    When a program carries out an illegal action, anexceptionis generated.

    Terminology:

    throw an exception: signal (in the method header)

    that some condition or error has occurred but wewant to pass the buck and not deal with it.

    catch an exception: deal with the error (or whatever)ourselves inside the function/method.

    Catch it using a try/catchblock (next slide).

    In Java, exception handling is necessary (forced bythe compiler compilation errors!)

    Except for RunTimeExceptions

  • 8/8/2019 Extra Java Crash Course

    17/41

    Try/Catch/Finally

    try {// code that can throw an exception

    } catch (ExceptionType1 e1) {

    // code to handle the exception

    } catch (ExceptionType2 e2) {// code to handle the exception

    } catch (Exception e) {

    // code to handle other exceptions

    } finally {// code to run after try or any catch

    }

    This block is always run

  • 8/8/2019 Extra Java Crash Course

    18/41

    Exception Handling

    Exceptions take care of handling errors

    instead of returning an error, some method calls willthrow an exception.

    Can be dealt with at any point in the methodinvocation stack.

    But if no method in the hierarchy handles it, resultsin an unchecked exception which generates acompiler error (unless its a RunTimeException)

    Forces the programmer to be aware of what errorscan occur and to deal with them.

  • 8/8/2019 Extra Java Crash Course

    19/41

    Defining a Class One top level public class per .java file.

    Typically end up with many .java files for a singleprogram with at least one containing a staticpublic main()method (if theyre applications).

    Class name must match the file name!

    The compiler/interpreter use class names to figure outwhat the file name is.

    Classes have these three features:

    A constructorthats used to allocate memory for theobject, initiailize its elements, and return a referenceto the object

    Methods(function members)

    Fields(data members)

  • 8/8/2019 Extra Java Crash Course

    20/41

    A Sample Class

    public class Point {

    public Point(double x, double y) {

    this.x = x; this.y=y;

    }

    public double distanceFromOrigin(){

    return Math.sqrt(x*x+y*y);

    }

    private double x,y;

    }

  • 8/8/2019 Extra Java Crash Course

    21/41

    Objects and new

    You can declare a variable that can hold an object:

    Point p;

    But this doesnt create the object! You have to usenew:

    Point p = new Point(3.1,2.4);

    new allocates memory and the garbage collector

    reclaims unused memory

  • 8/8/2019 Extra Java Crash Course

    22/41

    Using Java objects

    Just like C++:object.method() or object.field

    BUT, never like this (no pointers!)

    object->method() or object->field

    Event driven model:

    Objects register to receive (and respond to) certain

    messageslike button presses, mouse clicks, etc.(e.g., mouseUp(), mouseDown(), keyUp(),keyDown())

  • 8/8/2019 Extra Java Crash Course

    23/41

    Strings are special

    You can initialize Strings like this:

    String blah = "I am a literal ";

    Or this ( + String operator):

    String foo = "I love " + CET375";

    Or this ( new operator):

    String foo = new String(Yummy FooBars!);

  • 8/8/2019 Extra Java Crash Course

    24/41

    Arrays

    Arrays are supported as a second kind of reference type(objects are the other reference type).

    Although the way the language supports arrays is differentthan with C++, much of the syntax is compatible.

    however, creating an array requires new Index starts at 0.

    Arrays cant shrink or grow.

    e.g., use Vector instead.

    Each element is initialized. Array bounds checking (no overflow!)

    ArrayIndexOutOfBoundsException

    Arrays have a .length

  • 8/8/2019 Extra Java Crash Course

    25/41

    Array Examples

    int x[] = new int[1000];

    byte[] buff = new byte[256];

    float[][] mvals = new float[10][10];

    int[] values;

    int total=0;

    for (int i=0;i

  • 8/8/2019 Extra Java Crash Course

    26/41

    Array Literals

    You can use array literals likeC/C++ (no need for new keyword):

    int[] foo = {1,2,3,4,5};

    String[] names = {Joe, Sam};

  • 8/8/2019 Extra Java Crash Course

    27/41

    Reference Types

    Objects and Arrays are reference types

    Primitive types are stored as values

    Reference type variables are stored as references(pointers that we cant mess with)

  • 8/8/2019 Extra Java Crash Course

    28/41

    Primitive vs. Reference Types

    int x=3;

    int y=x;

    Point p = new Point(2.3,4.2);

    Point t = p;

    There are two copies of

    the value 3 in memory

    There is only one Pointobject in memory!

  • 8/8/2019 Extra Java Crash Course

    29/41

    Passing arguments to methods

    Primitive types: the method gets a copy of thevalue. Changes wont show up in the caller

    Pass by value

    Reference types: the method gets a copy of thereference, the method accesses the same objectPass by reference

    There is no pass by pointers!

  • 8/8/2019 Extra Java Crash Course

    30/41

    Comparing Reference Types

    Comparison using == means:

    Are the referencesthe same?

    Do they referto the same object?

    Sometimes you just want to know if twoobjects/arrays are identical copies.

    Use the .equals() method

    You need to write this for your own classes!

    All objects and arrays are references!

  • 8/8/2019 Extra Java Crash Course

    31/41

    Inheritance

    Use the extends keyword to inherit from a super

    (or parent) class

    No multiple inheritanceUse implements to implement multiple interfaces

    (abstract, virtual classes)

    Use import instead of #include (not exactly

    the same but pretty close) to include packages(libraries)

  • 8/8/2019 Extra Java Crash Course

    32/41

    Using Documentation Comments

    Documentation comments are delimited by /**

    and */ javadoc automatically generates documentation

    Copies the firstsentence of eachdocumentationcommentto a summary table

    Write the first sentence with some care!

    For each method/class, supply:@param followed by the parameter name and a short

    explanation@return followed by a description of the return

    value

    @author for author info, etc.

    Need to use javadoc

    author for this

    j d

  • 8/8/2019 Extra Java Crash Course

    33/41

    javadoc

    The Java Standard calls for everyclass, every

    method, everyparameter, and everyreturn value tohave a comment

    Write the method comments first!

    If you cant explain what a class or method does, youarent ready to implement it!

    How to create HTML documentation:Type: javadoc *.java in the directory containing

    your source code

    This produces one HTML file for each class and anindex.html file

    Documenation is together with code!

    Must come immediatelybefore the class, method,etc.

    ooey What does an applet with multiple buttons and a text field look

  • 8/8/2019 Extra Java Crash Course

    34/41

    import java.applet.Applet;

    import java.awt.*;

    import java.awt.event.*;

    public class ClickMe extends Applet implements ActionListener {

    private TextField text1;

    private Button button1;

    public void init() {

    text1 = new TextField(20);add(text1);

    button1 = new Button (Click me please!);

    add(button1);

    button1.addActionListener(this);

    }

    public void actionPerformed(ActionEvent e) {

    String msg = new String (Hello, world!);

    if (e.getSource() == button1) {

    text1.setText(msg);

    }

    }}

    Add GUI elements in init()

    Add components to the

    current frame (AWT)

    Register a class (this one) tolisten for button events

    ooeylike? Well develop this in more detail in lab but lets just

    see it (in all its gory detail) here in ClickMe.java:

    It d t thi

  • 8/8/2019 Extra Java Crash Course

    35/41

    It dont mean a thing Adding Swing to GUI applets/applications is easy:

    Add import javax.swing.*; or importjava.awt.swing.*;

    Use JApplet instead of Applet, JButton instead of Button,JTextField instead of TextField, etc.

    These are from the JFC (hence, all the J prefixes)

    In addition, you need to add components to the correctContentPane by doing the following in the init() fxn:

    1. Use JPanel contentPane; to declareit andcontentPane = new JPanel(); to initializea newcontentPane

    Could also have used Container contentPane =getContentPane() if our class extends JFrame

    2. add everything to that contentPane using a statement likecontentPane.add(button1);

    3. Finally, do a setContentPane(contentPane); (all in theinit() function) to make this the active contentPane

    G idB L t

  • 8/8/2019 Extra Java Crash Course

    36/41

    GridBagLayout

    Instead of the default FlowLayout (left-to-right), use

    the GridLayout or GridBagLayout to add buttonsand other GUI elements along the grid

    To call GridLayout, just use:

    setLayout(new GridLayout(9,3)); for AWTor contentPane.setLayout(newGridLayout(9,3)); for Swing

    GridLayouts firstargument is the number of rows

    (0 for unlimited) and the secondargument is thenumber of columns

    n examp e o a w ng- ase r ayou app e :

    http://java.sun.com/docs/books/tutorial/uiswing/layout/GridDemo.html
  • 8/8/2019 Extra Java Crash Course

    37/41

    import java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;

    public class ButtonsArray extends JApplet implements ActionListener {

    private JTextField text[] = new JTextField[3];private JButton button[] = new JButton[3];

    private JPanel contentPane = new JPanel();

    public void init() {

    contentPane.setLayout(new GridLayout(3,2));

    for (int i=0; i

  • 8/8/2019 Extra Java Crash Course

    38/41

    Concurrent Multi-threaded Programming Java is multithreaded!

    Threads are easy to use.

    Two ways to create new threads: Extend java.lang.Thread

    Override run() method.

    Implement Runnable interface

    Include a run() method in your class. Usually, youll implement the Runnable interface

    How to implement the Runnable interface: Add a public void start() function:

    This is where youll initializethe thread and start() it Add a public void stop() function:

    This is where youll set the booleanstopFlag to true

    Add a public void run() function:

    This is where youll call repaint() to paint eachnew frame

    and handle any synchronizedvariablesor methods

    Th h i d St t t

  • 8/8/2019 Extra Java Crash Course

    39/41

    The synchronized Statement

    Instead of mutex (a binary semaphore), use

    synchronized:synchronized ( object ) {

    // critical code here

    }

    Also, declare a method as synchronized:synchronized int blah(String x) {

    // blah blah blah

    }

    Can also use wait() and notify() to putthreads on hold and wake them up again (e.g., toimplement a pause or suspend feature)

    Must be called within a synchronizedblock

    Double buffering

  • 8/8/2019 Extra Java Crash Course

    40/41

    Double-buffering

    Composing an image off-screen to avoid flickering

    Not needed with Swing objects (already double-buffered!) Create an offscreen graphics image and context:

    Image offscreen;

    Graphics offgraphics;

    Dimension offdim;

    Set them in init() method:offdim = getSize(); // Get size of applet first:

    offscreen = createImage(offdim.width,offdim.height); // Create offscreen image of same size:

    offgraphics = offscreen.getGraphics(); // Setup offscreen graphics context

    Add an update() method that simply calls paint(): Overriding update() prevents the OS from wiping off the applets previous

    drawings and, instead, immediately repaints (since wiping off causes flickering,too). Called automatically when repaint() is called.

    Do all drawing to offscreen graphics context in the paint() method: Erase the previous image (with a big blank rectangle) Do all new drawing to the offscreen graphics context Finally, draw the offscreen image to the screen like a normal image:gr.drawImage(offscreen,0,0,this); //offscreen is width of screen, so start at 0,0

  • 8/8/2019 Extra Java Crash Course

    41/41

    Some Random Links

    http://java.sun.com/docs/books/tutorial/uiswing/components/components.html

    http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html

    http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html

    http://java.sun.com/docs/books/tutorial/uiswing/components/components.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/components/components.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/components/components.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/components/components.html