Java Reference
In-Depth Information
As you can see, the new version is more compact and does not use an if-else construct.
However, the rewrite only applies when one of two different values is assigned to the same
variable based on the validity of a condition.
2.8 Summary
The chapter presented an introduction to Java programming. Using an integrated devel-
opment environment, such as NetBeans, simplifies the development process. NetBeans not
only helps us identify compiler errors instantly, but also allows us to execute our program
line by line and monitor how the variables change (a.k.a., debug the program).
The cornerstones of any program are the variables. They can be thought as the “memory”
of the program. Throughout the execution of the program, we use variables to save important
data. Java allows us to create variables that store characters, integers, reals, and strings,
among others. Note that every type has a restriction. For example, we cannot store a number
that is bigger than three billion inside a variable of type int . Similarly, we can only store a
finite number of different real numbers inside a variable of type double and loss of precision
is common. Sometimes, the value of a variable can be supplied from the keyboard. In other
cases, the value of a variable can be the result of some computation. As we saw, we can
even assign a variable to be equal to a random number.
Managing the control flow is an important part of every program. For example, some-
times we want to branch our program based on the value of a condition. In this case, we
can use an if statement. Similarly, we can use a switch statement when we want to check
if a variable is equal to one of several values, where a switch statement can only be used
on integers, characters, and strings. A conditional operator is used when we want to assign
one of two values to a variable based on the validity of a Boolean condition.
2.9 Syntax
Declares the variable i to be an integer.
int i
￿ i=3
Assignsthevalue3tothevariable i .
￿ double d
Declares the variable d to be a double.
￿ d = 32.22
Assigns the value 32.22 to the variable d .
￿ char c
Declares the variable c to be a character.
￿ c='a'
Assigns the value
to the variable c .
￿ long l = 2342412L
Declares the variable l to be of type long and assigns the
value 2342412 to it.
￿ float f = 22432.222F
Declares the variables f to be of type float and assigns
the value 22432.222 to it.
Search WWH ::

Custom Search