Intoduction to Java

Java is downloaded onto a local hardrive, where it runs its applications

For this reason, yhou can run simple animation and games on the web

Java:
=> derived from C++, syntax and declarations similar to C++
=> class library/hierarchy, (similar to SmallTalk)
=> code is compiled into a language independent intermediate form
=> Sun maintains 'official' standard, still has lots of fragmentation,(Micorsoft J++, etc)

myths about Java:
* is only for web applications
* is totally transparent across platforms
* is simple, (I/O can be difficult to use)

JDK Tools for Java

1) some text-based editor (notepad, pico, emacs, vi) 2) Java compiler, (found in 'jdk') javac is compiler .java, (use this extension when saving file from text editor) javac will convert the text file, (.java), to a .class extension 3a) Java interpreter, (for stand-alone application) java actually RUNS the application of .class OR 3b) Java enabled browser, or a utility called 'appletviewer.exe' 4) Java byte code verifier, (embedded in interpreter)

Simple Java Applet

//Hello World Applet import java.applet.Applet; //use this library when building applets import java.awt.Graphics; //needed to draw text or graphics public class Welcome extends Applet { public void paint(Graphics g) { g.drawString("Welcome to the World of", 25, 25); g.drawString("Java Programming", 25, 40); } }

Sample HTML Code to Run Applet in Browser Window

<html> <applet code="Welcome.class" width=275 height=100> </applet> </html> Click to see Welcome.java output

Object Oriented Programming in Java
Instance Variable declaration

point P1 = new Point(2,11); scrollbar bar = new Scrollbar(); <= a constructor point P1 = window.location(); string String1 = new String("A String"); * This can be shortened to: string String2 = "Another String";

Java conventions for naming:

1) use lower case for first letter of instance variable name, (firstName)

2) begin class names with uppercase

3) constants in all uppercase

Simple I/O and Arithmetic

//simple input/output and arithmetic example import java.applet.Applet; import java.awt.*; //import entire awt library public class Addition extends Applet { Label prompt; //prompt user for input TextField input; //text box to use for user input value int number; //user input value int sum; //sum of user input values //set up GUI components and initialize variables public void init() { prompt = new Label("Type an integer and press <Enter>"); input = new TextField(10); add(prompt); //add prompt to applet window add(input); //add text field to applet window sum = 0; } //process user actions public boolean action(Event e, Object o) { number = Integer.parseInt(o.toString()); //get number user typed input.setText(""); //clear entry field sum = sum + number; showStatus(Integer.toString(sum)); //display result on status line return true; //indicate normal exit } } Click to see Addition.java output

To get the applet to perform we need to use event driven programming.


The "action" will only be called when the user presses the <Enter> key.


To treat atomic variables like int as classes the is an Integer class
in Java with its own messages. In this example, Integer provides 
typecasting services to convert the input from string to int.

The program result is displayed on the browser satus line (using 
Netscape). A running sum will be computed and displayed until the
browser reloads another page or is shut down.

Java Data Types

2 basic data types - primitives, (built in), and reference, (pointer based)

Primitives:
a) boolean 
     flag1 = false;
     flag2 = (6 < 7);
     flag3 = !true;

b) char
     16 bit unsigned int
     char c0 = 3;
     char c1 = 'Q';
     char c2 = '\u0000';      //smallest
     char c3 = '\uffff';      //largest
     char c4 = '\b';          //back space
     char c5 = '\n';          //new line
     char c6 = '\"';          //double quote

c) byte   
     8 bit 2's compliment

d) short 
     16 bit 2's compliment

e) int
     32 bit 2's compliment
	int i0 = 0;
 	int i1 = -12345;
	int i2 = OxCafeBabe;	//'magic numbers' for .class files

f) long 
     64 bit 2's compliment

g) float
     32 bit IEEE 754
	-1.23f		    
	6.02E23f       //exponential - can use either upper or lower case

h) double 
     64 bit IEEE 754

Any other type is a 'reference'.

Typecasts - explicit

converting among various types:


type2 type2Var = (type2)type1Var;


Arithmetic Operators

operators meaning +,- addition, subtraction *, /, % multiplication, division, modulo ++, -- prefix/postfix increment/decrement <<, >>, >>> signed and unsigned shift ~ bitwise compliment &, |, ^ bitwise and, or, not

Conditional Operators

a) if(expression) statement1; else statement2; b) expression ? val1 : val2; //val1 if true, val2 if false c) switch(someInt) { case val1: statement1; break; case val2: statement2; break; | | | default: statement; }

Boolean Operators

operators meaning ==, != equal, not equal, same as C++ <, <=, >, >= less than, less or equal, greater than, greater or equal &&, || logical and, logical or ! logical negation

Loops

a) pre-test: // may not execute at all i = 0; while(i < bound) { statement; i++; } b) post-test: // will execute at least once i = 0; do { statement; }while( i < bound); c) for loop: for(i = 0; i < bound; i++) { statement; i++ }

Input and Output

a) print - standard out, (like 'cout' in C++) (class PrintStream) system.out.println(arg); //prints a new line each time primitive types to strings: string.valueOf(); non-string objects to strings toString(); // method system.out.flush(); // prints all data left in buffer system.err)(); // prints standard error message b) standard input, (like 'cin' in C++) DataInputStream in = new DataInputSteam(system.in); string urlString = in.ReadLine(); char urlChar = in.read Char();

Reference Types

import java.awt.point 1) Point p1 = new Point(1,2); // (1,2) is x,y coordinates, p1.x, p1.y 2) Point p2 = p1; // this may result in aliasing problems, see below public static Point triple(Point p) { p = new Point(p.x * 3, p.y * 3); return p; //this would create memory leak in C++ } triple(p2); // in Java, no explicit 'delete' is needed here // as 'garbage collection' is used

Arrays

Like vectors, except vectors can grow in size - arrays cannot int[] values = new int[2]; Point[] points = new Point[5]; // an array with 5 elements values[0] = 10; values[1] = 100; for(int i = 0; i < point.length; i++) { points[i] = new point(i * 2, i * 4); // new values for // x & y coordinates }

Multi-Dimensional Arrays

int[][] values = new int[12][14]; // init a 12 x 14 array for(int i = 0; i < 12; i++) { for(int j = 0; j < 14; j++) { values[i][j] = 0; } } String[][] name0={"John", "Q", "Public"}; name1={"Jane", "Doe"}; name2={"Pele"}; Since Java is an interpretted language, this is allowable, not all array entries need to have the same dimensions
 

A Java-based Calculaor

Java can be used to parse text as would be needed in a natural language type user interface. Click here to view an example of a Java applet that evaluates simple expressions according that conform to a simple calculator grammar.

Graphics

Java has several primatives for drawing simple shapes. Click here to view an example of a Java applet that draws a table lamp.

GUI Development

Java also allows the development of graphical user interfaces. Click here to view an example of a Java applet that contains slidebars and push button. This particular web page also contains some Javascript controls that interact with Java controls on the same page.