Class 3: Types


Int Types
Different kinds of int: int (32bit), short (16bit), long (64bit). The following program has lots of interesting features. First, it demonstrates the difference between int and long: try this out on, for instance, 17!. Second, it shows off the ?:-operator. Third, it shows that functions can be used before they are defined, unlike C++ ... so there's none of that pesky prototype stuff! Fourth, it demonstrates that function overloading is still very much in play, just like C++. Finally, we see an automatic type conversion in the int-to-long assignment.
/********************************************************************
 * This program demonstrates the difference between long and int.
 ********************************************************************/
import java.util.*;

class IntDemo
{
  public static void main(String[] args)
  {
    Scanner s = new Scanner(System.in);
    int n1 = s.nextInt(); 
    System.out.println(n1 + "! = " + factorial(n1));
        
    long n2 = n1; 
    System.out.println(n2 + "! = " + factorial(n2));
  }

  static int factorial(int n)   { return n == 0 ? 1 : n*factorial(n-1); }
  static long factorial(long n) { return n == 0 ? 1 : n*factorial(n-1); }

}
Notice what happens when, as a user, I enter something that the scanner can't process as an int:
$ java IntDemo 
bad user input! ← User Input!
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:857)
	at java.util.Scanner.next(Scanner.java:1478)
	at java.util.Scanner.nextInt(Scanner.java:2108)
	at java.util.Scanner.nextInt(Scanner.java:2067)
	at IntDemo.main(IntDemo.java:9)
This is pretty typical. When things go wrong in a Java program you get a whole bunch of information about what went wrong and where! This is a good thing!

Char Type
The char type looks on the surface just like C++. However, Java inherently uses unicode! Unicode is like ASCII, except it has many, many more symbols. That means you have a much, much larger alphabet to work over. Consider this wonderful program:
import java.util.*;

class CharDemo
{

  public static void main(String[] args)
  {
    Scanner s = new Scanner(System.in);
    
    char a = 'X';
    char b = s.next(".").charAt(0); // This will be a mystery!
    System.out.println("a = " + a + ", b = " + b);

    // here are some funky Unicode symbols!
    char c = '\u27F0';
    char d = '\u0103';
    System.out.println("Ex: " + c + " " + d + " " + '\u016E');

  }

}
First of all, don't ask about why reading a single char is what it is. Just take it on faith. Now, what does this output look like?
$ java CharDemo
% ← User Input!
a = X, b = %
Ex: ⟰ ă Ů

Type Casts
The basic numeric types (long, int, short, char, double, float) all allow conversions via explicit casts (like (int)x), as well as implicit cases via assignment, function calls or promotion in expressions. This is all pretty much like C++.

The boolean type is different. Unlike C++, int or float or char values aren't automatically cast to boolean in contexts like if's/while's/for's which require booleans. On balance, this is probably a good thing, as you can't accidently write

	    if (x = 5)
	  
and have it compile. The compiler will barf on this.

Strings
Strings are different. The notes go into that. I just want to elaborate on one point. The + operator works to that if one argument is a string, the other is automatically converted to a string. Lots of what we've done already for output relied on that. This means, however, that the precedence and associativity of operators really matters in these kinds of expressions:
import java.util.*;

class StringPrecAssoc
{

  public static void main(String[] args)
  {
    int a = 2;
    int b = 3;
    System.out.println(a+b+"foo"); // prints 5foo
    System.out.println("foo"+a+b); // prints foo23
    System.out.println("foo"+a*b); // prints foo6
  }
}
In case you've forgotten: precencence is what determines which operator is applied first when different operators are involved. Associativity is what determins which occurence of two of the same operators is applied first.

Arrays
class ArrayEx
{
  public static void main(String[] args)
  {
    for(int i = 0; i < args.length; ++i)
      System.out.println("args[" + i + "] = " + args[i]);

    System.out.println(args[args.length]);
  }
}
When we run this program we get the following:
$ java ArrayEx the rain in "Spain falls" mainly on the plains
args[0] = the
args[1] = rain
args[2] = in
args[3] = Spain falls
args[4] = mainly
args[5] = on
args[6] = the
args[7] = plains
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
	at ArrayEx.main(ArrayEx.java:10)
Once again, notice how Java complains loudly when there's an error. What's especially significant here is that Java notices when you try to access an array with an invalid index (i.e. off the end of the array), refuses to do it for you, and exits the program with a useful error message.


Christopher W Brown
Last modified: Wed Aug 19 11:00:04 EDT 2009