SDSU CS 535: Object-Oriented Programming & Design
Fall Semester, 1997
Doc 2, Java Basics

To Lecture Notes Index
San Diego State University -- This page last updated 03-Sep-97

Contents of Doc 2, Java Basics


Reference
Basics slide # 1
...First Program slide # 3
...Syntax slide # 9
...IO slide # 14
...Basic Data Types slide # 17
......Primitive Type Ranges slide # 18
......NaN, +infinity, -infinity slide # 23
......Ints and Booleans are Different! slide # 26
......Characters slide # 28

Reference


The Java Programming Language, Arnold, Gosling, Chapter 5

The Java Language Specification, Gosling, Joy, Steele


Doc 2, Java Basics Slide # 1

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 is strongly typed
Doc 2, Java Basics Slide # 2
Java Resources

Newsgroups

comp.lang.java.XXX
     sdsu.java
Web Sites (few among hundreds)
Yahoo
http://www.yahoo.com/Computers_and_Internet /Programming_Languages/Java/
Gamelan - hundreds of examples
http://www.gamelan.com/
Source of Java - Sun
http://java.sun.com/
Local Java Docs
http://www.sdsu.edu/doc/


Doc 2, Java Basics Slide # 3

First Program


class HelloWorldExample 
{
     public static void main( String args[] )
     {
          System.out.println("Hello World");
     }
}

Setting Path etc. for Java on Rohan

Add to your path:

/opt/java/bin

Add CLASSPATH to your environment

setenv CLASSPATH '.:/opt/local/lib/java/classes.zip'


Doc 2, Java Basics Slide # 4
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 HelloWorldExample.class

rohan 37-> java HelloWorldExample
Hello World


Doc 2, Java Basics Slide # 5
Fancy Compiling

class HelloWorldExample 
{
     public static void main( String args[] ) 
     {
          System.out.println("Hello World");
     }
}


Put the above program in a file named:

HelloWorldExample.java

Now compile and run the program using the command:

rohan 42-> java -cs HelloWorldExample

The -cs (or -checksource) option recompiles all needed files and runs the program

A file is recompiled if it has not been compiled yet
or the binary file is older than the source file


Doc 2, Java Basics Slide # 6
Real Fancy Compiling

Create a directory to hold your java source code

For this example the directory will be

"/home/ma/whitney/java/classes"

Add the directory to your classpath

setenv CLASSPATH '.:/opt/local/lib/java/classes.zip:/home/ma/whitney/java/classes'

Note the above must not contain any newlines

Place the file HelloWorldExample.java in or in any subdirectory of "~whitney/java/classes"

From any location you can compile and run the program using:


rohan 42-> java -cs HelloWorldExample


Doc 2, Java Basics Slide # 7
Warnings

One class per file supports:

Decomposability
Composability
Understandability

Without correct tools this becomes difficult


Doc 2, Java Basics Slide # 8

Application of KISS

First program in any language should be the smallest possible

Incremental compiling while developing:

Compile at least once every 5 minutes

Doc 2, Java Basics Slide # 9

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

Doc 2, Java Basics Slide # 10
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" ) ;
     }
}

Doc 2, Java Basics Slide # 11
Style - Layout Continued


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

          int aVariable = 5;

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

          }
     }


Doc 2, Java Basics Slide # 12
Style - Names

Sun API Classes use the following style:


Names of classes

ClassNames

Names of variables and functions

variableAndFunctionNames

Names of constants

NAMES_OF_CONSTANTS

All Java programs should use these conventions


Doc 2, Java Basics Slide # 13
Style and Understandability

Consistant
use of a progamming style is important for understandability



What to do if your team has adopted "bad" style?


Doc 2, Java Basics Slide # 14

IO

Standard Java Output

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

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

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

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


          System.out.println(  "trouble"  +  5  +  7  );     // trouble57
          System.out.println(  "OK"  +  (5  +  7)  );     // OK12


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

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


Doc 2, Java Basics Slide # 15
Really Simple IO

import sdsu.io.Console;

public class Test_SDSU_Console
     {
     public static void main( String[] args )
          {
          Console.println( 5 );
          Console.print( "Hi Mom" );
          Console.println( " Hi Dad" );


          Console.print( "Print an integer ");
          int why = Console.readInt();
          Console.println( "You typed: " + why );


          int theEasyWay = 
               Console.readInt( "Print another integer" );


          Console.print( "You typed: %20i\n ", easy );


          String message = 
                    Console.readLine( "Type a line of text" );
          Console.println( "");


          double x = 1.23456789012;
          Console.print( "x = %f\n", x);
          Console.print( "x = % .5f\n", x);
          Console.print( "x = %10.8f\n", x);
     }
}

Doc 2, Java Basics Slide # 16
On-Line Documentation

Index to local documentation for Java and other systems

http://www.sdsu.edu/doc/


SDSU Java Class library documentation

http://www.eli.sdsu.edu/java-SDSU/index.html

Use of the on-line Java docs can not be avoided

Learn to use it now


Doc 2, Java Basics Slide # 17

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

          char   aCharVariable;          // always 16-bit Unicode

          boolean   aBooleanVariable;          // true or false
          }
     }

Doc 2, Java Basics Slide # 18

Primitive Type Ranges


typefromto
byte -128127
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
1e-44 3.4e38 approximate range in decimal

7 significant decimal digits

Double

1e-314 1.8e308 approximate range in decimal

15 significant decimal digits
Doc 2, Java Basics Slide # 19
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; //what value is this? long aLongOctal = 012L; long aLongHex = 0xAL; float aFloat = 5.40F; float aFloatAlso = 5.40f; float anotherFloat = 5.40e2f; float yetAnotherFloat = 5.40e+12f; double aDouble = 5.40; double alsoADouble = 5.40d; double aDoubleAlso = 5.40D; double anotherDouble = 5.40e2; double yetAnotherDouble = 5.40e+12d; } }
Doc 2, Java Basics Slide # 20
Operations on Primitive Types
Integral Types

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


Doc 2, Java Basics Slide # 21
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
          }
     }

Doc 2, Java Basics Slide # 22
Floating-Point Types
Operations
Equality = !=
Relational< <= > >=
Unary+ -
Arithmetic+ - * / %
Pre, postfix increment/decrement++ --

Doc 2, Java Basics Slide # 23

NaN, +infinity, -infinity


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

Overflow results in either +ƒ, -ƒ.

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

          System.out.println(  infinity * 0 );          // Prints NaN
          }
     }

Doc 2, Java Basics Slide # 24
NaN and Infinity

class Compare  
     {

     public static void main( String args[] ) 
          {
          float  nan  =  Float.NaN;
          float  positiveInfinity  =  Float.POSITIVE_INFINITY;
          float  negativeInfinity  =  Float.NEGATIVE_INFINITY;

          // The following statements print false

          System.out.println(  nan == nan  );
          System.out.println(  nan < nan  );
          System.out.println(  nan > nan  );
          System.out.println(  positiveInfinity  <  positiveInfinity 
);

          // The following statements print true

          System.out.println(  positiveInfinity  == positiveInfinity  );
          System.out.println(  5.2 < positiveInfinity  );
          System.out.println(  5.2 > negativeInfinity  );
          }
     }

Doc 2, Java Basics Slide # 25
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; 

          int  noWay  =  5 /  0;     // Compile error,

          int  zero  =  0;
          int  trouble  =  5 / zero;     // Metroworks Compiler error
                                             // No error on Sun compiler

          int  notZeroYet;
          notZeroYet  =  0;
          trouble  =  5 / notZeroYet  ;     // No compile error!
          }
     }

Doc 2, Java Basics Slide # 26

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

          int  x  =  10;
          int  y  =  5;

          if  ( x = y )                          // Compile error
               System.out.println( "This does not work in Java " );
          }
     }



Doc 2, Java Basics Slide # 27
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  ); // Compile error

          int  someValue;
          boolean tautology = true;

          if ( tautology )
               {
               someValue = 5;
               }
          System.out.println( someValue );  // Compile error
          }
     }



Doc 2, Java Basics Slide # 28

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
http://www.stonehand.com/unicode.html


visitors since 03-Sep-97