Previous Day Summary

Java source code is plain text
Any text editor can be used to write Java source code; jEdit is the recommended editor in CSE 1020.

A Java main method is a sequence of Java statements
For now, you can safely think of each line of code in your main method as a step in a sequence: The first line of code is evaluated, followed by the second, followed by the third, and so on.

Java source code needs to be compiled
Java source code in and of itself does not produce a functioning program. We use a program called a Java compiler to translate the source code to computer instructions.

Compiled Java code can be run
A compiled Java program can be run. In CSE 1020, we run the program using the Java virtual machine.

Complete the checklist on the Day 01 handout.

slanted W3C logo

Day 02: Java Basics

We use the HairsOnHead example to illustrate some of the elements of a Java program. The concept of types and a memory model of the assignment operation are introduced.

Elements of the Java Language

For our purposes, the Java language is made up of 3 elements:

Whitespace
space, tab, newline, return
Comments
specially marked text that the compiler does not try to interpret as Java code
Tokens
everything else that is not whitespace or a comment

Whitespace and comments act as separators for tokens.

Whitespace

Comments

A comment is text in source code that the programmer wants the compiler to ignore. Ideally, you write comments to explain to humans what your code is trying to do.

An end-of-line comment begins with // and continues to the end of the current line (i.e., the comment is at most one line long).

      // Step 1
      int diameter = 17;    // guesstimate of average diameter 

A traditional comment begins with /* and ends when */ is encountered (i.e., the comment can span multiple lines).

      /* Step 2
         Guestimate of the average fraction
         of a human head covered with hair
       */
      double fractionCovered = 0.5;

Tokens

There are 5 kinds of tokens:

Keywords
Words with special meaning in the Java language; all of them are in all lowercase.
Identifiers
Words made up by a programmer (not necessarily you) that are used as names for things.
Literals
A value that you can write down.
Operators
Similar to, but not exactly the same as, the usual mathematical operators.
Separators
All of the following:
[ ] ( ) { } ; , .

Keywords

Words with special meaning in the Java language; all of them are in all lowercase. See the table in Chapter 1, or google "java keywords".

public class HairsOnHead
{
   public static void main(String[] args)
   {
      // Step 1
      int diameter = 17;

      // Step 2
      double fractionCovered = 0.5;

      // Step 3
      double areaCovered = fractionCovered * Math.PI *
                           diameter * diameter;

      // Step 4
      int density = 200;

      // Step 5
      double numberOfHairs = areaCovered * density;

      // Step 6: Print out the result
      System.out.print("The number of hairs on a human head is ");
      System.out.println(numberOfHairs);
   }
}

Identifiers

Words made up by a programmer (not necessarily you) that are used as names for things. You cannot use a keyword as an identifier.

Identifiers always begin with a Java letter, and may contain letters, digits, and _.

public class HairsOnHead
{
   public static void main(String[] args)
   {
      // Step 1
      int diameter = 17;

      // Step 2
      double fractionCovered = 0.5;

      // Step 3
      double areaCovered = fractionCovered * Math.PI *
                           diameter * diameter;

      // Step 4
      int density = 200;

      // Step 5
      double numberOfHairs = areaCovered * density;

      // Step 6: Print out the result
      System.out.print("The number of hairs on a human head is ");
      System.out.println(numberOfHairs);
   }
}

Operators

Similar to, but not exactly the same as, the usual mathematical operators.

Java operators are always some combination of the following:
= > < ! ~ ? : & | + - * / ^ %

public class HairsOnHead
{
   public static void main(String[] args)
   {
      // Step 1
      int diameter = 17;

      // Step 2
      double fractionCovered = 0.5;

      // Step 3
      double areaCovered = fractionCovered * Math.PI *
                           diameter * diameter;

      // Step 4
      int density = 200;

      // Step 5
      double numberOfHairs = areaCovered * density;

      // Step 6: Print out the result
      System.out.print("The number of hairs on a human head is ");
      System.out.println(numberOfHairs);
   }
}

Literals

A value that you can write down.

Text inside quotation marks is called a string literal.

public class HairsOnHead
{
   public static void main(String[] args)
   {
      // Step 1
      int diameter = 17;

      // Step 2
      double fractionCovered = 0.5;

      // Step 3
      double areaCovered = fractionCovered * Math.PI *
                           diameter * diameter;

      // Step 4
      int density = 200;

      // Step 5
      double numberOfHairs = areaCovered * density;

      // Step 6: Print out the result
      System.out.print("The number of hairs on a human head is ");
      System.out.println(numberOfHairs);
   }
}

Separators

All of the following:
[ ] ( ) { } ; , .

Separators separate other tokens.

public class HairsOnHead
{
   public static void main(String[] args)
   {
      // Step 1
      int diameter = 17;

      // Step 2
      double fractionCovered = 0.5;

      // Step 3
      double areaCovered = fractionCovered * Math.PI *
                           diameter * diameter;

      // Step 4
      int density = 200;

      // Step 5
      double numberOfHairs = areaCovered * density;

      // Step 6: Print out the result
      System.out.print("The number of hairs on a human head is ");
      System.out.println(numberOfHairs);
   }
}

Style 1

The Java compiler does not care about how your code looks; it only cares about being able to break your code up into tokens, and that the sequence of tokens is sensible. That means the following are all legal Java programs:

public class Ugly { public static void main(String[] args)
{ System.out.println("This works!"); } }
public class UglyToo
{


public static void main  (   String[] args  )
{
System  .  out  .  println("This works!");
}
}
public/**/class/**/Ugliest{public/**/static/**/
void/**/main(String[]/**/args)
{System.out.println("This works!");}}

Style 2

Write Neat Code
Neat code with consistent style is easier to read and understand than free-form code. Learn and use the coding style rules for CSE 1020 shown in Appendix C.

A Line-by-line Explanation

Step 1: Declare a Class

In 1020, your programs will always consist of a single file. The file will define a Java class. For now, you can think of a class as being the smallest building block of a Java program.

You need to give the class a name to declare a class. The name (or identifier) should be descriptive of the problem you are trying to solve. We will use the name HairsOnHead for our solution. Type the following into jEdit:

public class HairsOnHead
{

}

Save the file with the name HairsOnHead.java in your working folder.

Step 2: Add a main Method

Every Java program starts executing in a method called main. A method is simply a group of Java statements that have been collected into one unit that can be re-used over and over again. In 1020, the only method that you will have to create is the main method; however, you will use methods that other programmers have created.

Add the main method to the HairsOnHead class as shown below:

public class HairsOnHead
{
   public static void main(String[] args)
   {

   }
}

Save the file.

Step 3: Declare a diameter Variable

Recall that our worked solution used a variable to describe the diameter of a human head. Let's assume that we're only interested in integer values for the diameter.

In Java, we must declare a variable before we can use it. Declaring a variable means specifying its type and its name. For integer numeric values we can use the type called int.

Declare a variable of type int named diameter by typing in the following code:

public class HairsOnHead
{
   public static void main(String[] args)
   {
      int diameter;
   }
}

What Does int diameter; Mean?

The statement int diameter; indicates that we want to associate the name diameter with a chunk of memory that holds an int value. A variable is the chunk of memory that is reserved for it.

A simple model of computer memory is a column of identical boxes numbered sequentially starting at zero.

0
1
  ¦
100
101
102
  ¦
500

What Does int diameter; Mean?

The statement int diameter; reserves a chunk of memory and labels the chunk with the identifier diameter.

0
1
  ¦
diameter ⇒ 100
101
102
  ¦
500

Step 4: Assign a Value to diameter

Now that we have declared a variable named diameter we need to assign it a value. Because the type of diameter is int, we can only assign it integer values.

In Java, the equals symbol = is used to assign values to a variable. The symbol = is called the assignment operator. Update your code to assign a value to diameter:

public class HairsOnHead
{
   public static void main(String[] args)
   {
      int diameter;
      diameter = 17;
   }
}

What Does diameter = 17; Mean?

The statement diameter = 17; means that you want to assign the value of 17 to the chunk of memory (the variable) with the identifier diameter.

0
1
  ¦
diameter ⇒ 100 17
101
102
  ¦
500

We say that the variable at address 100 has the type int, the name diameter, and the value 17. The Java compiler keeps track of all of this information.

Step 5: Declare and Assign a fractionCovered Variable

Now we need a variable that describes the fraction of a head that is covered by hair; this is a real-valued numeric variable. In Java, a suitable type for representing real-valued numeric quantities is called double.

If you know the value of a variable when you want to declare the variable, you can declare and assign a value to the variable in one statement. Declare and assign the value of 0.5 to a variable of type double named fractionCovered as shown below:

public class HairsOnHead
{
   public static void main(String[] args)
   {
      int diameter;
      diameter = 17;
      double fractionCovered = 0.5;
   }
}

Step 6: Declare and Assign an areaCovered Variable

We can now calculate the area of a head that is covered by hair. The calculation requires the multiplication of some variables we have already declared and assigned. We will declare a variable to hold the value of the calculated area.

In Java, multiplying variables of type int and double is done using the * symbol. Declare and assign a variable of type double named areaCovered as shown below:

public class HairsOnHead
{
   public static void main(String[] args)
   {
      int diameter;
      diameter = 17;
      double fractionCovered = 0.5;
      double areaCovered = fractionCovered * Math.PI *
                           diameter * diameter;
   }
}

Steps 7: Complete the Solution

You have now seen all of the techniques you need to complete the solution. Complete the solution as shown below:

public class HairsOnHead
{
   public static void main(String[] args)
   {
      int diameter;
      diameter = 17;
      double fractionCovered = 0.5;
      double areaCovered = fractionCovered * Math.PI *
                           diameter * diameter;
      int density = 200;
      double numberOfHairs = areaCovered * density;
   }
}

The Memory Diagram for our Solution

The complete memory diagram for our main method is shown below:

0
1
  ¦
diameter ⇒ 100 17
 ¦
fractionCovered ⇒ 104 0.5
 ¦
areaCovered ⇒ 112 ≈453.96
 ¦
linearDensity ⇒ 120 15
 ¦
areaDensity ⇒ 124 225
 ¦
numberOfHairs ⇒ 128 ≈90792.03
 
  ¦
500

Step 8: Print the Result

Our program is correct the way it is currently written, but we cannot see the answer to the problem. Java provides a way to send output to a console window. Output the answer by adding the code as shown below:

public class HairsOnHead
{
   public static void main(String[] args)
   {
      int diameter;
      diameter = 17;
      double fractionCovered = 0.5;
      double areaCovered = fractionCovered * Math.PI *
                           diameter * diameter;
      int density = 200;
      double numberOfHairs = areaCovered * density;

      System.out.print("The number of hairs on a human head is ");
      System.out.println(numberOfHairs);
   }
}

Save the file.

print and println

There is a subtle difference between
System.out.print() and System.out.println()

System.out.print("A") will print an A.

System.out.println("A") will print an A and terminates the line by printing a line separator (i.e., the next thing printed will appear on the next line).

public class PrintA
{
   public static void main(String[] args)
   {
      // 3 A's on one line
      System.out.print("A");
      System.out.print("A");
      System.out.print("A");

      // terminate the current line
      System.out.println();

      // 3 A's on 3 lines
      System.out.println("A");
      System.out.println("A");
      System.out.println("A");
   }
}

Summary

Language Elements
A Java program is made up of whitespace, comments, and tokens.

Tokens
The 5 kinds of Java tokens are keywords, identifiers, literals, operators, and separators.

Types
A type defines what values a variable can take and the operations that can be performed with the variable.

Java is strongly typed
If you create a variable then you must also declare its type.

= does not mean equals
The symbol = is the Java assignment operator. x = y means 'x gets the value of y'.

Become accustomed to drawing memory diagrams

Learn and use the coding style rules