Java Reference
In-Depth Information
A : No. You must not confuse strings with characters. A character literal represents a
single letter of type char . A string containing only one letter is still a string. Al-
though strings consist of characters, they are not the same type.
Notice how the \n escape sequence is used to generate a new line. You don't need to use
multiple println( ) statements to get multiline output. Just embed \n within a longer string
at the points where you want the new lines to occur.
A Closer Look at Variables
Variables were introduced in Chapter 1 . Here, we will take a closer look at them. As you
learned earlier, variables are declared using this form of statement,
type var-name;
where type is the data type of the variable, and var-name is its name. You can declare a
variable of any valid type, including the simple types just described, and every variable will
have a type. Thus, the capabilities of a variable are determined by its type. For example,
a variable of type boolean cannot be used to store floating-point values. Furthermore, the
type of a variable cannot change during its lifetime. An int variable cannot turn into a char
variable, for example.
All variables in Java must be declared prior to their use. This is necessary because the
compiler must know what type of data a variable contains before it can properly compile
any statement that uses the variable. It also enables Java to perform strict type checking.
Initializing a Variable
In general, you must give a variable a value prior to using it. One way to give a variable
a value is through an assignment statement, as you have already seen. Another way is by
giving it an initial value when it is declared. To do this, follow the variable's name with an
equal sign and the value being assigned. The general form of initialization is shown here:
type var = value;
Here, value is the value that is given to var when var is created. The value must be com-
patible with the specified type. Here are some examples:
Search WWH ::




Custom Search