Operators, Promotions, and Casts
Since Java is a very strict language when it comes to types and declarations, most common errors can be caught at compile time.
Patrick Naughton
from THE JAVA HANDBOOK
Java's resemblance to C and C++ can often be deceiving. One place where "C attitudes" cause the most confusion is in the handling of arithmetic types. In this section we focus on some of these differences in attitude.
- Rule 1
- byte, short and char are automatically promoted to int in all arithmetic operations.
- Rule 2
- Narrowing requires explicit casts
- Rule 3
- Narrowing consists of dropping bits.
The first two examples show the effect of these three Rules.
The unsigned shift operator
Java provides a new operator (>>>) which is "unsigned shift" . However it must be used with care because of the "Rules" as the example in the frame below shows.
Trying to do something useful
The next example is that of a program that:
- Accepts a line of input consisting of two integers (separated by a single blank character).
- Adds them.
- Outputs the result.
The program highlights difficulties Java faces with primitive types as well as the consequences of not providing programmer defined operator overloading. First here is the output with the program as is, then after an attempt to " overload" +
Now here are the program highlights.
import java.io.*;
import java.util.*;
The program uses a number of classes. "KeyBdIn" is defined in the source
code, but the others must be imported from class libraries
class Tester {
public static void main(String args[]){
KeyBdIn kb =new KeyBdIn();
StringTokenizer stok = new StringTokenizer(kb.GetKeys()," \n",false);
The StringTokenizer class provides tools for
parsing Strings. The arguments that are passed to the constructor are
- a string
- the list of break characters
- a boolean value to determine whether or not the break character should be included in the token.
nextToken() returns the next token substring.
String s=stok.nextToken();
Integer i=new Integer(s);
Integer is a "wrapper" class for byte, short, and int that allows some useful actions including formating
s=stok.nextToken();
Integer j=new Integer(s);
System.out.println(i.intValue()+j.intValue());
}
}
class KeyBdIn{
public String GetKeys(){
char b[] =new char[20];
int i=0,ihold=0;
try{while((ihold=System.in.read())!='\n')
{b[i++]=(char)ihold;}}
catch(IOException e){}
Exceptions will be discussed in the next section.
return new String(b,0,i);
}
}
Next |
Back