Review: String in Java (and other programming languages)
 

Important facts:

  • You can only enter inputs as ASCII codes with a keyboard

  • You can only print outputs as ASCII codes to a terminal

 

What is a string in a computer program:

  • A string (in Java or other programming languages) is an sequence (= array) of ASCII codes

    (Each ASCII code represents one character in the string)

The System.out.print( ) method

  • How the Java's System.out.print( ) method works:

    • It is overloaded

    • String and char typed inputs (in ASCII codes !) are sent verbatim (= unchanged) to the terminal

    • All other types of inputs must be converted to their String "equivalent" representation before printing

  • Conversion methods between primitive data types and String are defined in Wrapper classes in Java's library:

      Integer.toString( )      // CS170 material !
      Float.toString( )
      ... (and so on)
    

Java program that shows that a String is a series of ASCII codes (binary numbers)

This program shows the (1) character symbol, (2)+(3) ASCII code in decimal and (4) ASCII code in binary of each character in a string:

public class CharAt
{
   public static void main(String[] args)  throws Exception
   {
      String s = "ABC123";

      for ( int i = 0; i < s.length(); i++)
      {  
         System.out.println( s.charAt(i) );   
         System.out.println( (int) s.charAt(i) );   // Overloaded
         System.out.println( Integer.toString( s.charAt(i) ) );
         System.out.println( Integer.toBinaryString( s.charAt(i) ) );
      }
   }
}

(1) ASCII codes are printable (i.e.: can be displayed on a terminal)
(2) ASCII codes can also be used a (binary) numbers in computations !!!

DEMO program: /home/cs255001/demo/atoi/CharAt.java

The string comparison method compareTo( )
 

Recall that the compareTo( ) method uses the ASCII codes in strings as numbers:

   String s1, s2;

   if (   s1.compareTo(s2) < 0 )
      System.out.println( s1 + " preceeds " + s2 );
   else if ( s1.compareTo(s2) == 0 )
      System.out.println( s1 + " equals to " + s2 );
   else // s1.compareTo(s2) > 0
      System.out.println( s1 + " success " + s2 );
   

The s1.compareTo(s2) method call compares the (binary) ASCII codes in s1 and s2 as binary number values

Note: the method equals( ) also uses the ASCII codes as numeric values !

DEMO: /home/cs255001/demo/atoi/CompareTo.java