Introduction to Java


NOTE: It is advised that you try each example on your own to get practice using the Java language.

Object-Oriented Programming Principles

An Object is a collection of data and an associated set of methods that act on that data. Objects consist of an internal state (which is the data) and behavior (the methods).

A Class is a template that objects are created from. Any object is an instance of some class. Creating a new object is called instantiation. Note that a class declaration does not allocate memory, instantiation does.

Encapsulation - Associating data with the code that manipulates it. Provides data protection.

Polymorphism - Providing multiple implementations of one interface. Similar objects have similar methods.

Inheritance - defining a class as a specialization of another class. The specialized class receives all the data and methods possessed by its superclass, and can define new variables and methods of its own.

Back to top


Basic Programming

Like C, execution of the program begins at the main() method. This method must be defined within a class.
	class MyClass{
	  public static void main(String args[]){
		.
		.        // Body of main
		.
	  }
	}

The name of the source file must be classname.java (i.e., the source file for the code above would be MyClass.java).

Compiling: javac [options] filename (the filename includes the .java extension)
Execution: java classname [command-line arguments]

Back to top


Syntax

The syntax for Java is very similar to C. The control statements are the same (if, else, switch, for, while, do...while, etc.). Other similarities include: the same block structure with beginning and ending brackets, the same semi-colon line termination, and the same arithmetic operators.

Java does not use pointers, so the address operator (&) and the dereferencing operator (*) are not used. The same goes for the arrow operator (->). In additon C's common functions (printf, malloc, etc.) are completely different in Java.

A useful method to print a character string to standard output is System.out.println("..."). The argument within parentheses can be a quotation- mark enclosed string, a variable, or a combination of the two. Backslash codes can be used as in C (i.e., '\n', '\t', etc.). A newline is automatically appended when println() executes. To avoid printing the newline, use System.out.print("...") instead. Take a look at the following code.


	class output{
	    public static void main(String args[]){
        	int i = 5;
	        double j = 10.0; 
        	String hello = "Hello", world = "world";
	        char h='h', e = 'e', l='l', o='o';

	        System.out.println("Hello, world!");
        	System.out.println("My interger is " + i + ".");
	        System.out.println("My double is " + j/i + ".");
        	System.out.println("My chars are " + h + e + l + l + o);
	        System.out.println("My string is " + hello + ", "+ world + "!");
    	    }
	}

If we run it, the output is as follows:
	UNIX>javac output.java
	UNIX>java output
	Hello, world!
	My interger is 5.
	My double is 2.0.
	My chars are hello
	My string is Hello, world!
	UNIX>

Back to top


Primitive Types

Java uses eight primitive types.
Type Range Size Default
byte -128 to 127 8 bits 0
short -32768 to 32767 16 bits 0
int -2147483648 to 2147483647 32 bits 0
long -9223372036854775808 to 9223372036854775807 64 bits 0
float -1.4 x 10-45 to 3.4028235 x 1038 32 bits 0.0
double -4.9 x 10-324 to 1.7976931348623157 x 10308 64 bits 0.0
char Unicode character 16 bits '\0000
boolean true/false 1 bit false

Declaration and assignment of primitive types is the same as in C.

	int i;
	.
	.
	i = 10;
  
	int x = 0;
	char ch = 'A';

Unlike C, a variable can be declared at any point in the code. The point of declaration can place constraints on the scope of the variable. When a variable is declared, it is only usuable within that block of code. After the code passes that ending bracket, that variable is no longer accessible. The variable name can be declared again later in the program.

	for(int i = 0; i < 100; i++)
	{
	  .          // the variable i is only usable
	  .          // within this loop
	  .
	}

Direct float assignments require an 'F' or 'f' suffix.

	float price = 14.95f;

Direct long assignemnts require an 'L' or 'l' suffix.

	long atoms = 74120896650423L;

Widening conversions do not require an explicit type cast. That is, if the variable on the right is smaller in size (bit-wise) than the one on the left, e.g. assigning a byte to a short, short to an int, float to a double, etc. Narrowing conversions do require an explicit cast, even if the value being assigned is easily held by both variables (e.g. assigning a float to an int).

Back to top


Type Cast

Getting a String out of an ArrayList
	String stringName = (String)arrayName.get(n);

Getting a double out of an ArrayList (Stored in the ArrayList as a Double)

	double doubName = ((Double)arrayListName.get(n)).doubleValue();

String to Double to double (using Double constructor)

	double doubName = new Double(stringName).doubleValue;

String to Double to double

	double doubName = Double.valueOf(stringName).doubleValue;

String to double

	double doubName = Double.parseDouble(stringName);

double to a new String (using the String constructor)

	String stringName = new String(doubleName);

double to existing String

	stringName = String.valueOf(doubleName);

double to int

	double doubleOne = 10;
	double doubleTwo = 10.1;
	int intOne = (int)doubleOne;  // intOne becomes == 10
	int intTwo = (int)doubleTwo;  // intTwo becomes == 10

String to char

	char charName = stringName.charAt(2); //must specify offset in string to get char from

Back to top


Memory Allocation

Anything that is not a primitive type requires declaration and instantiation. This includes arrays of primitive types and all other objects. Memory for an object is allocated with the new operator. The new operator is similar to C's malloc() function. It allocates memory for the object, executes the object's constructor (more on constructors later), and initializes the object variables as necessary.

Declaration:


Object_name variable_name; FileWriter outfile;
Instantiation:


variable_name = new Object_name(parameters); outfile = new FileWriter();
Both at Once:
Object_name variable_name = new Object_name(parameters);   FileWriter outfile = new FileWriter();

Note - when an object is instantiated, it may require initial parameters to create the object. These parameters are passed within the parentheses following the object name.

Garbage Collection - Unlike C, Java does not have a free() function. This is because Java automatically reclaims memory when it is no longer in use. An object is not in use when no reference to it is held in any variable, array, or object field. This drastically reduces memory leaks at a minor cost in performance.

Back to top


Arrays

Java allows arrays of objects and arrays of primitive types. Arrays must be declared and instantiated like other objects. As in C, array indexing begins at zero.

         Object_type array_name[] = new Object_type[num_of_elements];

	int scorearray = new int[10];
Arrays can also be declared instantiated, and initialized with the following shorthand:

         Object_type array_name[] = {item1, item2, ..., itemN};

Values within an array are accessed the same as in C. The number of elements in an array can be accessed by the length variable as in the statement, array_name.length;
This is useful for a number of things, the most obvious is iterating through all array elements within a 'for' loop. The following code and its output demonstrates some of the simpler features of arrays.

        class ArrayDemo{
          public static void main(String args[]){
            int coinsOne[] = {1, 5, 10, 25};
            int coinsTwo[] = new int[4];
            coinsTwo[0] = 1;
            coinsTwo[1] = 5;
            coinsTwo[2] = 10;
            coinsTwo[3] = 25;

            int totalOne = 0,  totalTwo = 0;

            for(int i = 0; i < coinsOne.length; i++)
              totalTwo += coinsOne[i];

            for(int i = 0; i < coinsTwo.length; i++)
              totalOne += coinsTwo[i];

            System.out.println("The coins array one is worth " + totalOne +
                               " cents and " + totalTwo + " cents respectively.");
          }
        }
UNIX>java ArrayDemo
The coins array one is worth 41 cents and 41 cents respectively.
UNIX>
Multidimensional arrays are implemented as arrays of arrays. This means that each subarray on a given level is not required to be the same size as the others. As with one-dimensional arrays, multidimensional arrays require declaration and instantiation. Consider the following code that uses a two-dimensional array.
  class TwoDArrayDemo{
    public static void main(String args[]){
      int uneven[][] = {
        {21, 42, 5},             //Declare, allocate
        {-1, 88, 92, 16, 2},     //and initialize.
        {0, 12},                 //Could have used new and filled
        {4}                      //in the array contents.
      };
      for(int i = 0; i < uneven.length; i++){
        System.out.println("Array index " + i + " has " + uneven[i].length + " elements");

        for(int j = 0; j < uneven[i].length; j++)
          System.out.print(uneven[i][j] + " ");

	System.out.println();
      }
    }
  }
UNIX>java TwoDArrayDemo
Array index 0 has 3 elements
21 42 5
Array index 1 has 5 elements
-1 88 92 16 2
Array index 2 has 2 elements
0 12
Array index 3 has 1 elements
4
UNIX>
Back to top

Command-Line Arguments

The main() method of a java program takes one argument that is an array of String objects. This array holds any objects that may have been entered on the command line. Where C uses int argc to represent the number of command-line arguments, Java uses args.length. The individual strings are accessed as with any other array (args[0], args[1], etc).

	class CommandLineDemo{
	  public static void main(String args[]){
	    System.out.println("Command line has " + args.length + " arguments");
	    for(int i = 0; i < args.length; i++){
	      System.out.println("args[" + i + "] : " + args[i]);
	    }
	  }
	}
Notice in the output of the program that indexing of the command line arguments begins with the argument immediately after the class name. This differs from C where indexing (argv[0]) begins with the name of the program.
UNIX>java CommandLineDemo abcde 1 5 output.txt
Command line has 4 arguments
args[0] : abcde
args[1] : 1
args[2] : 5
args[3] : output.txt
UNIX>
Note - all command-line arguments are stored as Strings. Integer and floating point types require conversion from string to their relevant type before any calculations can be performed.
Back to top

Exception Handling

The term exception is shorthand for the phrase "exceptional event." It can be defined as follows:
Definition: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

Many kinds of errors can cause exceptions--problems ranging from serious hardware errors, such as a hard disk crash, to simple programming errors, such as trying to access an out-of-bounds array element. When such an error occurs within a Java method, the method creates an exception object and hands it off to the runtime system. The exception object contains information about the exception, including its type and the state of the program when the error occurred. The runtime system is then responsible for finding some code to handle the error. In Java terminology, creating an exception object and handing it to the runtime system is called throwing an exception.

After a method throws an exception, the runtime system leaps into action to find someone to handle the exception. The set of possible "someones" to handle the exception is the set of methods in the call stack of the method where the error occurred. The runtime system searches backwards through the call stack, beginning with the method in which the error occurred, until it finds a method that contains an appropriate exception handler. An exception handler is considered appropriate if the type of the exception thrown is the same as the type of exception handled by the handler. Thus the exception bubbles up through the call stack until an appropriate handler is found and one of the calling methods handles the exception. The exception handler chosen is said to catch the exception.

If the runtime system exhaustively searches all of the methods on the call stack without finding an appropriate exception handler, the runtime system (and consequently the Java program) terminates.

By using exceptions to manage errors, Java programs have the following advantages over traditional error management techniques:

  • Advantage 1: Separating Error Handling Code from "Regular" Code
  • Advantage 2: Propagating Errors Up the Call Stack
  • Advantage 3: Grouping Error Types and Error Differentiation

  • To read more about these advantages
    click here.

    This is the general form of an exception-handling block:

    	try{
    		// block of code to monitor for errors
    	}catch(ExceptionType1 exObj){
    		//exception handler for ExceptionType1
    	}catch(ExceptionType2 exObj){
    		//exception handler for ExceptionType2
    	}
    	//...
    
    
    Exception Types
    All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the exception class hiearchy. Immediately below Throwable are two subclasses that partition exceptions into two distinct branches. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. This is also the class that you will subclass to create your own custom exception types. There is an important subclass of Exception, called RuntimeException. Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing.

    The other branch is topped by Error, which defines exceptions that are not expected to be caught under normal circumstances by your program. Exceptions of tye Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error.

    The following examples uses try / catch block to catch the ArithmeticException.

    
    public class exceptions1{
        public static void main(String args[]){
            int d, a;
    
            try{
                d = 0;
                a = 42/d;
                System.out.println("this line will not be printed.");
    
            }catch(ArithmeticException e){
                System.out.println("Can't divide by zero");
    
                d = 10;
                a = 42/d;
            }
            System.out.println("After catch statement");
            System.out.println("d is being reset and a is " + a);
        }
    
    }
    
    
    
    This program generates the following output:
    Unix> java exceptions1                               
    Can't divide by zero
    After catch statement
    d is being reset and a is 4
    Unix>
    
    The following example traps two different exceptions types:
    public class exception2{
        public static void main(String args[]){
    
            try{
                int a = args.length;
                System.out.println("a = " + a);
                int b = 42/a;
                int c[] = {1};
                c[42] = 99;
    
            }catch(ArithmeticException e){
                System.out.println("Divide by zero: " + e);
            }catch(ArrayIndexOutOfBoundsException e){
                System.out.println("Array index oob: " + e);
            }
            System.out.println("After try/catch statement");
    
        }
    
    }
    
    
    
    This program generate the following output:
    Unix> java exception2                                
    a = 0
    Divide by zero: java.lang.ArithmeticException: / by zero
    After try/catch statement
    
    UNIX> java exception2 tuy                            
    a = 1
    Array index oob: java.lang.ArrayIndexOutOfBoundsException: 42
    After try/catch statement
    
    


    Back to top


    Exercises:

    When is this lab due?

    This lab is due at the end of your lab section at midnight, Jan. 26 by email to yli@cs.utk.edu

    Grading Guidelines for Lab 1

    1. CurrencyConverter Total points: 50 points
    2. ComplexNumberConverter Total points: 50 points
    3. command line argument checking (number of arguments, correct format, etc.): -5/each exercise
    4. Incorrect output: -20/each exercise
    5. Format output to be only 2 decimal places: -5/each exercise



    Assumptions for both exercises:


    Programming problems to be submitted:

    1. Write a program that accepts the U.S. currency from command line and prints out a conversion of that currency to four other countries' currencies. They are Yuan, Pound, Francs and Yen respectively. The rates are 1 pound = 1.778 U.S dollar = 14.757 Yuan = 2.115 Franc = 183.469 Yen.
      The output would look something like this:
        UNIX> java CurrencyConverter 1
              1.00 U.S dollar: 
                  8.30 Yuan
                  0.56 Pound
                  1.19 Francs
                  103.19 Yen
      

      The class name should be 'CurrencyConverter'.

      To compile and run:
        UNIX> javac CurrencyConverter.java
        UNIX> java CurrencyConverter 12    (or whatever number you want to convert)
      


    2. Conversion : Polar and Rectangular Both polar and rectangular form are commonly used to represent complex numbers. The prevalence of the polar form for sinusoidal representation makes it necessary to convert quickly and accurately between the two representations.

      polar representation needs (r,theta)
      rectangular representation needs (x,y)

      the conversion from polar to rectangular

      x = r cos(theta)
      y = r sin(theta)
      theta -> greek unit
      
      the conversion from rectangular to polar
      r = sqrt( x^2+ y^2 )
      theta = arctan( y/x)
      
      N.B. the sign of theta depends on the quadrant it is located in. This program takes in 3 arguments from cmdline. They are 2 numbers for conversion and type of these 2 numbers. For example 3 4 polar means 3 and 4 are two polar numbers, your program should convert these 2 polar numbers into 2 rectangular numbers.
    3. The class name should be ComplexNumberConverter. The command line should be something like:

      
      UNIX>java ComplexNumberConverter 3 4 rectangular
      Given x = 3.00, y = 4.00
               The rectangular representation is [r = 5.00, theta = 53.13]
      UNIX>java ComplexNumberConverter 5 30 polar Given r = 5.00, theta = 30.0 The rectangular representation is [x = 4.33, y = 2.50]

      To compile and run:
        UNIX> javac ComplexNumberConverter.java
        UNIX> java ComplexNumberConverter 1 1 rectangular
      


    Hints...

    1. For this lab you will need to know how to convert a String to an integer. Each data type has methods that can convert a String to itself or itself to a String. Take for example the following code:
      
        String mystring = "90";
        int myint = Integer.decode(mystring).intValue();
        myint++;
        mystring = Integer.toString(myint);
      
      

      Or another way:
      
        String mystring = "90";
        int myint = Integer.parseInt(mystring);
        myint++;
        mystring = Integer.toString(myint);
      
      
      This code assigns the string "90" to mystring, converts it to an integer and assigns that integer to myint. myint is incremented, then converted to a string and mystring is assigned the string value.

      Please note: For more explanation regarding doubles, floats, longs, etc., please refer to the Sun documentation. By the way, bookmark the Sun site on your browser. It will become your new best friend!!!!!

    2. For text formatting refer to: http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html
      Here is an example:
        DecimalFormat myFormatter = new DecimalFormat(pattern);
        String output = myFormatter.format(value);
        System.out.println(value + "" + pattern + "" + output);
      
    3. Exception Handling: Remember "try" and "catch" from lecture? You might need to use those in order to test if a string is a correct float value.....in particular "NumberFormatException" and "ArithmeticException". Also refer to your Java2 reference book Chapter 10.



    Created by Ben Pack & Justin Giles 2001. Modified by Yuan Li © 2005