Data types

We saw in the first lecture that when you declare a variable you have to give both a type for the variable and a variable name. Here are some examples.

int feet, inches;
double meters;
Scanner input;
String message;

Java offers two broad categories for variable types, primitive types and object types. To make it easy to tell the difference, Java programmers follow a simple naming convention: all primitive types have names that start with lower case letters, while all object types have names that start with upper case letters.

Literals

Once you have declared a variable, you then have to give that variable a value. The simplest way to do this is to initialize a variable from a literal value. Here are some examples of this.

int feet;
feet = 5; // Initialize from int literal

double meters;
meters = 1.7; // Initialize from double literal

String message;
message = "Hello, world!"; // Initialize from String literal

A common shortcut is to combine the variable declaration and the initialization in a single statement.

int feet = 5;
double meters = 1.7;
String message = "Hello, world!";

The String data type is unusual in that it is the only object data type that can be initialized with a literal. For every other object type you have to initialize the variable with a new expression, which creates a new object of the requested type.

Scanner input = new Scanner(System.in);

Type compatability rules

Since variables in Java can have different types, Java has rule that says that you can not assign a value of one type to a variable with a different type. Here are some examples that Java considers illegal:

double meters = 1.7;
int feet = meters; // Illegal: can't assign double to int
String str = meters; // Illegal: can't assign double to String

There are some exceptions to this rule. In some cases Java can perform an automatic type conversion to convert one type to another.

int feet = 5;
double meters = feet; // OK: int 5 converts to double 5.0
String str = "Value is " + meters; // OK: concatenation
// automatically converts double 5.0 to String "5.0".

Type preservation rule

Another rule that Java has related to types is the type preservation rule. This rule says that if all of the elements of an expression have a particular type, the result will automatically have that same type.

Here is an example:

int feet = 5;
int inches = 7;
int totalInches = feet*12 + inches;

The arithmetic expression in the last statement involves only int quantities, so the final result of the calculation is automatically an int, which makes the result legal to assign to an int variable.

Another rule related to the type preservation rule is the mixed expression rule. This rule says that if an expression contains a mix of both integer and floating point types, the result automatically converts to a floating point type. Here is an example:

double centimeters = totalInches * 2.54;

In the expression on the right, totalInches is an int, while the literal 2.54 is a double. This triggers the mixed expression rule, which says that the result of totalInches * 2.54 must be a double.

Integer arithmetic

Since the type preservation rule says that any arithmetic involving two integers should produce an integer result, you will have to exercise caution when using division with integers. Here is a example of how easily integer division can cause trouble.

One of the first example programs I showed in this course was a program to convert Fahrenheit degrees to Celsius degrees. Here is a version of this program which is actually incorrect, because it suffers from a subtle problem with integer division:

public class FahrenheitToCelsius {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.print("Enter a degree in Fahrenheit: ");
    double fahrenheit = input.nextDouble();

    // Convert Fahrenheit to Celsius
    double celsius = (5 / 9) * (fahrenheit - 32);
    System.out.println("Fahrenheit " + fahrenheit + " is " +
      celsius + " in Celsius");
  }

}

If you run this program with any input, it will return a result of 0 degrees Celsius! The reason this happens is that in computing the conversion Java will first compute 5 / 9: since both 5 and 9 are integers, the type preservation rule kicks in and triggers integer division. In integer division, 5/9 evaluates to 0, which in turn makes the rest of the expression evaluate to 0.

The usual remedy for integer division problems is to make sure that at least one of the two quantities involved in the division is not an integer - this will trigger the use of the mixed expression rule, which says that any arithmetic involving both an integer and a double defaults to a double result. Given this observation, there are now a couple of ways to fix the faulty conversion arithmetic in the program above. Either of the following will work, because each one of these examples will manage to trigger the mixed expression rule and thus avoid integer division:

double celsius = (5.0 / 9) * (fahrenheit - 32);
double celsius = 5 * (fahrenheit - 32) / 9;

The mod operator

The type preservation rule says that any division involving two ints must produce an int as its result. Unfortunatly, most divisions involving two ints will not want to produce an integer result: for example, 14/3 is the same as 4 2/3, which is not an integer. To force the type preservation rule to apply, Java will simply drop any fractional parts of results of divisions by rounding the result down to the nearest integer. Thus, in Java integer division says that 14/3 is 4.

To partially compensate for the loss of information caused by integer division, Java also offers a fifth arithmetic operator, %, that computes remainders. If a and b are integer variables, a%b computes the remainder upon division of a by b. For example, 14%3 is 2, because 3 divides into 14 4 times with a remainder of 2. The % operator is also known as the mod operator, and a%b is commonly read "a mod b".

14 / 3 = 4

14 % 3 = 2

The mod operator has one useful special application: it can be used to determine whether or not one number divides evenly into another number. If b divides evenly into a, then a%b will be 0.

Here is an example. To determine whether or not a given year is a leap year, we have to use the following rules.

Here is a simple sample program that determines whether or not a year the user inputs is a leap year:

public class LeapYear {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int year;

    System.out.print("Enter a year: ");
    year = input.nextInt();

    if(year%400 == 0) // If the year is divisible by 400..
      System.out.println("The year "+year+" is a leap year.");
    else if(year%100 == 0) // If the year is divisible by 100..
      System.out.println("The year "+year+" is not a leap year.");
    else if(year%4 == 0) // If the year is divisible by 4..
      System.out.println("The year "+year+" is a leap year.");
    else // All other years
      System.out.println("The year "+year+" is not a leap year.");
  }
}

First programming assignment

Write a program to solve programming exercise 2.17 from the end of chapter two.

For this program you should start by making a new project in NetBeans. To make a new project in NetBeans select New Project... from the File menu.

This brings up the New Project dialog box. NetBeans can create a wide variety of different projects, so the first step is to select an appropriate project type. Click the "Java with Ant" category in the category listing, and then click the "Java Application" project type. Click Next to move to the next dialog.

In the second dialog change the name for your project to WindChill, then click Finish to create the project.

When you are done writing the code for you program, you will send the project folder to me to be graded. To send me your work, compress the project folder into a zip archive, and then send me the archive as an attachment to an email message. (If you are having trouble finding your project folder, hold your mouse pointer over the project in the Projects pane in NetBeans. This will pop up some text that shows where the project is located on your computer. The project is the thing with the coffee cup icon next to it in the Projects pane.)

Work on this first assignment is due by 5 PM on Tuesday, September 22.

If you need help on the assignment, you are welcome to see me in office hours. My office hours run from 3:00-5:00 every day, Monday through Friday. To see me in office hours, please use the link to my Zoom personal meeting space that I emailed to you earlier.