SDSU CS 596 Java Programming
Fall Semester, 1998
Basic Java Syntax
To Lecture Notes Index
© 1998, All Rights Reserved, SDSU & Roger Whitney
San Diego State University -- This page last updated 31-Aug-98

Contents of Doc 2, Basic Java Syntax


Reference


The Java Programming Language, 2 ed., Arnold & Gosling, Chapter 5

The Java Language Specification, Gosling, Joy, Steele, Chapter 4




Doc 2, Basic Java Syntax Slide # 2

Some Basic Java 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;            // This is legal in Java
      char c;
      c =
         'a';
   }
}

Doc 2, Basic Java Syntax Slide # 3
Style - Layout

The following are three different indentation styles which will be used in these notes

Pick a reasonable indentation style and use it consistently in your assignments!

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" ) ;
      }
   }

Doc 2, Basic Java Syntax Slide # 4
Style - Names

Sun API Classes use the following style:


Class names

ClassNames


Variable and function names

variableAndFunctionNames


Names of constants

NAMES_OF_CONSTANTS


Avoid abbreviations in names!!!

All Java programs should use these conventions - including your assignments

Doc 2, Basic Java Syntax Slide # 5
Keywords

abstract
default
implements
protected
throws
boolean
do
import
public
transient
break
double
instanceof
return
try
byte
else
int
short
void
case
extends
interface
static
volatile
catch
final
long
super
while
char
finally
native
switch

class
float
new
synchronized

const
for
package
this

continue
if
private
throw



Reserved for possible future use (not used now)

byvalue
cast
future
generic
goto
inner
operator
outer
rest
var
Boolean

true, false act like keywords but are boolean constants



Doc 2, Basic Java Syntax Slide # 6

IO

Standard Java Output

System.out is standard out in Java
System.err is error out in Java

class Output 
   {
   public static void main( String args[] ) 
      {
         // Standard out
      System.out.print(  "Prints, but no newline" );
      System.out.println(  "Prints, adds platforms newline 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.println(  "trouble"  +  5  +  7  );   //Problem here
      System.out.println(  "ok"  +  (5  +  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
trouble57
ok12
Standard error output

Doc 2, Basic Java Syntax Slide # 7
Simple IO

Java assumes that you will be using a GUI for input from the user

Hence there is no "simple" way to read input from a user

The Console class in the SDSU Java library provides simple input

More on this when we cover Java IO

The following example uses the SDSU Java Library

Your CLASSPATH ( http://www.eli.sdsu.edu/courses/fall98/cs596/notes/intro/intro.html#Heading13) must include the SDSU library for the next example to work

The import statement is an include statement, it just tells the compiler to use the short name of the class sdsu.io.Console

More on that when we cover packages

See http://www.eli.sdsu.edu/java-SDSU/index.html for more information about SDSU Java library and sdsu.io.Console


Doc 2, Basic Java Syntax Slide # 8
Simple IO - The Example

import sdsu.io.Console;
public class Test_SDSU_Console
   {
   public static void main( String[] args )
      {      
      // Simple printing
      Console.println( 5 );
      Console.print( "Hi Mom" );
      Console.println( " Hi Dad" );
      
      Console.print( "Print an integer ");
      int why = Console.readInt();
      Console.flushLine();            // flushes newline from input
      Console.println( "You typed: " + why );
      
      int easy = Console.readInt( "Print another integer" );
      Console.flushLine();
      Console.print( "You typed: %20i\n ", easy );
      String message = Console.readLine( "Type a line of text" );
      Console.flushLine();
      Console.println( ":" + message + ":");
      
      }
   }
Output
5
Hi Mom Hi Dad
Print an integer 12
You typed: 12
Print another integer 34
You typed:                   34
 Type a line of text Hi Mom
:Hi Mom:


Doc 2, Basic Java Syntax Slide # 9

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

Doc 2, Basic Java Syntax Slide # 10

Primitive Type Ranges


typeMinMax
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 values are of the form s*m*2^e
s = 1 or -1
0 ≤ m ≤ 2^24 and m is an integer
-149 < e < 104
1e^-44 to 3.4e^38 approximate range in decimal

7 significant decimal digits
double values are of the form s*m*2^e where

s = 1 or -1
0 ≤ m ≤ 253 and m is an integer
-1045 < e < 1000
1e^-314 to 1.8e^308 approximate range in decimal
15 significant decimal digits


Doc 2, Basic Java Syntax Slide # 11
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;
      float    compileError = 5.40;         //Need cast here
      double    aDouble  =  5.40;         //Double is default!!
      double    alsoADouble  =  5.40d;
      double    moreDouble  =  5.40D;
      double    anotherDouble  =  5.40e2;
      double    yetAnotherDouble  =  5.40e+12d;
      }
   }


Doc 2, Basic Java Syntax Slide # 12

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

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


NaN, +∞, -∞

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 Infinity
      System.out.println(  infinity  );      // Prints Infinity
      }
   }

Doc 2, Basic Java Syntax Slide # 14

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, Basic Java Syntax Slide # 15

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, 
      int  noWay  =  5 /  0;      // Compile error, compiler detects
                           // zero divide
      int  zero  =  0;
      int  trouble  =  5 / zero;   //Some compilers may give error here
      int  notZeroYet;
      notZeroYet  =  0;
      trouble  =  5 / notZeroYet  ;   // No compile error!
      }
   }

Doc 2, Basic Java Syntax Slide # 16
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, Basic Java Syntax Slide # 17

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, Basic Java Syntax Slide # 18
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



Copyright © 1998 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA.
All rights reserved.

visitors since 31-Aug-98