Review: String in Java (and other programming languages)
 

What is a string in a computer program:

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

    (One ASCII code represents one character in the string)

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

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( Integer.toBinaryString(s.charAt(i)) );
         System.out.println( Integer.toString(s.charAt(i)) );
      }
   }
}
   

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

Reading integer numbers from keyboard input

In CS170, you have learned this method to read integer inputs from the console (keyboard):

   Scanner in = new Scanner(System.in); 

   int x = in.nextInt( );
   
 

The nextInt( ) method in Java consists of 2 method calls.
This is an alternate way to read integer input in Java:

   Scanner in = new Scanner(System.in); 

   String s = in.next( ); // Read input as a String
   int x = Integer.parseInt(s); // Conv String to 2s compl
   

The next( ) method in the Scanner class
 

The next( ) method:

  • The next( ) method returns the input string (= series of ASCII codes (= binary numbers) entered by the user
 

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

The parseInt( ) method in the Scanner class
 

The parseInt( ) method:

  • The parseInt( ) method returns the integer representation (= a 2s complement code) for the input number string (= series of ASCII codes passed to the method
 

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

 

The parseInt( ) method is an example of a conversion method needed in computer programming that convert between different kinds of representations!!!