Java Reference
In-Depth Information
Chapter 2
Programs, Data, Variables, and Calculation
WHAT YOU WILL LEARN IN THIS CHAPTER:
• How to declare and define variables of the basic integer and floating-point types
• How to write an assignment statement
• How integer and floating-point expressions are evaluated
• How to output data from a console program
• How mixed integer and floating-point expressions are evaluated
• What casting is and when you must use it
• What boolean variables are
• What determines the sequence in which operators in an expression are executed
• How to include comments in your programs
In this chapter you look at the entities in Java that are not objects — numbers and characters. This gives you
all the elements of the language you need to perform numerical calculations, and you apply these in a few
working examples.
DATA AND VARIABLES
A variable is a named piece of memory that you use to store information in your Java program — an item of
data of some description. Each named piece of memory that you define can only store data of one particular
type. If you define a variable to store integers, for example, you can't use it to store a value that is a decimal
fraction, such as 0.75. If you've defined a variable that you use to refer to a Hat object, you can only use it
to reference an object of type Hat (or any of its subclasses, as you will see in Chapter 6). Because the type
of data that each variable can store is fixed, the compiler can verify that each variable you define in your
program is not used in a manner or a context that is inappropriate to its type. If a method in your program is
supposed to process integers, the compiler is able to detect when you inadvertently try to use the method with
some other kind of data, for example, a string or a numerical value that is not integral.
Explicit data values that appear in your program are called literals . Each literal is also of a particular type:
25, for example, is an integer literal of type int . I will go into the characteristics of the various types of liter-
als that you can use as I discuss each variable type.
Before you can use a variable you must specify its name and type in a declaration statement. First consider
what flexibility you have in choosing a name for a variable.
Search WWH ::




Custom Search