Java Reference Quick Guide

Applets - Basic Structure of a Program Applications - Basic Structure of a Program
Arithmetic & Logic Operators Arrays
Bubble Sort Algorithm Casting
Comments in Java Comparison and Logic Operators
Conditional Execution (If statements) Console Graphics Commands (colors too)
Converting a String to a double (not possible with casting) Converting a String to an Integer
Counters and Accumulators Declaring and Initializing Variables and Constants
File Reading and Writing Fonts
Functional and Procedural Methods Inheritance of Classes
Loops Math Methods
Opening and closing console windows Output - Standard in hsa.Console
String Methods Variable Types

Applets - Basic Structure of a Program

import java.applet.Applet;
import java.awt.*;

public class appletName extends Applet

{
   public void init( )
    {
      // initializes and instantiates all the parts of the applet
     }

public boolean action (Event e, Object o)

    {
     // launches any actions resulting from events on the GUI    
      if (e.target instanceof Button)
       {
          if (e.target = = specificButton)
          {
          // carry out an action
          }
       }
     return true;    // required because this is a function-type method
    } // end of action method
}     // end of class



Applications - Basic Structure of a Program
TOP

import java.awt.*;
import hsa.Console;

public class className
{
    static Console c= new Console( );
    static public void main (String [] args)
      {
      .... main body of the application
      } // end of main method

  } // end of class


Arithmetic Operators
TOP
Operator Meaning Example
- Unary negation x = -y;
+ Addition x = 2 + 3;
- Subtraction x = 12 - y;
* Multiplication z = 5 * 27;
/ Division f = q / 5;
% Modulus n = x % 3;
+ + Increment by 1 x + + ; + + y;
- - Decrement by 1 i - -; - - q;
= Assingment x=3;
== Logical Comparator if (x ==3) or while (x==3);
! Logical Negation while (! (resp.equalsIgnoreCase("yes") ) );
!= Logical Not Equals if (x !=3)
&& Logical AND if (resp.equals("YES") == true && count ==3)
|| Logical OR if (resp.equals("YES") == true || resp.equals("yes") )
     


Arrays
TOP


Declaring an array:

The array declaration gives the array's name, the data type of the elements of the array, and the range of values to be used as its index.

e.g. int a [ ] = new int [10 ] ;

creates an array of 10 integers numbered 0 - 9.

Array values may be assigned by user input.

String list [ ] = new String [5];

for (i=0;i<=4; ++i); //generate the list
   {
     c.print ("Type in name: " + i);
     list [i] = c.readString ( );
   }

Array values may be assigned by the program itself :

String list [ ] = new String [5];
list [0] = "Mary Jones";
list [1] = "Frank Smith";
list [2] = "Richard vonFriedel";
list [3] = "Olatolu Peters";
list [4] = "Bob Fraser";

OR the values of the array may be initialized in the declaration

String list [ ] = {"Mary Jones", "Frank Smith", "Richard vonFriedl", "Olu Peters", "Bob Fraser"};

double marks [ ] = { 57.4, 33.5, 97.4, 88.3, 56,9};


Modified Bubble Sort Algorithm
TOP


// This class is designed to be inherited by another class which passes as parameters
// an array of names (strings) and the number of items in the array, then bubble sorts
// the list of names into alphabetical order. Because this algorithm is designed to be
// inherited by another class, it does not have a main method. It could easily be rewritten
// as a stand-alone class or a procedure to be called by the main method within the
// same class.

public class SortThese
   {
    static public void sortdata (String names [ ] , int number)
   {
      for (int x = 0; x < number-1; x + +)
         {
         for (int y = x+1; y < number ; y + +)
         {
            if (names [ y ] .compareTo (names [ y + 1] > 0)
            {
               String temp = names [ y];
               names [ y ] = names [x];
               names [x] = temp;
            }
         }
      }
   }
} // end of SortThese class



Casting
TOP

Converting one variable type to another
Assume for the following:
int x = 65;
double y = 33.33;
char z = 'B';
String s;

integer casted to a double

y = (double)x;

double casted to a integer (truncates all decimal values) x = (int)y;
integer cast to a char (so if x=65, the casted z would be 'A' - ASCII) z = (char)x;
char coast to an integer (if 'B', the ASCII integer value is 66) x = (int)z;
String casted to integer (assuming 1st items in String are integer!) x = Integer.parseInt(s);
String cast to a double (assuming 1st items in String are double!) y = Double.parseDouble(s);
String cast to a char (specific character selected) z = s.charAt(2);



Comments in Java
TOP


Comparison and Logic Operators
TOP

Operator Meaning Example
= = Equality if (z = = 3) y = 7;
! = Not equal to if (z ! = 3) y = 7;
< Less than if (z < 3) y = 7;
< = Less than or equal to if (z < = 3) y = 7;
> Greater than if (z > 3) y = 7;
> = Greater than or equal to if (z >= 3) y = 7;
&& And condition if (z > = 3 && y <=7)
|| Or condition if (z > = 3 | | y < = 7)


Conditional Execution (if statements)

To execute one statement resulting from a condition:

if (condition)
    statement;


To execute a block of code resulting from a condition:
if (condition)
   {
      statement1;
      statement2;
      statement3;
   }

Selection from two conditions:
if (condition)
   statement1;
else
   statement2;

Selection from more than two conditions:

if (condition1)
   statement1;
else if (condition2)
   statement2;
else if (condition3)
   statement3;
else
   statement4;

 

Switch statement:
switch (expression)
{
case value1:statement1;
   break;
case value2:statement2;
   break;
case value3: statement3;
   break;
default: statement4;
}

Using an 'if' statement to exit a repetition statement (loop):
if (x ==3)
break;


Console Graphics Commands
TOP


c.setTextColor(Color.black); // sets the color of subsequent text
// available colors include black, cyan, darkGray, gray, green, lightGray,
// magenta, orange, pink, red, white and yellow
c.setColor(Color.green); // sets the colour of subsequent drawn figures
c.drawLine (100,140,500,140); // draws a line between the two given sets of X and Y coordinates
c.drawRect (x1,y1,x2,y2); // coordinates specify the lower left and upper right corners of the rectangle
c.drawOval (Xcenter,Ycenter,xradius,yradius);  
c.drawString("String contents",locationx,locationy);  
c.drawMapleLeaf(x,y, width, height);  
c.fillRect(x,y,width,height);  
c.fillOval (Xcenter,Ycenter,xradius,yradius);  
c.drawStar(x,y,width,height);  
c.fillStar(x,y,width,height);  
c.drawArc(x,y,initialangle,finalangle,xradius,yradius)  
c.drawRoundRect(x,y,width,height,xcornerradius,ycornerradius);  
c.setFont ( new Font ("Arial",Font.BOLD,22) ); // setting font, type and size of c.drawString command

Converting a String to a Double
(outside of casting)

public static double convert (String x)
{
  double answer;
   int marker = 0;
   int countafters = 0;
   String before = "";
   String after = "";
   for (int z=0; z<=x.length ( ) ; ++z)
   {
     if (x.charAt(z) = = '.')     // determine the integers before the decimal
      {    
        marker = z;
        break;
      }
      before +=x.charAt(z);
     }
   for (int z=marker; z<=x.length ( )-1 ; ++z)
   {
         // determine the integers after the decimal
   after +=x.charAt(z);
   countafters + +;
   }
   int y,w;
   y=Integer.parseInt (before);
   w=Integer.parseInt (after);
   answer = y + (w / (Math.pow(10,countafters)));
   return answer;
   } // end of convert method
}

Converting a String to an Integer
TOP

x=Integer.parseInt (y)    // determines the integer value of a string y (if possible) and stores in the variable x.

Counters and Accumulators
Comparison Counter Accumulator
What does it do? adds/subtracts a set value/number to a variable adds/subtracts a variable amount to another variable
Example count++;

count+=3;

total + = mark;

amount - = deduction;

Why used? To increment/decrement a set value, usually within a loop To total up values, often in preparation for averages;

Declaring and Initializing Variables and Constants

int hoursWorked, golfScores, numberofCars       // declaring variables

double salary, averageMarks;

String girlsName, countryofBirth, streetAddress;

hoursWorked=39;       // initializing variables

salary = 6.85;

girlsName="Janita";

int hoursWorked = 39;       // combining declaration and intialization

String girlsName= "Janita";

final doubleTAX_PST = 0.07;       // declaring and initializing constant values - use all upper case for constant names


File Reading and Writing
TOP

Writing to a Sequential File

// This class writes all the odd integers between 1 and 36 into a file call oddint.txt

import java.awt.*;
import hsa.Console;
import java.io*;

public class OddInts
{
   static Console c;
   public static void main (String [ ] args) throws IOException

{

   String fileName, line;
   int number;
   PrintWriter output;
   fileName = "oddint.txt";
   output = new PrintWriter (new FileWriter (fileName));
   for (number = 1; number <=36; number + = 2)
      output.println (number);
   output.close ( );
   }
}


Reading from a Sequential File, One Token per Line

// This program reads in a series of marks, stored one per line in a sequential file
// called "integers.txt". Because marks are read in as strings, they must be converted
// to integers using the parseInt ( ) function. If the input is to be in the form of a string
// anyway, no conversion of the data is necessary.

import java.awt.*;
import has.Console;
import java.io.*;

// The "FileAvg" class

public class FileAvg
{
   static Console c;
   public static void main (String [ ] args) throws IOException
   {
   c= new Console ( );
   String fileName, line;
   int number;
   int sum = 0; count = 0;
   fileName = "integers.txt";
   BufferedReader input;
   input = new BufferedReader (new FileReader (fileName));
   line = input.readLine ( ) ; // Read a line of characters
   while (line ! = null) // File is terminated by a null
   {
      number = Integer.parseInt (line);    // Change to an integer
      count + + ;
      sum + = number;
      line = input.readLine ( ) ;    // Read next line
   }
   c.println ("Average of " + count + "numbers is " + (double) (sum/count));
   }    // main method
} // FileAvg class


Reading from a Sequential File, Multiple Tokens per Line

// This program demonstrates the reading of a file, one line at a time.
// Each line contains several columns of data. The routine "String Tokenizer"
// takes the line and divides it into individual tokens which are then stored
// in a 2 dimensional array.

import java.io.*;
import java.util.*;
import hsa.Console;

public class Read2D
{
   static Console c;
   public static void main (String [ ] args) throws IOException
   {
   c=new Console ( );
   BufferedReader script;
   String data [ ] [ ] = new String [ 6 ] [ 6 ] ;
   script = new BufferedReader ( new FileREader ("script.txt"));
   String word;
   int x,y,q,r;
   x=0;
   y=0;
   while (true)
   {
      x + +;
      String line = script.readLine ( );    // reads lines until no more lines are found
      if (line = = null)
      break;
      StringTokenizer words = new StringTokenizer (line);
      y = 0;
      while (words.hasMoreTokens ( ))    // examine each line and break up into individual tokens
      {
      y + +;
      word = words.nextToken ( );
      data [x] [y] = word;
      }
   }
   script.close ( );    // close the file
   for (q = 1; q<=3; ++q) // display the 2D array in a table
   {
   for (r=1; r<=4; + + r)
      c.print (data [q] [r], 15) ;
      c.println ("");
      }
   }    // main method
}    // Read2D class


Functions and Procedures
TOP

Here is an example of a class which contains a function-type method, followed by some explanation:
static public void main (String [] args)
{
c=new Console ( );
for (value = 1; value < = 10; value + +)
{
   c.println ("Square of " + value + "=" + square (value));
}
}    // end of main method

static public int square (int number)     // signature of the method
{
return number * number;
}    // end of square method

            return number*method

            c.println ("Square of" + value + "=" + square (value));

Here is an example of a procedure-type method

// This class takes a person's first, middle and last names, and outputs them last name first,
// followed by their two initials.

static public void main (String [ ] args)
{
String first, middle, last;
first = "Bucephalus";
middle = "John";
last = "Finkbeiner";
full (first, middle, last);     // call to the procedure
}

public static void full (String f, String m, String l)    // signature of the procedure type method
{
     c.print ( l );
    c.print (f.charAt(0));
    c.println(m.charAt(0));
}

Inheritance of Classes

// This program demonstrates the use of a function stored in one program
// (Convert) but called into another program (Inherit). The inherit program
// takes a string (named number) and calls upon the convert class to convert
// the number to a double, outputting the answer divided by 2. (See the note - Converting
// a String to an Integer for a copy of the convert program.)

import java.awt.*;
import hsa.Console;
public class Inherit
{
    static Console c = new Console ( );
    static Convert q = new Convert ( );
    public static void main (String [ ] args)
    {
    String numbers = "16.1416" ;
    c.println (q.convert (number) /2 );
   } //     main method
}


Loops
TOP


Counted (for) loops
for (initialize; condition; increment)
{
   ... statement1 ;   ... // braces are optional if there is only one statement
   ... statement2 ;    ... // in the loop
   ... statement3;
}


e.g.
for (int x=0; x < 10;++x)
{
   c.print (Math.pow(x,2),10);
   c.println(Math.pow(x,3),10);
}

Conditional loops

The while loop puts the condition at the top of the loop

while (condition) {    statement1;    statement2; }

e.g while (( d=(Math.random( ) * 100 ) ) < 75 | | d > 80)
{
   n + + ;
}
c.println ("It took" + n + "tries.");

while (true)
{
   c.print ("Do you want to continue? ( Y/N)");
   response = c.readChar( );
   if (response = 'Y' | | response = 'N' | | response = 'y' | | response = 'n')
   break;
else
c.print ("Invalid Entry, Try Again!");
}

Do loop puts the test at the bottom of the loop.
do
{
   statement1;
   statement2;
   statement3;
}
while (condition);

e.g.
do
{
   c.print( year, 10);
   c.println (depth, 18,1);
   year + + ;
   depth = depth - .01 * depth);
}
while (depth > 9);


Math Methods
TOP
Math.round (x);  
Math.sin(x);  
Math.tan(x);  
Math.sqrt(x); // square root
(Math.random ( ) * x ) // random real number between 0 and 10 - use with round function to produce a random integer
Math.min (x,y) // smaller of two numbers
Math.max(x,y) // larger of two numbers
Math.PI // constant Pi
Math.abs (x - y) // absolute value
Math.ceil (x) // rounds to next higher integer
Math.floor (x) // rounds to next lower integer
Math.pow (x,y) // x to the power of y

Opening and Closing Console Windows

To close the current console window:

c.close( );

To open a new console window:

c = new Console ( );


Output - Standard in hsa.Console

Remember: Number will align to the left of a field (like your calculator), and Strings to the right of a field (like a book). A field is the space that one identifier will occupy.

c.println ("Hello there");    // outputs a string followed by a carriage return

c.print ("Hello");    // outputs a string with no carriage return

c.println ("Hello" + "there")    // concatenates two strings together

c.println (15);    // outputs the numerical value argument

c.println (15 * 3);    // outputs the result of a calculation

c.println (15*3,5);    // outputs the result of the calculation right justified in a field of 5 spaces.

c.println (15*3,5,2);    // second field descriptive argument forces the number of decimal places output

PI=3.1416;

c.println(PI); // output the value of a constant (or variable)


String Methods
x = (s0.concat (s1));  
x=(s0.toUpperCase( ));  
x=(s0.toLowerCase( ));  
x=(s0.equals (s1)); returns true or false to compare 2 strings ( = = comparison operator doesn't work for strings)
x=(s0.equalsIgnoreCase(s1));  
x=s0.indexOf(s1); searches for the subString s1 in the string s0 and returns the integer value of the position of the substring
x=s0.charAt(y); returns the yth character in the string s0
x=s0.length( );  
x=s0.replace ('a','o'); replace all occurences of the letter a by the letter o in the string s0
x= (int) 'A'; cast a char as an integer - returns the corresponding ASCII value of the char
x= (char) y; returns the actual character corresponding with the ASCII value y.

Variable Types

int integer numbers (without decimals) - 4 bytes of memory
byte small integers - 1 byte of memory
short integers smaller in size than int - 2 bytes of memory
long integers larger in size than int - 8 bytes of memory
float real numbers - 8 bits
double real numbers - 16 bits
char strings - single character - doesn't require a carriage return when entering
String holds a series of characters


Graphical Fonts

c.setFont(new Font ("Arial",Font.BOLD,22));
// use any font already loaded in your computer, BOLD/ITALIC, 22=size in traditional non-web perspective

c.drawString ("Blah Blah Blah",200,100);
// 200 is bottom left x coordinate, 100 is bottom left right coordinate