SDSU CS 596 Java Programming
Fall Semester, 1998
Arrays, Strings, Control Structures
To Lecture Notes Index
© 1998, All Rights Reserved, SDSU & Roger Whitney
San Diego State University -- This page last updated 19-Sep-98

Contents of Doc 3, Arrays, Strings, Control Structures


Reference


The Java Programming Language, 2 ed., Arnold & Gosling, Chapter 5, 6, 8.1 - 8.5



Doc 3, Arrays, Strings, Control Structures Slide # 2

Arrays


Major differences with C/C++ arrays:

public class SimpleReferenceExample 
   {
   public static void main( String args[] ) 
      {
      // Reference allocated, no array space allocated
      float[]   sampleArray;         
      //allocate array locations on heap
      sampleArray = new float[ 12 ];
      // Indexing starts at 0 like C/C++
      sampleArray[ 0 ] = 3.2F;
      int[]   integerArray = new int[ 3 ];
   
      // Reference refers to new array.
      // Old array available for garbage collection
      sampleArray = new float[ 2 ];   
      }
   }


Doc 3, Arrays, Strings, Control Structures Slide # 3
More Reference Examples
public class ArrayExamples 
   {
   public static void main( String args[] ) 
      {
      // Two locations to place [ ] 
      int      integerArray[ ];
      int[ ]   alias;
      integerArray  =  new  int[ 10 ];   // Indexed from 0 to 9
      // Note use of .length to get array size
      for ( int index = 0; index < integerArray.length; index++ )
         integerArray[  index  ]  =  5;
      alias = integerArray;      // Arrays are references
      alias[  3  ]  =  10;
      System.out.println( integerArray[ 3 ] );      //Prints 10
      
      integerArray  =  new int[ 8 ];
      System.out.println( integerArray[ 3 ]  );      //Prints 0, Why?
      System.out.println( alias[ 3 ]  );         //Prints 10
      System.out.println( integerArray  );      //Prints [I@5e300868
      }
   }


Listen Here!Q-sept10 3mins Doc 3, Arrays, Strings, Control Structures Slide # 4

Arrays, References, Memory Leaks


Arrays are references!

Garbage collection reclaims arrays that can not be accessed!

References are initialized to null

When done with a reference set it to null

public classArrayExamples 
   {
   public static void main( String args[] ) 
      {
      int[]   integerArray  =  new  int[ 4 ];
      integerArray[ 1 ] = 12
      integerArray  =  new  int[ 2 ];   // Memory Leak - No!
      integerArray[  1  ]  =  5;
      int[]   aliasForArray  =  integerArray;
      aliasForArray[  1  ]  =  10;
      System.out.println( integerArray[ 1 ] );   //Prints 10
      }
   }

Doc 3, Arrays, Strings, Control Structures Slide # 5
Arrays, References

      int[]   integerArray  =  new  int[ 4 ];

      integerArray[ 1 ] = 12

      integerArray  =  new  int[ 2 ];   // Memory Leak - No!

      integerArray[  1  ]  =  5;

      int[]   aliasForArray  =  integerArray;

      aliasForArray[  1  ]  =  10;

Doc 3, Arrays, Strings, Control Structures Slide # 6
Memory Problems in C/C++

Memory Leaks

Memory that program has allocated but can no longer access
int* trouble = new int( 5 );
trouble = new int( 8 );
Dangling References

Two or more pointers point to the same memory on the heap
Using one of the pointers the memory is deallocated
Second pointer can still access the memory

Estimates are that up to 40% of development time in C/C++ are spent dealing with these two problems



Doc 3, Arrays, Strings, Control Structures Slide # 7
Java Solution

No pointers

No explicit deallocation of memory

When memory can no longer be accessed, garbage collection eventually reclaims the memory



Java's solution is more dynamic, flexible, and safer than C/C++

Doc 3, Arrays, Strings, Control Structures Slide # 8

Array Bounds and Initial Values


Any access of an array element is check at runtime to insure the element index is valid

The example below shows what happens when accessing an illegal index. More on this later

The lower index of an array is always zero

All array elements are given an initial value

The actual value given depend on the type

public class BoundsAndInitialValueExample 
   {
   public static void main( String args[] )
      {
      int[ ] data = new int[ 2];
      
      System.out.println( "Data[1]= " + data[1] );
      data[ 12] = 2;
      System.out.println( "After assignment"  );
      }
   }
Output
Data[1]= 0
java.lang.ArrayIndexOutOfBoundsException
   at BoundsAndInitialValueExample.main(BoundsAndInitialValueExample.java:9)


Doc 3, Arrays, Strings, Control Structures Slide # 9

Array Initializer's


One can initialize arrays to a list of values

The syntax is slightly different for declaration statements and assignments

There is no way to indicate repeated values in the initializer

public class InitializingArrays 
   {
   public static void main( String args[] ) 
      {
      // Short Declaration syntax
      int[ ]    odds = {1, 3, 5, 7, 9 };
      char[ ]    vowels = { 'a', 'e', 'i', 'o', 'u' };
      String[] names;
      // Assignment syntax - new in JDK 1.1.x
      names = new String[] { "Sam", "Sally", "Pete" };
      // Can use longer syntax in declarations
      char[] abc = new char[] { 'a', 'b', 'c' };
      //You can not use short syntax in assignments
      double[ ] trouble;
      
      trouble = { 1.2, 2.3, 5.4 };   //Compiler Error
      }
   }


Doc 3, Arrays, Strings, Control Structures Slide # 10

Multidimensional Arrays


public class MultidimensionalArrayExample 
   {
   public static void main( String args[] ) 
      {
      int[][]   squareArray = new int [ 10 ] [ 20 ];
      squareArray[ 2 ] [ 5 ] = 25;
      int[][][]   threeDArray = new int [ 10 ] [ 20 ][ 5 ];
      int[][]   triangularArray;
      triangularArray = new int [ 30 ] [ ] ;
      // Allocate rows of different length!
      for ( int row = 0; row < triangularArray.length; row ++ )
         triangularArray [  row ]  =  new int [ row ];
      // Fill array locations
      for ( int row = 0; row < triangularArray.length; row ++ )
         for ( int col = 0; col < triangularArray[ row ].length; col++ )
            triangularArray[ row ][ col ] = 10;
      // Initializers for multidimensional arrays, 
      //  note the different size rows
      int[ ] [ ] oddShape = {
            { 1 , 2, 3 } ,
            { 1, 2 },
            { 4, 5, 6, 7 }
         };
      }
   }


Doc 3, Arrays, Strings, Control Structures Slide # 11

Some JDK1.2 Array Features


JDK 1.2 add some useful operations on arrays as:

binary search
equals
fill
sorting

We will see more useful operations later

To use these features you must:
use JDK1.2
import java.util.Arrays


Arrays and Good OOP

Arrays in Java are not full objects

There is no Array class containing array operations

I assume this is done to:
Keep array syntax similar to C/C++
Performance reasons

As a result we now get a class java.util.Arrays which violates the spirit of a class

It has methods, but no data

Doc 3, Arrays, Strings, Control Structures Slide # 12
New Array Operation Example

import java.util.Arrays;
public class NewArrayOperations
   {
   public static void main( String[ ] args )
      {
      int [] list = { 9, 2, 5, 7, 1 };
      
      // Sorts using fancy quicksort
      Arrays.sort( list );
      
      // if not found, then return -1
      int foundIndex = Arrays.binarySearch( list, 7 );
      
      System.out.println( "Found 7 at: " + foundIndex );
      
      int[ ] ones = new int[ 12 ];
      
      // Fill array with value 1
      Arrays.fill( ones, 1 );
      System.out.println( "One: " + ones[10] );
      }
   }
Output
Found 7 at: 3
One: 1


Listen Here!Q-sept10 6mins Doc 3, Arrays, Strings, Control Structures Slide # 13

Strings


public class StringExample 
{
   public static void main( String args[] ) 
   {
      String  firstName  = "    Roger    ";
      String  lastName  = "    Whitney     ";
      String  fullName  =  firstName  + lastName;
      System.out.println(  fullName  );
      firstName  =  firstName.toLowerCase();
      lastName  =  lastName.toUpperCase();
      System.out.println(  firstName  );
      firstName  =  firstName.trim();   // trim leading, trailing
      lastName  =  lastName.trim();   // white space
      lastName  =  lastName.replace( 'I', 'a' );
      System.out.println(  firstName  + lastName  );
      String floatAsString  =  String.valueOf( 13.4e+5f);
      System.out.println(  floatAsString  );
   }
}
Output
    Roger        Whitney
    roger
rogerWHaTNEY
1.34e+06


Doc 3, Arrays, Strings, Control Structures Slide # 14

Strings are Constant!


Once a string is created its value cannot be changed. One can create a new string from the old one with changes. This is a security feature.

If strings could change, once a String has been accepted as a secure operation one could change the string before the operation was performed.

In the StringExample above I used toLowerCase(). This method returns a new string with all characters in lower case. I assigned the new string to the same string variable!

      firstName  =  firstName.toLowerCase();

The variable firstName now references the new string. The old string has not changed!

Doc 3, Arrays, Strings, Control Structures Slide # 15
String is a Class

Actual strings in Java are objects

This means that String variables are references to the objects

String Operations

charAt(int)replace(char,char)
compareTo(String)startsWith(String)
concat(String)substring(int,int)
copyValueOf(char[])toCharArray()
endsWith(String)toLowerCase()
equals(Object)toUpperCase()
equalsIgnoreCase(String)trim()
getChars(int,int,char[],int)valueOf(int)
indexOf(String)valueOf(long)
lastIndexOf(String)valueOf(float)
length()valueOf(double)
regionMatches(int,String,int,int)

For more information see: http://www.sdsu.edu/doc/jdk1.1/docs/api/java.lang.String.html


Doc 3, Arrays, Strings, Control Structures Slide # 16
String vs. char[] vs. C/C++ char*

Neither String nor char[] end in the null character like char* in C

char[]
Array of characters
Only array operations are supported

String
Is a class with numerous operations
Integrated into Java's ~200 classes


Listen Here!Q-sept10 13mins, Q-sept10 8mins Doc 3, Arrays, Strings, Control Structures Slide # 17

== and Strings


public class StringTest
   {
   public static void main( String[] args )
      {   
      String me   = "Roger";
      
      if ( me == "Roger" )
         System.out.println( "Yes, I am me" );
      else
         System.out.println( "No, I am not me?" );
      
      String shortName = me.substring( 0, 3 );
      System.out.println( shortName );
      
      if ( shortName == "Rog" )
         System.out.println( "Very Good" );
      else
         System.out.println( "Trouble here" ); //How is this possible?
      
      if ( shortName.equals( "Rog" ) )
         System.out.println( "Do it this way" );
      
      }
   }
Output
Yes, I am me
Rog
Trouble here
Do it this way

Doc 3, Arrays, Strings, Control Structures Slide # 18
== and Strings: The Issue

String variables are references to objects. The == operator checks to see if two string references refer to the same memory location.

      if ( me == "Roger" )
         System.out.println( "Yes, I am me" );
      else
         System.out.println( "No, I am not me?" );

Compilers are allowed, but not required to store equal strings in the same memory location. The comparison above checks to see if the two variables refer to the same memory location. Since me was initialized with a string literal the compiler was smart enough to store the two strings in the same location.

In the comparison:
      if ( shortName == "Rog" )

shortName was not initialized with a literal, so the compiler did not know to store in the same location as "Rog". Thus this comparison is false !

The equals method compares the two strings to determine if they have the same length and are the same character by character.

Be safe and use the "equals" method to compare strings


Doc 3, Arrays, Strings, Control Structures Slide # 19

Reading Command Line Arguments


We can now read the arguments from the command line

The process is very similar to C/C++

Java has an additional method of passing information from the command line to a program, will cover this later

public class CommandLineExample 
{
   public static void main( String args[] ) 
   {
      System.out.println(  "Args length: " + args.length  );
      for ( int k = 0; k < args.length;  k++ )  
      {
         System.out.println( "Argument " + k + "\t" + args[ k ] );
      };
      Float secondArgument = Float.valueOf( args[ 1 ] );
      System.out.println( secondArgument );
   }
}
Sample Session Running above Program
rohan 16-> java CommandLineExample  1   2   3   4   5
Args length: 5
Argument 0      1
Argument 1      2
Argument 2      3
Argument 3      4
Argument 4      5
2


Listen Here!S-sept9 27secs, Q-sept10 32secs Doc 3, Arrays, Strings, Control Structures Slide # 20

Control Structures


Contains all the standard C/C++ control structures

public class Control 
   {
   public static void main( String args[] ) 
      {
      int a = 5;
      int b = 10;
      if ( a > b ) System.out.println( "a is bigger ");

      if ( a > b ) 
         System.out.println( "a is bigger ");
      else
         System.out.println( "b is bigger ");
      switch ( a ) 
         {   //Controlling expression converted to int
         case  4: 
            b++;
            break;
         case  10: 
            b--;
            break;
         default:                     // optional
            System.out.println( "Default action" );
         };
      while ( a < b ) 
         {
         a++;
         };

Doc 3, Arrays, Strings, Control Structures Slide # 21
// Control Structures Continued

      for  ( int loop = 0;  loop  < a;  loop++ ) 
         {
         System.out.println( a );
         };
      
      System.out.println( loop );   // Error, loop does not
                              // exist here
      do 
         {
         System.out.println( a-- );
         System.out.println( b );    
         }
      while ( a > b );
      int max  =  ( a > b ) ?  a  :  b;
      if  ( ( a > 5 ) &&  ( b < 10 ) ) 
         System.out.println( "Good" );
      a  += ( a = 5 );
      }
   }

Doc 3, Arrays, Strings, Control Structures Slide # 22

Jump Statements

break

Exits out of a loop or switch statement

Unlabeled break exits out of the innermost loop or switch

Use labeled break to exit out of nested loops or switch

public class BreakExample {
   public static void main( String args[] ) {
      for ( int row = 0; row < 5;  row++  )  { 
         for (  int column = 0; column < 4 ;  column++ )   {
            System.out.println( row + "\t" + column );
            if ( ((row + column) % 2 ) == 0 )
               break;
            System.out.println( " After if " );
         }
      };
      Outer:
      for ( int row = 0; row < 5;  row++  )  { 
         for (  int column = 0; column < 4;  column++ )  {
            System.out.println( row + "\t" + column );
            if ( ((row + column) % 2 ) == 0 )
               break Outer;
            System.out.println( " After if " );
         } 
      } 
   }
}
Output (Read Down Column First)
0 03 0
1 0 After if
After if3 1
1 14 0
2 00 0


continue

A continue statement skips to the end of the current loop's body

The loop's boolean expression is then evaluated


Methods (Functions)


What are called "functions" in C are called "methods" in Java

When we cover Classes we will talk about:
the difference between methods and functions
"static" and "public"

Note we do not have to forward declare methods, addOne is used before it is declared

public class SampleFunction {
   public static int subtractOne( int  decreaseMe )   {
      return  decreaseMe - 1;
   }
   public static void main( String[] args ) {
      int  startValue  =  5;
      int  smaller  =  subtractOne(  startValue  );
      int  larger  =  addOne(  startValue  );
      System.out.println( "smaller = " + smaller + "\n" +
                      "larger = " + larger );
   }
   public static int addOne( int  increaseMe ) {
      return increaseMe + 1;
   }
}
Output
smaller = 4
larger = 6


Parameter Passing - By value only

In Java all parameters are passed by value
  • The method gets a copy of the parameter
  • Changes to a parameter in a method are valid only in the method


public class TestParameter
   {
   public static void main( String[] args ) 
      {
      int  startValue  = 5;
      noChange(  startValue  );
      System.out.println(  startValue  );
      }
   public static void noChange(  int fixed  )
      {
      fixed = fixed + 10;
      }
   }
Output
5


Returning Information from a Method

To return information from a method you can:
  • Use a return statement
  • Use an array as a parameter
  • Use an object as a parameter (Covered later)


Return Statement

public class ReturnExample
   {
   public static int change( int input )
      {
      return input + 10;
      }
   
   public static void voidReturnExample( int data )
      {
      if (data > 10 )
         return;
      
      if (data < 5)
         System.out.println( "Under 5");
      else
         System.out.println( "Over 5");
      }
   }


Arrays and Methods

A method can modify individual array elements

The modified elements remain modified outside the method

public class ArrayAsParameter 
   {
   public static void main( String args[] ) 
      {
      int[]   integerArray  =  new  int[ 10 ];
      integerArray[ 1 ]  =  5;
      modifyElements( integerArray, 10 );
      System.out.println( integerArray[ 1 ] );
      }
   public static void modifyElements( int[] changeMe, int newValue )
      {
      for ( int index = 0;  index < changeMe.length;  index++ )
         changeMe[ index ] =  newValue;
      }
   }

Output
10


Arrays and Methods

Arrays are references. A reference to an array is passed to a method. The method gets a copy of this reference. The reference points to the same array on the heap as the original array reference. This is why any changes to the array elements are not local to the method. However, as the example below shows, changes to the reference itself remain local to the method.

public class ArrayAsParameter 
   {
   public static void main( String args[] ) 
      {
      int[]   integerArray  =  new  int[ 10 ];
      integerArray[ 1 ]  =  5;
      doesNotWork( integerArray );
      System.out.println( integerArray[ 1 ] );
      }
   public static void doesNotWork( int[] changeMe )
      {
      changeMe = new  int[ 10 ];
      for ( int index = 0;  index < changeMe.length;  index++ )
         changeMe[ index ] =  555;
      }
   }

Output
5

Final Variables


Declaring a variable or parameter as final means that its value can not be changed.

Final variables can be given a value only once!

public class FinalExamples
   {
   public static void fixed( final double fixedValue )
      {
      double newValue = fixedValue + 1;
      fixedValue = fixedValue + 1;       //Compile error
      
      final int aConstant = (int) fixedValue;
      
      final int aBlankFinal;   //This is ok
      
      aBlankFinal = 12;      //This is ok
      
      aBlankFinal = 13;      //Compile error
      }
   
   public static void fixedArray( final int[] data )
      {
      data[2] = 4;      // This is ok, Why?
      data[2] = 5;      // This is ok
      
      data = new int[ 4];   //Compile error
      }
}

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

visitors since 02-Sep-98