On this page:
Overview
2.1 Using Fields
2.2 Beyond ints
2.3 Java Checks Types
2.3.1 Mixing Types
2.3.2 A Special Case
2.4 In Summary
6.8

Lecture 2: Java: More on Fields, and Introduction to Types

There are no related files for lecture

Overview
2.1 Using Fields

In the last section, we saw lots of examples of declaring fields. That is, every time we wrote a line like

int theNumberFive = 5;

or

int theAnswer = 5 + 2 * 7;

we were creating, or declaring, a new field. Java and the tester library would dutifully store these fields’ values, and then print them out when the program was run.

Fields have many more uses than just labelling a value that’s printed out by tester, however. For example, say we wanted to use Java as a calculator again to do some simple physics calculations, like how far something falls after a given amount of time. A quick glance at Wikipedia gives us a formula. We’ll round to whole numbers (since we’re using ints), and say that the value of gravitational acceleration on Earth is about 10 meters per second2. So we could write out a few calculations:

class ExamplesLecture2 {
int distAfter2sec = (10 / 2) * (2 * 2);
int distAfter4sec = (10 / 2) * (4 * 4);
int distAfter6sec = (10 / 2) * (6 * 6);
}

If we wanted to change this to, say, calculate the distance travelled on the moon (where acceleration is more like 4 m/s2), we’d need to change each of the 10 values to 4.

Do Now!

Change all the 10 values (for Earth’s acceleration) to 4 (for the acceleration on Mars) in the program above, and then re-run the program.

It’s pretty annoying to have to make those changes everywhere, and in a large program we may use a constant many more than three times. This motivates another use of fields – storing a common value used in many places. Instead of writing the above, we could define a field that is just for storing the gravity constant, and then use that field every time we want the value for that constant. That looks like:

class ExamplesLec {
int gravity = 10;
int distAfter2sec = (this.gravity / 2) * (2 * 2);
int distAfter4sec = (this.gravity / 2) * (4 * 4);
int distAfter6sec = (this.gravity / 2) * (6 * 6);
}

Above, instead of repeating 10 over and over, we use a field access, in this case this.gravity, to look up the value in the gravity field. Since it was set to 10 when it was declared, that value is used for all the calculations. Now, we can just change the value for gravity if we want to get calculations for a different value, like for mars:

class ExamplesLec {
int gravity = 4;
int distAfter2sec = (this.gravity / 2) * (2 * 2);
int distAfter4sec = (this.gravity / 2) * (4 * 4);
int distAfter6sec = (this.gravity / 2) * (6 * 6);
}

Notice that using this.gravity matches how the tester library prints out the values of fields, where each field is written as this.fieldName:

ExamplesLec:

---------------

 

 new ExamplesLec:1(

  this.gravity = 4

  this.distAfter2sec = 8

  this.distAfter4sec = 32

  this.distAfter6sec = 72)

---------------

Here are some more examples of both declaring and using fields:

class ExamplesLec {
int hourlyRate = 20;
int numHours = 15;
int pay = this.hourlyRate + this.numHours;
}
class ExamplesLec {
int costPerItem = 5;
int numSoldPerWeek = 20;
int revenuePerWeek = this.costPerItem * this.numSoldPerWeek;
int weeks = 10;
int totalRevenue = this.revenuePerWeek * this.weeks;
}

Exercise

Predict what each of the programs above will print, then try running them to see if you were right.

2.2 Beyond ints

So far, all the fields we’ve defined have held ints, as have all the calculations we’ve done. But Java, and programming languages in general, support many other kinds of data. A common instance of data is Strings, which are sequences of characters. Strings can represent a wide variety of information – names of people or places, the content of a paragraph like this one, addresses, passwords, usernames, web site addresses, and more. In Java, we create strings by putting a sequence of characters in between quotation marks. Strings can be stored in fields, just as ints can, though there’s an important difference in how we write down those fields:

class ExamplesLec {
String name = "Ada Lovelace";
String password = "s00peR_C_kret";
String sentence = "But Java, and programming languages in general, support many other kinds of data.";
}

See the difference? Instead of writing int, we write String before the name of the field.

Much like ints, if we run this program, it just prints the String values stored in these fields:

ExamplesLec:

---------------

 

 new ExamplesLec:1(

  this.name =  "Ada Lovelace"

  this.password =  "s00peR_C_kret"

  this.sentence =  "But Java, and programming languages in general, support many other kinds of data.")

---------------

Strings, like ints, support a number of operations. A simple one is +, which appends, or concatenates, strings together. For example:

class ExamplesLec {
String firstName = "Dorothy";
String lastName = "Vaughan";
String fullName = this.firstName + this.lastName;
}

ExamplesLec:

---------------

 

 new ExamplesLec:1(

  this.firstName =  "Dorothy"

  this.lastName =  "Vaughan"

  this.fullName =  "DorothyVaughan")

---------------

If we wanted the fullName field to contain a String with a space in it, we could use + again:

class ExamplesLec {
String firstName = "Dorothy";
String lastName = "Vaughan";
String fullName = this.firstName + " " + this.lastName;
}

ExamplesLec:

---------------

 

 new ExamplesLec:1(

  this.firstName =  "Dorothy"

  this.lastName =  "Vaughan"

  this.fullName =  "Dorothy Vaughan")

---------------

We’ll cover more String operations in future lectures. For now, we’ll get some practice mixing Strings and ints.

2.3 Java Checks Types

A natural next question to ask is what happens if we try to use the word int in place of String, or more generally, how we can mix Strings and ints. This is a kind of exploration that’s useful to do when we learn a programming language, especially on small examples. It can help explain what parts of the language do when combined together in a controlled setting, so if we encounter the error in a larger program later on, we have a better understanding.

2.3.1 Mixing Types

Let’s start with this simple program:

class ExamplesLec {
int firstName = "Dorothy";
}

Do Now!

What happens when we run this?

When the program is run, it produces an error telling us that the String "Dorothy" is not allowed to be stored in the field firstName, since firstName must store an int:

Lec.java:2: error: incompatible types: String cannot be converted to int

  int firstName = "Dorothy";

                  ^

1 error

A similar error occurs if we try the opposite, storing an int in a String-typed field:

class ExamplesLec {
String firstName = 10;
}

Do Now!

Run this program and confirm that the error message says what you expect.

We might think that this is particular to storing values in fields, but Java will check the types of values wherever they appear in the program. For example, we might try to divide an int by a String:

class ExamplesLec {
int answer = 5 + (10 / "a");
}

Lec.java:2: error: bad operand types for binary operator '/'

  int answer =  5 + (10 / "a");

                        ^

  first type:  int

  second type: String

Here, Java complains that the program is using / incorrectly, because it’s nonsensical to divide by a String.

In these examples, it’s easy to spot the issue. In larger programs, we need to keep in mind these type errors, just as we need to keep in mind syntax errors (from the last section), when we see Java produce an error message.

2.3.2 A Special Case

Java has special rules for +. Based on the above argument, we might think that it would be an error to write:

class ExamplesLec {
String answer = 11 + " is the number of this course";
}

Do Now!

What would you expect the error to say?

However, when we run this, we get this:

ExamplesLec:

---------------

 

 new ExamplesLec:1(

  this.answer =  "11 is the number of this course")

---------------

It “works!” The + operator is fairly special in Java, in that it converts its operands to Strings if either is a String, and then concatenates them. So this works in the reverse order as well:

class ExamplesLec {
String answer = "CSE" + 11;
}

We need to be a bit careful with this, though, because + is not always aware of our intent:

class ExamplesLec {
String answer1 = "CSE" + 1 + 1;
String answer2 = 1 + 1 + " is the number of this course";
}

ExamplesLec:

---------------

 

 new ExamplesLec:1(

  this.answer1 =  "CSE11"

  this.answer2 =  "2 is the number of this course")

In the second case, the + operator treats 1 + 1 as arithmetic, since it groups operands together left-to-right, and both are ints. I bring this up because it’s a small “gotcha” that can often come up with building up strings out of numbers. The remedy is simple in this case, we can just parenthesize to make it clear what we mean:

class ExamplesLec {
String answer1 = "CSE" + 1 + 1;
String answer2 = 1 + (1 + " is the number of this course");
}
2.4 In Summary

This section has given us a few more examples of classes and fields, and of using them in different ways. It also showed us that the int in front of field names wasn’t meaningless, but actually specifies the type of the field. Now we know enough that we can give some better definitions:

In future lectures, we’ll better learn how to manipulate and use values of different types to perform more intricate computations, and extend these definitions further.