Chapter 9. Immutable Objects

Java is an object-oriented language, which means that it uses objects to (1) represent data and (2) provide methods related to them. This way of organizing programs is a powerful design concept, and we will introduce it gradually throughout the remainder of the book.

An object is a collection of data that provides a set of methods. For example, Scanner, which you saw in “The Scanner Class”, is an object that provides methods for parsing input. System.out and System.in are also objects.

Strings are objects too. They contain characters and provide methods for manipulating character data. Other data types, like Integer, contain numbers and provide methods for manipulating number data. We will explore some of these methods in this chapter.

Primitives Versus Objects

Not everything in Java is an object: int, double, char, and boolean are primitive types. When you declare a variable with a primitive type, Java reserves a small amount of memory to store its value. Figure 9-1 shows how the following values are stored in memory:

int number = -2;
char symbol = '!';
Figure 9-1. Memory diagram of two primitive variables

As you learned in “Accessing Elements”, an array variable stores a reference to an array. For example, the following line declares a variable named array and creates an array of three characters:

    char[] array = {'c', 'a', 't'};

Figure 9-2 shows them both, ...

Get Think Java, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.