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 2. Variables and Operators

This chapter describes how to write statements using variables, which store values like numbers and words, and operators, which are symbols that perform a computation. We also explain three kinds of programming errors and offer additional debugging advice.

To run the examples in this chapter, you will need to create a new Java class with a main method (see “The Hello World Program”). Throughout the book, we often omit class and method definitions to keep the examples concise.

Declaring Variables

One of the most powerful features of a programming language is the ability to define and manipulate variables. A variable is a named location in memory that stores a value. Values may be numbers, text, images, sounds, and other types of data. To store a value, you first have to declare a variable:

String message;

This statement is called a declaration, because it declares that the variable message has the type String. Each variable has a type that determines what kind of values it can store. For example, the int type can store integers like 1 and -5, and the char type can store characters like 'A' and 'z'.

Some types begin with a capital letter and some with lowercase. You will learn the significance of this distinction later, but for now you should take care to get it right. There is no such type as Int or string.

To declare an integer variable named x, you simply type this:

int x;

Note that x is an arbitrary name for the variable. In general, you should ...

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