Friday, July 4, 2008

JAVA-6

Variables and Data Types:-
There are eight primitive data types in Java:
1-boolean
2-byte
3-short
4-int
5-long
6-float
7-double
8-char
However there are only seven kinds of literals, and one of those is not a primitive data type:
boolean: true or false
int: 89, -945, 37865
long: 89L, -945L, 5123567876L
float: 89.5f, -32.5f,
double: 89.5, -32.5, 87.6E45
char: 'c', '9', 't'
String: "This is a string literal"
There are no short or byte literals.
Strings are a reference or object type, not a primitive type. However the Java compiler has special support for strings so this sometimes appears not to be the case.class Variables {
public static void main (String args[]) {

*boolean b = true;
*int low = 1;
*long high = 76L;
*long middle = 74;
*float pi = 3.1415292f;
*double e = 2.71828;
*String s = "Hello World!";

}

}

Comments:-
Comments in Java are identical to those in C++. Everything between /* and */ is ignored by the compiler, and everything on a single line after // is also thrown away. Therefore the following program is, as far as the compiler is concerned, identical to the first HelloWorld program. // This is the Hello World program in Java

class HelloWorld
{
public static void main (String args[]) {
/* Now let's print the line Hello World */
System.out.println("Hello World!");

} // main ends here
} // HelloWorld ends here
The /* */ style comments can comment out multiple lines so they're useful when you want to remove large blocks of code, perhaps for debugging purposes. // style comments are better for short notes of no more than a line. /* */ can also be used in the middle of a line whereas // can only be used at the end. However putting a comment in the middle of a line makes code harder to read and is generally considered to be bad form.
Comments evaluate to white space, not nothing at all. Thus the following line causes a compiler error:int i = 78/* Split the number in two*/76;
Java turns this into the illegal line
int i = 78 76;
not the legal line
int i = 7876;
This is also a difference between K&R C and ANSI C.

Command line argumentsclass:-
PrintArgs {
public static void main (String args[]) {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}

}

}
The name of the class is not included in the argument list.
Command line arguments are passed in an array of Strings. The first array component is the zeroth.
For example, consider this invocation:
$ java printArgs Hello There
args[0] is the string "Hello". args[1] is the string "There". args.length is 2.
All command line arguments are passed as String values, never as numbers. Later you'll learn how to convert Strings to numbers.

No comments: