abstract, assert
boolean, break, byte,
case, catch, char, class, const*, continue,
default, do, double,
else, enum, extends,
false, final, finally, float, for,
goto*,
if, implements, import, instanceof, int, interface,
long,
native, new, null,
package, private, protected, public,
return,
short, static, strictfp, super, switch, synchronized,
this, throw, throws, transient, true, try,
void, volatile,
while
* not used
NOTE: Earlier versions of Java included additional reserved words (such as byvalue, cast, future, generic, inner, operator, outer, var) that are not reserved anymore.
There are three types of comments in Java:
The following example demonstrates each kind: (source file)
// This is an in-line comment. It ends at the end of this line. // This attempt to roll to the next line will fail to compile. /* Instead, long comments are best placed inside block comments like this */ /** * Finally, there is the type of documentation that * javadoc produces. To use this, you need to use javadoc * commands inside the comment block, such as: * @version 1.1 * @author Rahul Simha * @return No value returned * @param command arguments (any number of strings) * Note: each line must start with a `*' symbol. */ // javadoc will produce HTML documentation. To try it out, don't // forget to fix the in-line comment error above. public class HelloWorld3 { public static void main (String[] argv) { System.out.println ("Hello World!"); // prints to screen } }
Java has 8 pre-defined types:
Let's consider each of these in turn:
deficit = 1000000000L;
Before we get to objects, functions and the like, let's first worry about writing simple statements in a single function (method)
Let's start with a file called Test.java, in which we have a function (method) called main.
public class Test { public static void main (String[] argv) { // Put your code in here } }
Two rules in Java to remember:
Exercise 2.1: What happens if you do not have a main function in your file? Try compiling and executing such a file.
Variables are declared by following the type keyword with the identifier:
byte b; // A byte int i; // i is a 4-byte integer long num_stars; // A long integer float epsilon, delta; // Multiple variables separated by a comma double // Often, you use several lines for commenting: pi, // 3.14159 e, // 2.718 squareRootOfTwo; // Use Math lib for computing this boolean over;
Assignment uses the assignment operator =
int i, j; i = 7; j = 2000;
Variable declarations can occur almost anywhere
in a block of code.
Declarations and assignment can be combined where appropriate:
double pi = 3.14159; // Declaration and assignment combined int i = 3; double threePi; // Pure declaration while (true) { threePi = i * pi; // Pure assignment double fourPi = pi * 4; // Combination in a sub-block of code }
NOTE:
Constants in Java are a little strange.
Currently, the only way to declare a constant is as follows:
public class Test { public static final double pi = 3.14159; public static void main (String[] argv) { double d = pi; } }
NOTE:
Can the contents of an int variable be copied into a (assigned to) long variable? (Yes).
Can an double be assigned to an int? (Not directly).
For example:
int i = 5; long j; double d = 3.141; j = i; // Fine - an example of an implicit cast. i = d; // Won't compile - needs an explicit cast. d = i; // Fine (implicit cast).
To assign a variable of one type to another, use a cast. A cast is the desired type in parens, preceding the variable that needs casting.
int i = 5; long j; double d = 3.141; j = (long) i; // Not really needed. i = (int) d; // Truncates the real value; System.out.println (i); // Prints `3'
NOTE:
byte → short → int → long → float → double
public class Test { // A method that prints an integer. public static void print (int i) { System.out.println (i); } public static void main (String[] argv) { double d = 3.141; print ( (int) d); } }
Java supports standard C-style operators, for example:
public class TestOperators { public static void main (String[] argv) { int i = 5; i = i + 1; i += 1; // Same as i = i+1; // Pre and post-use increment: i = 10; System.out.println (++i); // Prints 11 i = 10; System.out.println (i++); // Prints 10 // Comparison operators: < > <= >= == != int j = 10; if (i != j) { System.out.println ("Help! i not equal to l!"); } // Casting: byte b = 8; long l = 100; i = i + b; // b is automatically converted to an int i = i + l; // Illegal - explicit cast required i = i + (int) l; // OK (explicit downward cast) b = b + 1; // Illegal: `1' is an integer l = l + 1; // OK, `1' is up-cast. b++; // OK, within type. // Bitwise operators: & | ^ << >> >>> &= |= ^= <<= >>= >>>= int x1 = 8, x2 = 15; int x3 = x1 & x2; System.out.println (x3); // What does this print? // Boolean type: boolean tired = true; boolean had_enough = true; // Boolean operators: && || ! if (tired && had_enough) { System.out.println ("Go home"); } } }
Complete list of operators:
Example:
public class StringExample { public static void main (String[] argv) { // Declare a string variable and assign it an actual string: String s = "The quick brown fox jumps over the lazy dog"; System.out.println (s); // Extract its length: int k = s.length (); System.out.println (k); // 43. Includes spaces. // You can identify any character in the string, such as: char c = s.charAt(0); System.out.println (c); // Prints 'T'. // The very useful concatenation operator + String s1 = "The"; String s2 = "quick"; String s3 = s1 + s2; // s3 is "Thequick" // You can concatenate any number of strings in an expression: String s4 = "brown"; String s5 = s1 + " " + s2 + " " + s4; System.out.println (s5); // You can concatenate any other type: String allLetters = ""; for (char ch='a'; ch<='z'; ch++) { allLetters = allLetters + ch; } System.out.println ("The alphabet: " + allLetters); // Example with concatenating integers onto a string: String num1to10 = ""; for (int i=1; i<=10; i++) { num1to10 = num1to10 + " " + i; } System.out.println ("Numbers 1 to 10: " + num1to10); } }
The String class contains many useful functions:
Java's control flow statements are the same as those in C/C++ except:
Let's go through the standard control flow statements:
if (i == 4) { System.out.println ("Four"); } if ( (i >= 4) && (i <= 8) ) { j = i; System.out.println ("Between 4 and 8"); }
Exercise 2.2:
Find out what happens if you use an assignment in an if-expression,
e.g.,
if (i = 4) {
System.out.println ("Four");
}
if (i < 4) { System.out.println ("Less than four"); } else if (i == 4) { System.out.println ("Exactly four"); } else { System.out.println ("More than four"); }Although braces were not required above, it's often considered a good habit to always use them.
i = 4; while (i > 0) { System.out.println (i); i = i - 1; }
int i; for (i=1; i<=10; i++) { System.out.println (i); } for (int j=1; j<=10; j++) { // Note definition of j i = i + j; System.out.println (j); } // j is not available here System.out.println (i); // What gets printed out?
Note: Comma-separated statements and expressions may appear in the first and third parts of the for-loop construct.
int[] A = {1,4,9,16,25}; // Standard for-loop using an array index: for (int i=0; i<A.length; i++) { System.out.println (A[i]); } // for-each loop that directly iterates over values in the array: for (int k: A) { System.out.println (k); }
if (i == 4) { System.out.println ("Four"); } else if (i == 3) { System.out.println ("Three"); } else if (i == 2) { System.out.println ("Two"); } else if (i == 1) { System.out.println ("One"); } else { System.out.println ("Not interesting"); }
you can write
switch (i) { case 4: System.out.println ("Four"); break; // The break is needed to // avoid falling to next case. case 3: System.out.println ("Three"); break; case 2: System.out.println ("Two"); break; case 1: System.out.println ("One"); break; default: System.out.println ("Not interesting"); }
while (true) { // Initially an infinite loop; // Stuff ... // Read integer from user if (i == -1) break; // Other stuff... } // Control reaches here on break
outerloop: // Label set up here, BEFORE loop starts. while (true) { // Initially an infinite loop; // Stuff ... // Read input from user while (true) { // Read one character at a time. if (invalid (c)) { break outerloop; } } // Other stuff ... } // Control reaches here on break
try { // Stuff ... } catch (Exception e) { // Deal with exception here ... System.out.println (e); }
Let's look at some examples:
public class TestArray { public static void main (String[] argv) { // Declaration: A is an array of int's int[] A; // The new operator instantiates an array with a given size. A = new int[10]; // Individual items are referred to using square brackets. // Indexing starts from 0. for (int i=0; i<10; i++) { A[i] = i; } // This will compile but create a runtime exception. A[10] = 5; // A.length is a field indicating the length. System.out.println ("Number of elements of array A: " + A.length + "\nContents:"); // Size can be determined dynamically. int size = 10; double[] B = new double[size]; // Arrays can be initialized String[] C = {"glyph", "gypsy", "myrrh", "rhythm", "syzygy" }; } }
Exercise 2.3:
Write a program that takes in command line arguments, prints out each
argument, the length of each argument and the average length of all the
arguments. Name your program
TestCommandLine
Here's sample output:
% java TestCommandLine aaa aaaa
Arg#0 = aaa, length = 3
Arg#1 = aaaa, length = 4
Average: 3.5
Example: let's create the identity matrix.
public class Test2DArray { public static void main (String[] argv) { int size = 5; int[][] identMatrix; // Create the first dimension - an array identMatrix = new int[size][]; // Create the second dimension - an array for each // element of the first dimension. for (int i=0; i < size; i++) { identMatrix[i] = new int[size]; // The size can be changed dynamically. } // We're done creating the 2D array. Now create the // identity matrix and print it out. System.out.println ("Identity matrix of size: " + size); for (int i=0; i < size; i++) { for (int j=0; j < size; j++) { if (i == j) { identMatrix[i][j] = 1; } else { identMatrix[i][j] = 0; } } System.out.print (identMatrix[i][j] + " "); } System.out.println (); } }
Since the 2D array is really an array of unidimensional arrays, the individual unidimensional arrays can be of different sizes.
The following example creates a triangle of 1's and prints it out:
public class Test2DArray2 { public static void main (String[] argv) { int size = 5; int[][] triangle; // There are `size' rows. triangle = new int[size][]; // Each row has a different number of elements. for (int i=0; i<size; i++) { triangle[i] = new int[i+1]; for (int j=0; j<triangle[i].length; j++) { triangle[i][j] = 1; } } // Now print. System.out.println ("Triangle of 1's:"); for (int i=0; i<size; i++) { for (int j=0; j<triangle[i].length; j++) { System.out.print (" " + triangle[i][j]); } System.out.println (); } } }
Exercise 2.4:
Compile and execute the above program. Then,
modify the above code to create
and print Pascal's triangle. Sample output:
1 1
1 2 1
1 3 3 1
1 4 6 4 1