Tuesday, 4 May 2010

Casting

The cast operator (type) is used to convert numeric values from one numeric type to another or to
change an object reference to a compatible type.

A widening conversion is a conversion from a smaller numeric type to a larger numeric type. An
example of a widening conversion is when a byte value is promoted to an int value. A narrowing
conversion is a conversion from a larger numeric type to a smaller numeric type. A conversion from a
long value to a short value would be an example of a narrowing conversion. Narrowing conversions
require the use of the cast operator.

double d = 123.456;
byte b;
b = (byte) d;

Rules for casting
When casting is used with object references, the following rules apply:
1. A reference to any object can be cast into a reference to an object of class Object.
String s = "abcd';
Object o = s;

2. A reference to an object can be cast into a reference to an object of class C', if the actual class of the object is a subclass of C'.
Subclass s = ...  ;
Base b = s;

3. A reference to an object can be cast into a reference to an object of interface I, if the actual class of the object implements I, if the object is of interface type I' and I' is a subinterface of I, or if the object is an array type and I is the Cloneable interface.
class X implements I{}
X x = ... ;
I i = x;
For example, a Vector object can be cast to a List object, and a List object can be cast to a Collection object. Because the array type implements the Cloneable interface, any array can be cast into a Cloneable object.

4. A reference to an object can be cast a reference to an object of an array type (with element reference type T), if the object is of an array type (with element reference type T') such that T' can be cast into T.

Casting to array types is more complicated. In order to cast to an object reference to an array type reference, the object must be an array of a component type that is compatible with the component type of the array type reference.
As an example of object type casting, consider the following program. Without the (String) cast operator, the result returned by v.elementAt(0) is an object of the Object class. The compiler recognizes this inconsistency and generates an error message. When the (String) cast operator is used, the compiler recognizes that you are casting the reference to an Object object into a String object and proceeds with the compilation.

String s1 = "abc";
String s2 = "def";
Vector v = new Vector();
v.add(s1);
s2 = (String) v.elementAt(0);
System.out.println(s2);

Monday, 3 May 2010

Numeric promotion

When binary operations are applied to numeric arguments (integer and floating-point), numeric
promotion is performed before the operation takes place. The numeric promotion consists of converting
the values of the operands to a common type. The rules for this conversion are straightforward.
  •  If one of the operands is a double, then the other is converted to a double.
  •  Otherwise, if one of the operands is a float, then the other is converted to a float.
  •  Otherwise, if one of the operands is a long, then the other is converted to a long.
  •  Otherwise, both operands are converted to int values.
Make sure that you remember these rules. You won't be tested on the rules themselves, but you'll need
to know them to work through related questions.

One thing that you probably will see on the test is + operations involving a numeric value and a String value. These questions test your knowledge of the difference between the arithmetic + operator and the String + operator. The String + operator results in the concatenation of two String objects. For example, "abc" + "def" results in "abcdef". But what about, 10 + "0" or "2.4" + 2.5?
The rule that you should remember is that when one of the operands in a + operation is a String, then
the other operand is converted to a String. Therefore, 10 + "0" results in the String "100" and
"2.4" + 2.5 results in the String object "2.42.5". The other operand is converted to a String
object in one of two ways, depending on whether the operand is an object or a value of a primitive type.
If the other operand is an object, then its toString() method is invoked to convert it to a String
object. If the other operand is a value of a primitive type, then an object of the type's wrapper class is
created and the object's toString() method is invoked
to convert it to a String object.

Language Fundamentals : The main() Method and command line arguments

The main() method is used as the entry point for a Java application program. All programs must have
a main() method or they cannot be run. The main() method is a method of the class that is executed
to run the program.
Note Importing java.lang The java.lang package is always imported by default and does not need to be imported by an import statement.
For example, if your program's name is MyProgram, then the MyProgram class must be defined in a
file named MyProgram.java. The MyProgram class must have a correctly defined main() method.
A correctly defined main() method has the following form:
public static void main(String[] args) {
// Statements go here
}
The main() method must be declared as public, static, and void.
The void keyword must appear immediately before main().
The public and static keywords may be interchanged.
The main() method has one argument—an array of String arguments. This argument may be defined as
String[] args or String []args or String args[]. The args argument may use any valid
identifier. For example, you can use arg, myArgs, or parms. However, args is standard, and you
should probably stick with it. As a convention, when I refer to args, I'm referring to the argument to a
program's main() method.
The args array is used to access a program's command-line arguments. These arguments are passed
to a program when it is invoked. They are passed as part of the command that is used to invoke the
program.

Note Applets Applets are not required to have a main() method.

For example, to run the MyProgram program, you would enter
java MyProgram
Suppose that you wanted to pass the arguments 2 and 3 to MyProgram. You would invoke it as follows:
java MyProgram 2 3
The String object "2" would be accessed as args[0], and the String object "3" would be accessed as args[1]. If you are a C or C++ programmer—pay attention. Java accesses commandline
arguments using different indices than do C and C++ programs.
The ArgsTest program of Listing 2.1 shows how command-line arguments are accessed using the
args array. When you run the program using the following command line
java ArgsTest this is a test
it displays the following results
args[0] = this
args[1] = is
args[2] = a
args[3] = test
Listing 2.1: The Argstest Program
class ArgsTest {
public static void main(String[] args) {
for(int i=0;i
System.out.println("args["+i+"] = "+args[i]);
}
}
}

Language Fundamentals : Main methods and Java program structure

The Structure of Java Programs
Java programs are composed of declarations of classes and interfaces. Classes define variables, which
provide named access to data, methods, which perform actions consisting of operations on the data,
and constructors, which create instances of classes, referred to as objects. Data items consist of
primitive data values—such as byte, char, and int values—and objects—such as arrays, I/O
streams, and GUI elements.

Interfaces define collections of methods that are implemented by classes. They are also used to define
constants, which are data values that cannot be changed.
Java programs are written using one or more compilation units, which are Java source code files. Every
source code file consists of the name of a class or interface followed by the .java extension. Since java identifiers are case-sensitive, source code filenames are also case-sensitive.

Source file : Each source code file may contain at most one public class or interface. If a class or interface is
declared as public, the source code filename must be the name of the class or interface (followed by
the .java extension). If a source code file does not contain a public class or interface, it may take on
a name that is different from its classes and interfaces.

Identifying Packages
Java classes and interfaces are organized into packages. Packages provide a naming context for
classes and interfaces. In other words, packages enable different programmers (or even the same
programmer) to create classes and interfaces with the same name. For example, if you and I both
create a class named Cool and then use the two different versions of Cool in the same program, the
compiler and runtime system won't know which version to use. But, if I put my Cool class in the My
package, and you put your Cool class in the You package, the compiler and runtime system will have
no problem, as long as we refer to Cool using its package name.
Packages are identified by the package statement. It must appear as the first statement in a source
code file
package packageName;
Note Use of Packages In addition to being used as a naming context, packages are used to organize related classes and interfaces into a single API unit to which access may be controlled.
If a package statement is omitted, the classes and interfaces declared within the package are put into
the default no name package. In the Java 2 Platform Software Development Kit (SDK), the package
name and the CLASSPATH environment variable are used to find a class or interface that is located in
another package.
Importing Classes and Interfaces from Other Packages
The import statement is used to reference classes and interfaces that are declared in other packages
(without having to specify their names each time they are referenced). There are three forms of the
import statement:
import packageName.className;
import packageName.interfaceName;
import packageName.*;
The first and second forms enable the identified classes and interfaces to be referenced without
specifying the name of their package. The third form allows all classes and interfaces in the specified
package to be referenced without specifying the name of their package.

The Main method and command line arguments