SDSU CS 596 Client-Server Programming
Java Basics

[To Lecture Notes Index]
San Diego State University -- This page last updated February 3, 1996
----------

Contents of Java Basics Lecture

  1. Java
    1. Why is Java so "Hot"?
    2. Basics
      1. Java Resources
      2. First Program
      3. Simple Types and Syntax
      4. IO
      5. Applets
        1. Complete syntax for the APPLET tag
      6. Basic Data Types
      7. Operations on Primitive Types
      8. Casting
      9. Default Values of Variables

Java


Why is Java so "Hot"?


Multi-platform development
Compiled code runs on multiple platforms
Solaris, Windows 95, Windows NT, Linux/x86, OS/2, AIX, Macs in Feb.

Distributed Programming
Embed programs in WWW home pages ( Applets )
Programs are down loaded and run locally
Networking class make client-server programming easier

Standard API
Makes GUI easier to program

Philosophical Differences with C/C++

C/C++
C is replacement for assemble language
C/C++ strive to give programmer control over machine and all performance issues.
Java
Distributed programming requires security

Basics

C and Java

Uses C/C++ basic syntax


Uses C/C++ basic data types
int, char, float, double, long, short, byte


"Pure" OO language
No stand alone functions
All code is part of a class

No explicit pointers
Uses garbage collection

Uses standard C/C++ control structures

Java Resources


Newsgroups
comp.lang.java
sdsu.java

Web Sites (few among hundreds)
Yahoo
http://www.yahoo.com/Computers_and_Internet/Languages/Java/
Gamelan - hundreds of examples
http://www.gamelan.com/
Source of Java - Sun
http://java.sun.com/
Local Copy of API
http://www.sdsu.edu/doc/java/
Local Copy of Sun's Java Tutorial
http://www.sdsu.edu/doc/JavaLanguageTutorial/index.html
Local Examples
On Rohan see: /opt/java/demo
Books
13 more books should come out by end of March
See http://sunsite.unc.edu/javafaq/books.html

Draft Language Specification

First Program

class JustOutput 
{
	public static void main( String args[] ) 
	{
		System.out.println("Hello World");
	}
}
Setting Path etc. for Java

Add to your path:
/opt/java/bin

Add CLASSPATH to your environment
setenv CLASSPATH '.:/opt/java/classes:/opt/local/lib/java/classes.zip'
Compiling & Running the Program

Place code in file: FirstProgram.java

rohan 34-> ls
FirstProgram.java
rohan 35-> javac FirstProgram.java
rohan 36-> ls
FirstProgram.java JustOutput.class
rohan 37-> java JustOutput
Hello World
Keywords
abstractdoimplementspackagethrow
booleandoubleimportprivatethrows
breakelseinstanceofprotectedtransient
byteextendsintpublictry
casefinalinterfacereturnvoid
catchfinnallylongshortvolatile
charfloatnewsuper
constifnullswitch
continuesynchronized
defaultthis

Reserved for possible future use (not used now)
byvaluecastfuturegenericgoto
inneroperatorouterrestvar
Boolean

true, false act like keywords but are boolean constants

Simple Types and Syntax



/* Standard C comment works
*/

// C++ comment works

/** Special comment for documentation
*/

/***** ???? */
class Syntax 
{
	public static void main( String args[] ) 
	{

		int aVariable = 5;

		double aFloat = 5.8;

		if ( aVariable < aFloat )
			System.out.println( "True" ) ;

		int b = 10;

		char c;

		c =
			'a';
	}
}

Style - Layout
class Syntax {

	public static void main( String args[] ) {

		int aVariable = 5;

		if ( aVariable < aFloat )
			System.out.println( "True" ) ;

	}
}

class Syntax 
{
	public static void main( String args[] ) 
	{

		int aVariable = 5;

		if ( aVariable < aFloat )
			System.out.println( "True" ) ;

	}
}

class Syntax 
	{
	public static void main( String args[] ) 
		{

		int aVariable = 5;

		if ( aVariable < aFloat )
			System.out.println( "True" ) ;

		}
	}

Style - Names

Sun API Classes use the following style:


Class names
ClassNames


Variable and function names
variableAndFunctionNames


Names of constants
NAMES_OF_CONSTANTS

Early Sample of Classes and Functions
class Main
	{

	public  static  void  main( String args[] ) 
		{
		hello();

		MyFirstClass  test  =  new  MyFirstClass();
		for  ( int k = 0;  k < 3;  k++)
			test.hello();
		}

	public  static  void  hello() 
		{
		System.out.println(  "Hello from main" );
		}
	}

class MyFirstClass
	{
	
	int referenceCount  =  0;

	public  void  hello()
		{
		System.out.println(  "Hello # " +  referenceCount++  );
		}
	}
Output
Hello from main
Hello # 0
Hello # 1
Hello # 2
Multiple Entry Points
class Top
	{

	public static void main( String args[] )
		{
		System.out.println(  "Start in Top" );
		Bottom  test  =  new  Bottom();
		test.hello();
		} 

	public  void  hello()
		{
		System.out.println(  "Hello from Top"  );
		}
	}

class Bottom
	{

	public static void main( String args[] )
		{
		System.out.println(  "Start in Bottom" );
		Top  test  =  new  Top();
		test.hello();
		} 

	public  void  hello()
		{
		System.out.println(  "Hello from Bottom"  );
		}
	}
Output
java Topjava Bottom
Start in TopStart in Bottom
Hello from BottomHello from Top

IO


class Output 
	{

	public static void main( String args[] ) 
		{
			// Standard out
		System.out.print(  "Prints, but no linefeed " );
		System.out.println(  "Prints, adds linefeed  at end" );

		double  test  =  4.6;
		System.out.println(  test  );

		System.out.println( "You can use " + "the plus operator on " 
							+ test  + "  String mixed with numbers" );

		System.out.println(  5  +  "\t"  +  7  );

		System.out.flush();		// flushes output buffer

		System.err.println(  "Standard error output"  );

		}
	}

Output
Prints, but no linefeed Prints, adds linefeed  at end
4.6
You can use the plus operator on 4.6  String mixed with numbers
5       7
Standard error output

To Avoid Typing "System" all the Time

import  java.io.PrintStream;

class Output 
	{

	public static void main( String args[] ) 
		{
		
		PrintStream  out  =  System.out;

		out.print(  "Look Mom, No System" );

		out.flush();

		out.println(  "Be careful with print, flush can be useful" );

		out.println(  "Everything you can do with System.out"  +  
							"You can do here" );
		}
	}

Simple Input
import sdsu.io.ASCIIInputStream;

public class TestSDSUio
	{

	public static void main(String args[]) throws Exception
		{
		ASCIIInputStream  cin = new ASCIIInputStream(System.in);
		
		System.out.print( "Type two integers: " );
		System.out.flush();

		int i1 = cin.readInt();
		int i2 = cin.readInt();
		System.out.println( "They were " + i1 + " and " + i2 );

		System.out.print( "Type two words: " );
		System.out.flush();

		String  firstWord  =  cin.readWord();
		String  secondWord  =  cin.readWord();
		System.out.println( "They were " + firstWord  + " and "  + secondWord  );

		}
	}

Some ASCIIInputStream Methods
readChar()readWord()
readLong()readLine()
readFloat()flushLine();
readDouble()

Applets


import java.awt.Graphics;

public class HelloWorld extends java.applet.Applet 
	{

	public void init() 
		{
		resize(150,25);
		}

	public void paint(Graphics g) 
		{
		g.drawString("Hello world!", 50, 25);
		}
	}

Create a directory for your HTML pages.

Place the above program in a file, "HelloWorld.java" in the HTML directory.


Compile the program

Place the following text a file named Hello.html in your HTML directory
<HTML>
<HEAD>
<TITLE> A Simple Program </TITLE>
</HEAD>
<BODY>

Here is the output of my program:
<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>

Run the appletviewer

appletviewer Hello.html

Or use netscape2.0b6 to read the file Hello.html

Important: Do NOT invoke netscape2.0b6 from the HTML directory if you might want to reload the applet. Because of the way the class loader works, an applet can't be reloaded (for example, after you make changes to its code) when you invoke the applet viewer from the directory that contains the applet's compiled code.


Applet Showing more Events

Modify the .html file to run this program
Use Appletviewer to see the history of the events
import java.awt.Graphics;

public class Simple extends java.applet.Applet
	{

	StringBuffer buffer = new StringBuffer("  " );

	public void init()
		{
		resize(500, 200);
		addItem("initializing... ");
		}

	public void start()
		{
		addItem("starting... ");
		}

	public void stop()
		{
		addItem("stopping... ");
		}

	public void destroy()
		{
		addItem("preparing for unloading...");
		}

	public void addItem(String newWord)
		{
		System.out.println(newWord);
		buffer.insert(1, newWord+ "\n");
		repaint();
		}

	public boolean mouseDown(java.awt.Event evt, int x, int y)
		{
		addItem("click!... " + x + " " + y);
		return false;
		}

	public boolean mouseUp(java.awt.Event evt, int x, int y)
		{
		addItem("Mouse Released!... " + x + " " + y);
	       return false;
		}

	public boolean mouseEnter(java.awt.Event evt, int x, int y)
		{
		addItem("Mouse enter!... " + x + " " + y);
		return false;
		}

	public boolean mouseExit(java.awt.Event evt, int x, int y)
		{
		addItem("Mouse Exit!... " + x + " " + y);
		return false;
		}

	public boolean mouseMove(java.awt.Event evt, int x, int y)
		{
		addItem("Mouse is moving!... " + x + " " + y);
		return false;
		}

	public boolean keyDown(java.awt.Event evt, int key )
		{
		addItem("Key pressed!... " + key);
		return false;
		}

	public boolean keyUp(java.awt.Event evt, int key )
		{
		addItem("Key released!... " + key);
		return false;
		}
	public void paint(Graphics g)
		{
		g.drawRect(0, 0, size().width - 1, size().height - 1);
		g.drawString(buffer.toString(), 5, 15);
		}

	} // class Simple 


Complete syntax for the APPLET tag

	'<' 'APPLET'
		['CODEBASE' '=' codebaseURL]
		'CODE' '=' appletFile
		['ALT' '=' alternateText]
		['NAME' '=' appletInstanceName]
		'WIDTH' '=' pixels 'HEIGHT' '=' pixels
		['ALIGN' '=' alignment]
		['VSPACE' '=' pixels] ['HSPACE' '=' pixels]
	'>'
	['<' 'PARAM' 'NAME' '=' appletAttribute1 'VALUE' '=' value '>']
	['<' 'PARAM' 'NAME' '=' appletAttribute2 'VALUE' '=' value '>']
	. . .
	[alternateHTML]
	'</APPLET>'

'CODEBASE' '=' codebaseURL
This optional attribute specifies the base URL of the applet -- the directory that contains the applet's code. If this attribute is not specified, then the document's URL is used.

'CODE' '=' appletFile
This required attribute gives the name of the file that contains the applet's compiled Applet subclass. This file is relative to the base URL of the applet. It cannot be absolute.

'ALT' '=' alternateText
This optional attribute specifies any text that should be displayed if the browser understands the APPLET tag but can't run Java applets.

'NAME' '=' appletInstanceName
This optional attribute specifies a name for the applet instance, which makes it possible for applets on the same page to find (and communicate with) each other.

'WIDTH' '=' pixels 'HEIGHT' '=' pixels
These required attributes give the initial width and height (in pixels) of the applet display area, not counting any windows or dialogs that the applet brings up.

'ALIGN' '=' alignment
This required attribute specifies the alignment of the applet. The possible values of this attribute are the same as those for the IMG tag: left, right, top, texttop, middle, absmiddle, baseline, bottom, absbottom.

'VSPACE' '=' pixels 'HSPACE' '=' pixels
These option attributes specify the number of pixels above and below the applet (VSPACE) and on each side of the applet (HSPACE). They're treated the same way as the IMG tag's VSPACE and HSPACE attributes.

'<' 'PARAM' 'NAME' '=' appletAttribute1 'VALUE' '=' value '>'
This tag is the only way to specify an applet-specific attribute. Applets access their attributes with the getParameter() method.

Basic Data Types

class PrimitiveTypes 
	{
	public static void main( String args[] ) 
		{
		// Integral Types
		byte   aByteVariable;		// 8-bits
		short   aShortVariable;		// 16-bits
		int   aIntVariable;		// 32-bits
		long   aLongVariable;		// 64-bits

		// Floating-Point Types
		float   aFloatVariable;		// 32-bit IEEE 754 float
		double   aDoubleVariable;		// 64-bit IEEE 754 float

		// Character Type
		char   aCharVariable;		// always 16-bit Unicode

		// Boolean Types
		boolean   aBooleanVariable;		// true or false

		}
	}



Integral and Floating-Point types make up arithmetic types
Primitive Type Ranges
typefromto
byte -256255
short -32,76832,767
int -2,147,483,6482,147,483,647
long -9,223,372,036,854,775,8089,223,372,036,854,775,807

Float Types

float values are of the form s*m*2e where
s = 1 or -1
0 <= m <= 224 and m is an integer
-149 < e < 104
1e-44 2.9e38 approximate range in decimal
double values are of the form s*m*2e where
s = 1 or -1
0 <= m <= 253 and m is an integer
-1045 < e < 1000
1e-314 1e316 approximate range in decimal

Arithmetic Literals
class ArithmeticLiterals 
	{

	public static void main( String args[] ) 
		{
		long   aLong   =  5L;
		long   anotherLong  =  12l;

		int    aHex  =  0x1;
		int    alsoHex  =  0X1aF;

		int    anOctal  =  01;
		int    anotherOctal  =  0731;

		long    aLongOctal  =  012L;
		long    aLongHex  =  0xAL;

		float    aFloat  =  5.40F;
		float    alsoAFloat  =  5.40f;
		float    anotherFloat  =  5.40e2f;
		float    yetAnotherFloat  =  5.40e+12f;

		double    aDouble  =  5.40;
		double    alsoADouble  =  5.40d;
		double    moreDouble  =  5.40D;
		double    anotherDouble  =  5.40e2;
		double    yetAnotherDouble  =  5.40e+12d;
		}
	}

Operations on Primitive Types

Integral Types
Equality = !=
Relational< <= > >=
Unary+ -
Arithmetic+ - * / %
Pre, postfix increment/decrement++ --
Shift<< >> >>>
Unary Bitwise logical negation~
Binary Bitwise logical operators& | ^
class Operations 
	{

	public static void main( String args[] ) 
		{
		int a = 2;
		int b = +4;
		int c = a + b;

		if ( b > a )
			System.out.println("b is larger");
		else 
			System.out.println("a is larger");

		System.out.println( a << 1);  	// Shift left: 4
		System.out.println( a >> 1);  	// Shift right: 1
		System.out.println( ~a );  		// bitwise negation: -3
		System.out.println( a  |  b);  	// bitwise OR: 6
		System.out.println( a  ^  b);  	// bitwise XOR: 6
		System.out.println( a  &  b);  	// bitwise AND: 0
		}
	}

Floating-Point Types
Operations
Equality = !=
Relational< <= > >=
Unary+ -
Arithmetic+ - * / %
Pre, postfix increment/decrement++ --

NaN, +infinity, -infinity

Zero divide with floating-point results in +infinity, -infinity

Overflow results in either +infinity, -infinity.

Underflow results in zero.

An operation that has no mathematically definite result produces NaN - Not a Number

NaN is not equal to any number, including another NaN
class NaN  
	{

	public static void main( String args[] ) 
		{
		float  size  =  0;
		float  average  =  10 / size;
		float  infinity  =  1.40e38f  *  1.40e38f;

		System.out.println(  average  );		// Prints Inf
		System.out.println(  infinity  );		// Prints Inf
		}
	}

Casting

class Casting  
	{

	public static void main( String args[] ) 
		{
		int anInt = 5;

		float aFloat = 5.8f;

		aFloat  =  anInt;		// Implicit casts up are ok

		anInt  =  aFloat ;		// Compile error, 
									// must explicitly cast down
		anInt  =  (int) aFloat ;

		float error = 5.8;		// Compile error, 5.8 is double

		float works = ( float) 5.8;

		char c	=  (char) aFloat;

		double aDouble = 12D;

		double bDouble  =  anInt + aDouble; 

			// anInt  is cast up to double, 
		}
	}

Ints and Booleans are Different!

class UseBoolean 
	{

	public static void main( String args[] ) 
		{
		if ( ( 5 > 4 ) == true )
			System.out.println( "Java's explicit compare " );

		if ( 5 > 4 )
			System.out.println( "Java's implicit compare " );

		if ( ( 5 > 4 ) != 0 )			// Compile error
			System.out.println( "C way does not work" ); 


		boolean cantCastFromIntToBoolean = (boolean) 0; 
					// compile error
		}
	}

Default Values of Variables


All arithmetic variables are initialize to 0

char variables are initialize to the null character: '\u000'

boolean variables are initialize to false

reference variables are initialize to null


Compiler usually complains about using variables before explicitly giving them a value
class InitializeBeforeUsing  
	{

	public static void main( String args[] )  
		{
		int noExplicitValue;

		System.out.println(  noExplicitValue  ); // complains here

		int     someValue;
		boolean tautology = true;

		if (tautology)
			{
			someValue = 5;
			}
		System.out.println( someValue );  // complains here
		}
	}

Characters
class CharactersLiterals 
	{

	public static void main( String args[] ) 
		{
		char   backspace   =	'\b';
		char   tab   =	'\t';
		char   linefeed   =	'\n';
		char   formFeed   =	'\f';
		char   carriageReturn   =	'\r';
		char   doubleQuote   =	'\"';
		char   singleQuote   =	'\'';

		char   aCharacter    =  'b';
		char   unicodeFormat   =  '\u0062';  	// 'b'
		}
	}

Unicode

Superset of ASCII

Includes:
ASCII, Latin letter with diacritics
Greek, Cyrillic
Korean Hangul
Han ( Chinese, Japanese, Korean )
Others
For more information see: The Unicode Standard Vol 1 or
URL http://www.stonehand.com/unicode.html

----------