Skip to Content
Think Java, 2nd Edition
book

Think Java, 2nd Edition

by Allen B. Downey, Chris Mayfield
November 2019
Beginner
326 pages
6h 44m
English
O'Reilly Media, Inc.
Book available
Content preview from Think Java, 2nd Edition

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, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First Java, 2nd Edition

Head First Java, 2nd Edition

Kathy Sierra, Bert Bates
Java in a Nutshell, 8th Edition

Java in a Nutshell, 8th Edition

Benjamin J. Evans, Jason Clark, David Flanagan
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781492072492Errata PageSupplemental Content