SDSU CS 535: Object-Oriented Programming & Design
Fall Semester, 1997
Doc 3, Arrays, Strings, Control Structures

To Lecture Notes Index
San Diego State University -- This page last updated 08-Sep-97

Contents of Doc 3, Arrays, Strings, Control Structures


...Repetitive Strain Injuries slide # 1
...Arrays slide # 2
......Multidimensional Arrays slide # 6
...Strings slide # 7
......Reading Command Line Arguments slide # 12
...Control Structures slide # 15
......Methods slide # 19

Reference


The Java Programming Language, Arnold, Gosling, Chapter 5, 6, 8



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

Repetitive Strain Injuries


A good reference:

Repetitive Strain Injury: A Computer User's Guide

by Emil Pascarelli, MD
& Deborah Quilter

John Wiley & Sons, Inc
1994

Cost $14.95 in 1994

You can order directly from Wiley at:

1-800-225-5945


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

Arrays


class ArrayExamples      {
     public static void main( String args[ ] ) {

          int declarationTypeA[ ] = new int[5];
          float[ ]     floatArray;

          int[]     factorial = { 1,  1,  2,  6,  24,  120,  720,  5040  };
          char[]     vowels = { 'a',  'e',  'o',  'i',  'u' };

          floatArray = new float[ 25 ];

          // indexing starts at zero
          System.out.println( vowels[ 0 ] );

          System.out.println( floatArray.length );

          floatArray[ 32] = 42;

          System.out.println( "Never Reach here, " +
                    "Array bounds are checked at runtime" );
     }
}

Output
a
25
java.lang.ArrayIndexOutOfBoundsException
at ArrayExamples.main(classNotes.java:25)


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

class ArraysAreReferences      {
     public static void main( String args[ ] ) {

          int[ ]     integerArray     ;
          int[ ]     alias;
          integerArray  =  new  int[ 4 ];

          for ( int index = 0; index < integerArray.length; index++
)
               integerArray[  index  ]  =  5;

          alias = integerArray;          // Arrays are references
          alias[  2  ]  =  4
          System.out.println( integerArray[ 2 ] );
          
          integerArray  =  new int[ 3 ];

          System.out.println( integerArray[ 2 ]  );
          System.out.println( alias[ 2 ]  );
          System.out.println( integerArray  );

          alias = new int[5];
          }
     }
Output
4
0
4
[I@1a47b5

Doc 3, Arrays, Strings, Control Structures Slide # 4
Array As References in Pictures

int[ ] integerArray; int[ ] alias;
integerArray = new int[ 4 ];

for ( int index = 0; index < integerArray.length; index++ )
integerArray[ index ] = 5;


alias = integerArray;


alias[ 2 ] = 4;


integerArray = new int[ 3 ];


alias = new int[5];


Doc 3, Arrays, Strings, Control Structures Slide # 5
Arrays, References, Memory Leaks
Arrays are references!

Garbage collection reclaims arrays (or any references) that can not be accessed from the program!

References are initialized to null

When done with a reference set it to null if you want the space reclaimed via garbage collection

class ArrayExamples 
     {

     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 # 6

Multidimensional Arrays


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[][]     oddShaped;

          oddShaped = new int [ 4 ] [ ] ;

          oddShaped [  0  ]  =  new int [ 5 ];
          oddShaped [  1  ]  =  new int [ 2 ];
          oddShaped [  2  ]  =  new int [ 6 ];
          oddShaped [  3  ]  =  new int [ 3 ];

          for ( int row = 0; row < oddShaped.length; row ++ )
               for ( int col = 0; col < oddShaped[ row ].length; col++
)
                    oddShaped[ row ][ col ] = 10;
          }
     }


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

Strings


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 # 8
Java's String and 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

Strings are constant,
Their values cannot be changed after creation

Strings are constant for efficiency and security

class StringConstantExample 
{
     public static void main( String args[] ) 
     {
          String  firstName  = "ROGER";

          firstName.toLowerCase();
          System.out.println(  firstName  );

          firstName = firstName.toLowerCase();
          System.out.println(  firstName  );
          }
     }

Output
ROGER
roger
Doc 3, Arrays, Strings, Control Structures Slide # 9
== 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" );
          
          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 # 10
== and String: The Issue

String is an object

String variables are references

The == operator check 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 compiler can not always store equal strings in the same memory location

For example when strings are created dynamically at runtime,

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


Doc 3, Arrays, Strings, Control Structures Slide # 11
Some 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 the java documentation for the string class


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

Reading Command Line Arguments


class CommandLineExample 
{
     public static void main( String args[] ) 
     {
          System.out.println(  args.length  );

          for ( int k = 0; k < args.length;  k++ )  
          {
               System.out.println( "Argument " + k + "\t" + args[ k ] );
          };

     }
}
Example of Running Program

rohan 16-> java CommandLineExample  a   b   c   d   e

5
Argument 0      a
Argument 1      b
Argument 2      c
Argument 3      d
Argument 4      e



Doc 3, Arrays, Strings, Control Structures Slide # 13
Fancy Command Line Arguments

class CommandLineProperty 
     {
     public static void main( String args[] ) 
          {
          String firstName = System.getProperty( "first" );
          
          String defaultLastName = "Missing";
          String lastName = System.getProperty( "last",
                                                        defaultLastName );
          
          System.out.println( firstName );
          System.out.println( lastName );
          }
     }
Sample Use of Program

eli-> java -cs -Dfirst=Roger -Dlast=Whitney
CommandLineProperty

Roger
Whitney

eli-> java -cs -Dfirst=Roger CommandLineProperty

Roger
Missing

eli-> java -cs CommandLineProperty -Dfirst=Roger

null
Missing

Doc 3, Arrays, Strings, Control Structures Slide # 14
Command Line Flags

import sdsu.util.LabeledData;

class CommandLineFlags 
     {
     public static void main( String args[] ) 
          {
          LabeledData flags = new LabeledData();          
          flags.fromCommandLine( args );
          
          String userFirstName;
          if ( flags.containsKey( "first" ) )
               userFirstName = flags.getData( "first" );
          else
               userFirstName = "Not Known";
               
          String userLastName = 
                                   flags.getData( "last", "Not Known");
          
          System.out.println( userFirstName );
          System.out.println( userLastName );
          }
     }

Sample Use of Program

eli-> java CommandLineFlags -first Roger
Roger
Not Known

eli-> java CommandLineFlags -first=Roger
Roger
Not Known

eli-> java CommandLineFlags -last=Whitney
Not Known
Whitney

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

Control Structures


Contains all the standard C/C++ control structures

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


Doc 3, Arrays, Strings, Control Structures Slide # 16
// Control Structures Continued
          while ( a < b ) 
               {
               a++;
               };

          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 );     // What does this do?
          }
     }

Doc 3, Arrays, Strings, Control Structures Slide # 17
Jump Statements
break

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

Output
0 0
1 0
After if
1 1
2 0
3 0
After if
3 1
4 0

Doc 3, Arrays, Strings, Control Structures Slide # 18
Labeled Breaks
class ControlStructures 
     {
     public static void main( String args[] ) 
          {     
     
     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
0 0
Doc 3, Arrays, Strings, Control Structures Slide # 19

Methods (Functions)


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

Doc 3, Arrays, Strings, Control Structures Slide # 20
Warning

In the last example the methods, subtractOne and addOne, should not be static

After we have covered classes I will not accept this use of static.



Once we have covered classes it should be very clear why this use of static is not to be tolerated


Doc 3, Arrays, Strings, Control Structures Slide # 21
Parameter Passing - By value only

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

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

Arrays are references, a function can modify array elements

class ArrayAsParameter 
     {

     public static void main( String args[] ) 
          {
          int[]     integerArray  =  new  int[ 3 ];

          integerArray[ 1 ]  =  5;

          modifyElements( integerArray, 9 );

          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

9

Doc 3, Arrays, Strings, Control Structures Slide # 23
ArrayAsParameter By Pictures

integerArray[ 1 ]  =  5;



in modifyElements
modifyElements( integerArray, 9 );



for ( int index = 0;  index < changeMe.length;  index++ )
     changeMe[ index ] =  newValue;


Doc 3, Arrays, Strings, Control Structures Slide # 24
Arrays and Functions

Arrays are references, a function can not modify the array


class ArrayAsParameter 
     {

     public static void main( String args[] ) 
          {
          int[]     integerArray  =  new  int[ 3 ];

          integerArray[ 1 ]  =  5;

          doesNotWork( integerArray );

          System.out.println( integerArray[ 1 ] );
          }

     public static void doesNotWork( int[] changeMe )
          {
          changeMe = new  int[ 3 ];

          for ( int index = 0;  index < changeMe.length;  index++
)
               changeMe[ index ] = 999;
          }
     }

Output

5

Doc 3, Arrays, Strings, Control Structures Slide # 25
DoesNotWork in Pictures

In main
     integerArray[ 1 ]  =  5;


In doesNotWork:
changeMe = new int[ 3 ];


Back in main:



visitors since 08-Sep-97