Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Crash Course A Tutorial Introduction for C++ Programmers.

Similar presentations


Presentation on theme: "Java Crash Course A Tutorial Introduction for C++ Programmers."— Presentation transcript:

1 Java Crash Course A Tutorial Introduction for C++ Programmers

2 So what the heck is Java (besides coffee, that is)? n A programming language. u Syntax and constructs are very similar to C++ n A virtual platform u Java Virtual Machine is a software machine or hypothetical chip u Since its virtual, it can be implemented on any hardware Cross-platform distribution achieved via.class binary file of bytecodes (instead of machine-dependent machine code) Write Once, Run Anywhere n A class library u Standard APIs for GUI, data storage, processing, I/O, and networking.

3 Getting Java Brewing… 1.Download the latest Java SDK from nThe SDK is a command-line based set of tools 2.A Text Editor: our choice is, of course, Emacs! 3.Web-browser thats java-enabled (optional) 4.IDE like BlueJ from or JCreator from (optional)http://www.bluej.org 5.Some introductory links/guides/tutorials: n ompile.html ompile.html n n

4 Mechanics of Writing Java Programs Create a Java source file. Must have the.java extension and contain only one public class. Compile the source file into a bytecode file. The Java compiler, 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. The Java 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.

5 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

6 Applications vs. Applets n A Java application: u Is a standalone program Is interpreted by the Java Virtual Machine and run using the java command Contains a main() method. n A Java applet: u Runs within a Java-enabled Web browser extends the Applet or JApplet class (Inheritance) Contains an init() or a paint() method (or both). n To create an applet, you'll perform the same basic steps: 1. Create a Java source file ( NameOfProgram.java ) and an HTML file ( NameOfHTMLFile.html ) 2. Compile the source file ( NameOfProgram.class ) 3. Run the program (either using java NameOfProgram (application) or appletviewer NameOfHTMLFile.html (applet))

7 Java notes for C++ programmers n Everythings an object u Every object inherits from java.lang.Object n No code outside of the class definition! No global variables (use static variables instead) n Single inheritance only Instead, implement interfaces All classes are defined in.java files One top level public class per file F The file has to have the same name as the public class! n Syntax is similar (control structures are very similar). u Primitive data types are similar But a bool is not an int To print to stdout, use System.out.println()

8 Requisite First Program (Application Version) Put in HelloWorld.java: public class HelloWorld { public static void main(String args[]) { System.out.println("Hello World"); }

9 Compiling and Running HelloWorld.java javac HelloWorld.java java HelloWorld HelloWorld.class compile run bytecode source code

10 So whats going on? The Java bytecode and interpreter at work! Bytecode is an intermediate representation of the program (the class file) u Think of it as the machine-code for the Java Virtual Machine The Java interpreter ( java ) starts up a new Virtual Machine The VM starts executing the users class by running its main() method

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

12 Cool Applet Methods n 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 n Funky methods on Applet AudioClip getAudioClip(URL url) : gets audioClip object (play with audioClip.play() ) Image getImage(URL url) : starts asynchronous image loading java.net.URL constructor takes normal string argument (used to store URLs) void showDocument(URL url) : tells browser to load new document void showStatus(String msg) : writes to browser status line n Applet repainting paint() : defaults to nothing update() : clears screen, calls paint() repaint() : passes events to Motif/Win32 dont override/change this

13 Java Language Basics Data types same as in C++ (except bool ) u bool,char,byte,short,int,long,float, double,string, etc. n Operators (same as C++) u Assignment: =, +=, -=, *=, … u Numeric: +, -, *, /, %, ++, --, … u Relational: ==. !=,, =, … u Boolean: &&, ||, ! u Bitwise: &, |, ^, ~, >, … n Control Structures more of what you expect: 1. conditional: if, if else, switch 2. loop: while, for, do 3. break and continue not an int!

14 Classes, References, & Packages n Classes and Objects u All Java statements appear within methods, and all methods are defined within classes. u Java classes are very similar to C++ classes (same concepts). u Instead of a standard library, Java provides a lot of Class implementations or packages n What are packages? u You can organize a bunch of classes and interfaces into a package (or library of classes) F defines a namespace that contains all the classes. Use the import keyword to include the packages you need F import java.applet.*; u You need to use some java packages in your programs F java.awt (Abstract Windowing Toolkit), java.io (for Files, etc.), java.util (for Vectors, etc.) n References u No pointers everythings a reference! u classes u arrays

15 Type Conversions (Skip) n conversion between integer types and floating point types. this includes char No automatic conversion from or to the type boolean ! n You can force conversions with a cast – same syntax as C/C++. int i = (int) 1.345;

16 Exceptions n When a program carries out an illegal action, an exception is generated. n Terminology: u throw an exception: signal (in the method header) that some condition or error has occurred but we want to pass the buck and not deal with it. u catch an exception: deal with the error (or whatever) ourselves inside the function/method. u Catch it using a try/catch block (next slide). n In Java, exception handling is necessary (forced by the compiler compilation errors!) u Except for RunTimeExceptions

17 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

18 Exception Handling n Exceptions take care of handling errors u instead of returning an error, some method calls will throw an exception. n Can be dealt with at any point in the method invocation stack. u But if no method in the hierarchy handles it, results in an unchecked exception which generates a compiler error (unless its a RunTimeException) n Forces the programmer to be aware of what errors can occur and to deal with them.

19 Defining a Class One top level public class per.java file. Typically end up with many.java files for a single program with at least one containing a static public main() method (if theyre applications). n Class name must match the file name! u The compiler/interpreter use class names to figure out what the file name is. n Classes have these three features: u A constructor thats used to allocate memory for the object, initiailize its elements, and return a reference to the object u Methods (function members) u Fields (data members)

20 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; }

21 Objects and new You can declare a variable that can hold an object: Point p; But this doesnt create the object! You have to use new : Point p = new Point(3.1,2.4); new allocates memory and the garbage collector reclaims unused memory

22 Using Java objects n Just like C++: u object.method() or object.field n BUT, never like this (no pointers!) u object->method() or object->field n Event driven model: Objects register to receive (and respond to) certain messages like button presses, mouse clicks, etc. (e.g., mouseUp(), mouseDown(), keyUp(), keyDown() )

23 Strings are special n 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!);

24 Arrays n Arrays are supported as a second kind of reference type (objects are the other reference type). n Although the way the language supports arrays is different than with C++, much of the syntax is compatible. however, creating an array requires new n Index starts at 0. n Arrays cant shrink or grow. u e.g., use Vector instead. n Each element is initialized. n Array bounds checking (no overflow!) u ArrayIndexOutOfBoundsException n Arrays have a.length

25 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

26 Array Literals You can use array literals like C/C++ (no need for new keyword): int[] foo = {1,2,3,4,5}; String[] names = {Joe, Sam};

27 Reference Types n Objects and Arrays are reference types n Primitive types are stored as values n Reference type variables are stored as references (pointers that we cant mess with)

28 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 Point object in memory!

29 Passing arguments to methods n Primitive types: the method gets a copy of the value. Changes wont show up in the caller Pass by value n Reference types: the method gets a copy of the reference, the method accesses the same object Pass by reference n There is no pass by pointers!

30 Comparing Reference Types n Comparison using == means: u Are the references the same? F Do they refer to the same object? n Sometimes you just want to know if two objects/arrays are identical copies. Use the.equals() method F You need to write this for your own classes! n All objects and arrays are references!

31 Inheritance Use the extends keyword to inherit from a super (or parent) class n No multiple inheritance Use implements to implement multiple interfaces (abstract, virtual classes) Use import instead of #include (not exactly the same but pretty close) to include packages (libraries)

32 Using Documentation Comments Documentation comments are delimited by /** and */ javadoc automatically generates documentation u Copies the first sentence of each documentation comment to a summary table F Write the first sentence with some care! n For each method/class, followed by the parameter name and a short followed by a description of the return for author info, etc. Need to use javadoc –author for this…

33 javadoc n The Java Standard calls for every class, every method, every parameter, and every return value to have a comment n Write the method comments first! u If you cant explain what a class or method does, you arent ready to implement it! n How to create HTML documentation: Type: javadoc *.java in the directory containing your source code This produces one HTML file for each class and an index.html file u Documenation is together with code! Must come immediately before the class, method, etc.

34 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) to listen for button events A Gooey GUI! What does an applet with multiple buttons and a text field look like? Well develop this in more detail in lab but lets just see it (in all its gory detail) here in ClickMe.java:

35 It dont mean a thing… n Adding Swing to GUI applets/applications is easy: Add import javax.swing.*; or import java.awt.swing.*; u Use JApplet instead of Applet, JButton instead of Button, JTextField instead of TextField, etc. F These are from the JFC (hence, all the J prefixes) In addition, you need to add components to the correct ContentPane by doing the following in the init() fxn: 1. Use JPanel contentPane; to declare it and contentPane = new JPanel(); to initialize a new contentPane Could also have used Container contentPane = getContentPane () if our class extends JFrame 2. add everything to that contentPane using a statement like contentPane.add(button1); 3. Finally, do a setContentPane(contentPane); (all in the init() function) to make this the active contentPane

36 GridBagLayout n Instead of the default FlowLayout (left-to-right), use the GridLayout or GridBagLayout to add buttons and other GUI elements along the grid n To call GridLayout, just use: setLayout(new GridLayout(9,3)); for AWT or contentPane.setLayout(new GridLayout(9,3)); for Swing n GridLayouts first argument is the number of rows (0 for unlimited) and the second argument is the number of columns

37 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<3; i++) { text[i] = new JTextField(20); contentPane.add(text[i]); button[i] = new JButton(String.valueOf(i)); contentPane.add(button[i]); button[i].addActionListener(this); } setContentPane(contentPane); } public void actionPerformed(ActionEvent e) { for (int i=0; i<3; i++) { if (e.getSource() == button[i]) { text[i].setText("Clicked Button #" + i); } An example of a Swing-based GridLayout applet:

38 Concurrent Multi-threaded Programming n Java is multithreaded! u Threads are easy to use. n Two ways to create new threads: u Extend java.lang.Thread Override run() method. u Implement Runnable interface Include a run() method in your class. u Usually, youll implement the Runnable interface n How to implement the Runnable interface: Add a public void start() function: This is where youll initialize the thread and start() it Add a public void stop() function: This is where youll set the boolean stopFlag to true Add a public void run() function: This is where youll call repaint() to paint each new frame and handle any synchronized variables or methods

39 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 put threads on hold and wake them up again (e.g., to implement a pause or suspend feature) u Must be called within a synchronized block

40 Double-buffering n Composing an image off-screen to avoid flickering u Not needed with Swing objects (already double-buffered!) n 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() : u 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: u Erase the previous image (with a big blank rectangle) u Do all new drawing to the offscreen graphics context u 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

41 Some Random Links n mponents/components.html mponents/components.html n mponents/toplevel.html mponents/toplevel.html n mponents/layeredpane.html mponents/layeredpane.html


Download ppt "Java Crash Course A Tutorial Introduction for C++ Programmers."

Similar presentations


Ads by Google