Module 2: Elementary Java, Part I


Java Syntax

 
 


Comments in Java

 

There are three types of comments in Java:

  1. In-line comments, using // that comment out everything up to end of the current line.

  2. Block comments (C-style) using /* and */ that comment out everything in between.

  3. Documentation comments using /** and */ that are used by the javadoc utility to produce documentation.

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
  }
}
 


Built-in data types:

 

Java has 8 pre-defined types:

Let's consider each of these in turn:

 


Identifiers in Java

 
 


Getting started with writing Java

 

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:

  1. The filename and the public class name must be the same.
  2. The main method needs to be in the class with the same name as the file name.

Exercise 2.1: What happens if you do not have a main function in your file? Try compiling and executing such a file.
 


Variables and assignment

 

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

 

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:

 


Type conversions and casting

 

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:

 


Operators

 

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:

 


Strings

 

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:

 


Control flow statements

 

Java's control flow statements are the same as those in C/C++ except:

Let's go through the standard control flow statements:

 


Unidimensional arrays

 
Like Strings, arrays in Java are "sort-of" objects.

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
 


Multidimensional arrays

 

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 



© 1998, Rahul Simha (revised 2017)