CS 4773 Object Oriented Systems


The Java Language

The examples Test1.java through Test12.java are available in /usr/local/courses/cs4773/spring97/examples/set01

Primitive Types:


Type Promotion in Expressions

This is similar to C but it is more important in Java. Example:
class Test1 {
   public static void main(String args[]) {
      byte b = 25;
      b = b*4;
      System.out.println("Hello World! b = " + b);
   }
}
 
make Test1.class
javac Test1.java
Test1.java:4: Incompatible type for =.
Explicit cast needed to convert int to byte.
      b = b*4;
        ^
1 error
*** Error code 1
make: Fatal error: Command failed for target `Test1.class'
If you change byte to int everything works!
class Test2 {
   public static void main(String args[]) {
      int b = 25;
      b = b*4;
      System.out.println("Hello World! b = " + b);
   }
}
 
make Test2.class
javac Test2.java
 
java Test2
Hello World! b = 100

Assignment Conversion:

An automatic conversion will take place on assignment if the conversion is a widening.

A narrowing conversion is only allowed if:

The following is OK:
class Test3 {
   public static void main(String args[]) {
      byte b = 25;
      b = 100;
      System.out.println("Hello World! b = " + b);
   }
}
However, since Java is interpreted and there is no preprocessor, the following produces an error:
class Test4 {
   public static void main(String args[]) {
      byte b = 25;
      b = 25*4;
      System.out.println("Hello World! b = " + b);
   }
}
 
make Test4.class
javac Test4.java
Test4.java:4: Incompatible type for =.
Explicit cast needed to convert int to byte.
      b = 25*4;
        ^
1 error
*** Error code 1
make: Fatal error: Command failed for target `Test4.class'

Type Casting

Type Casting is severely limited.

Anything can be cast to a String

boolean values cannot be cast to anything else.

You can cast between any arithmetic types (integer, floating point, character)

Basically for objects, you can only cast if one is a subclass of the other.


Java Types and Default Values

No variable in Java ever has an undefined value.

All variables are given a value when they are created.

There are two classifications of types in Java.

Variables of primitive type are created by their declaration.
If not explicitly initialized, they are assigned a default value.
boolean variables have default value false.
All other variables of primitive type have default value 0.

All variables of reference type have default value null.


Arrays

This is a reference type.
This means that an array is represented by a pointer.

Unlike in C, arrays are created dynamically.
A declaration does not automatically create the array.
Arrays are created by new.

Array declarations which do not create an array:

   int num[];
int[] num;
Array declarations which do create an array:
   int num[] = new int[10];
int[] num = new int[10];
int num[] = {2,4,6,8};
Array declarations with run time creation:
   int num[];
   int size;
 
   size = 20;
   num = new int[size];
The size of an array is known at run time.

Bounds checking is done on all array references.

A program can determine the size of an array:

class Test5 {
   public static void main(String args[]) {
      int num[];
      int size;
      int i;
 
      size = 3;
      num = new int[size];
      for (i=0; i < num.length; i++)
         num[i] = i*i;
      for (i=0; i < num.length; i++)
         System.out.println("num[" + i + "] = " + num[i]);
   }
}
 
java Test5
num[0] = 0
num[1] = 1
num[2] = 4

Arrays with Multiple Dimensions

class Test6 {
   public static void main(String args[]) {
      double   matrix[][];
      byte[][] bytematrix = {{2,3,4},{6,8,10}};
 
      matrix = new double[3][12];
      int i,j;
 
      System.out.println("matrix has lengths " +
         matrix.length + " and " + matrix[0].length);
      System.out.println("bytematrix has lengths " +
         bytematrix.length + " and " +
         bytematrix[0].length);
      for (i=0; i<2; i++)
         for (j=0; j<3; j++)
         System.out.println(
            "bytematrix[" + i + "][" + j + "] = " +
            bytematrix[i][j]);
   }
}
 
java Test6
matrix has lengths 3 and 12
bytematrix has lengths 2 and 3
bytematrix[0][0] = 2
bytematrix[0][1] = 3
bytematrix[0][2] = 4
bytematrix[1][0] = 6
bytematrix[1][1] = 8
bytematrix[1][2] = 10

Strings

A String in Java is just a predefined class.

A String Example

class Test7 {
   public static void main(String args[]) {
      String str1 = "This is a string";
      String str2;
      String str3;
      String str4;
      int i = 5;
      char fourth;
 
      System.out.println("str1: " + str1);
      System.out.println("str1 has length " + str1.length());
      str2 = str1 + i;
      System.out.println("str2: " + str2);
      str3 = "This is" + " a string";
      System.out.println("str3: " + str3);
      if (str1.equals(str3))
          System.out.println("str1 equals str3");
      else
          System.out.println("str1 and str3 are different");
 
      str1 = "This is a new string 1";
      System.out.println("str1: " + str1);
      if (str1.equals(str3))
          System.out.println("str1 equals str3");
      else
          System.out.println("str1 and str3 are different");
      fourth = str1.charAt(3);
      System.out.println(
         "The fourth character in str1 is " + fourth);
   }
}
 
java Test7
str1: This is a string
str1 has length 16
str2: This is a string5
str3: This is a string
str1 equals str3
str1: This is a new string 1
str1 and str3 are different
The fourth character in str1 is s

A Command Line Arguments Example

class Test8 {
   public static void main(String args[]) {
      int numargs;
      int i;
 
      numargs = args.length;
      System.out.println(
         "Number of command line arguments: " + numargs);
      for (i=0; i< numargs; i++)
         System.out.println("   " + i + ": " + args[i]);
   }
}
 
java Test8
Number of command line arguments: 0
 
java Test8 abc def ghij
Number of command line arguments: 3
   0: abc
   1: def
   2: ghij
 
java Test8 abc "def ghij"
Number of command line arguments: 2
   0: abc
   1: def ghij

Arrays of Characters

The copyValueOf(char[]) static method of the class String returns a string made from a character array. The method
getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)
copies characters from the string into the array starting at srcBegin and ending before srcEnd.
class Test9 {
   public static void main(String args[]) {
      String str1 = "A string";
      String str2;
      char arr[];
      int strlen;
      int i;
 
      strlen = str1.length();
      System.out.println("str1: " + str1);
      System.out.println("str1 has length " + strlen);
      arr = new char[strlen];
      str1.getChars(0,strlen,arr,0);
      for (i=0; i< strlen; i++)
         System.out.println("   " + i + ": " + arr[i]);
      arr[2] = 'S';
      str2 = String.copyValueOf(arr);
      System.out.println("str2: " + str2);
   }
}
 
java Test9
str1: A string
str1 has length 8
   0: A
   1:
   2: s
   3: t
   4: r
   5: i
   6: n
   7: g
str2: A String

String Buffers

The StringBuffer class does not require prior knowledge of the size of the string.
class Test10 {
   public static void main(String args[]) {
      StringBuffer mystrbuf = new StringBuffer();
      String str1 = "A string of any size";
      String str2 = " Another string of any length";
      String str3;
 
      System.out.println("str1: " + str1);
      System.out.println("str2: " + str2);
      mystrbuf.append(str1);
      mystrbuf.append(str2);
      str3 = mystrbuf.toString();
      System.out.println("str3: " + str3);
   }
}
 
java Test10
str1: A string of any size
str2:  Another string of any length
str3: A string of any size Another string of any length

Operators

Java operators are similar to C operators.

Here are a few of the differences.


Flow Control

The following are similar to C: but no goto and a break or continue can refer to a label and transfer control out of a block from inside a nested block.
double arr[][];
 
outer:
   for (i=0; i < arr.length; i++) {
      for (j=0; i < arr[0].length; j++) {
         if (arr[i][j] == val) {
            foundit = true;
            break outer;
         }
      }  
   }
Like in C++, you can declare a variable in the initialization section of a for loop, but the scope of this variable is the body of the for loop.