|
|
|
1000 Java Tips ebook
|
|
 

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java
programming articles and tips. Please take your copy here.
Take your copy of free "Java Technology Screensaver"!. |
|
The Java Lesson 4: Variables, constants, and literals
|
JavaFAQ Home » Java Lessons by Jon Huhtala

The Java Lesson 4
Variables, constants, and literals
Variables
-
Data areas that may take on
different values during processing
-
"Automatic" or "method local"
variables are part of a method or nested statement block
-
"Member" or "class" variables
are part of a class but not part of a method or nested statement block. They
will be covered later.
"Automatic" or "method local" variables
data-type identifier; data-type identifier =
literal; data-type
identifier = expression;
Example: This program defines
three integer variables of different sizes. Two of the variables are assigned
values which are displayed by using the println() method.
public class App { public static void
main(String[] args) { byte x;
short y = 4; int z = y + 1;
System.out.println("y is " + y); System.out.println("z
is " + z); } }
Note: When the plus sign
(+) is coded following
a string, it means concatenation. In each of the println() method calls of this sample, the value
of the variable is automatically converted to a string and appended to the
end of the string to be displayed.
public class App { public static void
main(String[] args) { int x; int
y = x - 6; System.out.println("y has a value of " +
y); } }
The expression x - 6 can not be calculated
because x has no value.
public class App { public static void
main(String[] args) { byte a, b = -7, c = 5,
d; System.out.println("b = " +
b); System.out.println("c = " + c);
} }
Notice how much easier it is to
see the declaration of each variable in the following equivalent example:
public class App { public static void
main(String[] args) { byte a;
byte b = -7; byte c = 5; byte
d; System.out.println("b = " +
b); System.out.println("c = " + c);
} }
public class App { public static void
main(String[] args) { int x =
17; {
System.out.println("x = " + x); }
} }
will compile and run because
variable x is known
within the inner block. The following program, however, will not compile:
public class App { public static void
main(String[] args) {
{ int x = 17;
} System.out.println("x = " + x);
} }
The variable x is not "in scope" in the
outer block.
-
Are automatically deleted
("garbage collected") when processing jumps to an outer block of code. The
memory space they occupied is made available for other uses. In the previous
program, the variable x
would no longer exist when the println() method is to be called. That is the reason for the
compile error.
Literals
-
Are constants having no
identifier
-
Have their value specified
within the program's source code
-
Can only appear on the right
side of an assignment operator ( = ) or within an expression
-
Have a data type associated
with them
boolean literals
Example: This program declares
and initializes two boolean variables, then displays their values.
public class App { public static void
main(String[] args) { boolean isToday =
true; boolean isTomorrow =
false; System.out.println("Is it today? " +
isToday); System.out.println("Is it tomorrow? " +
isTomorrow); } }
char literals
-
Represent a single Unicode
character (16 bits)
-
Must be enclosed within single
quotes (apostrophes)
-
Are often associated with a
single key stroke
-
Can represent special
characters ("escape sequences") used for device control
Example: This program
declares a number of char
variables then displays the values of a few of them.
public class App { public static void
main(String[] args) {
// Some char literals for
keys found on the standard keyboard
char
lowerCaseA = 'a'; char upperCaseA =
'A'; char digit3 = '3'; char
space = ' ';
// "Escape" sequences for denoting
special characters
char newLine =
'
'; char returnKey = '
';
char tab = ' '; char backspace =
''; char formfeed = 'f'; char
singleQuote = '''; char doubleQuote =
'"'; char backslash = '';
// Hexadecimal, Unicode value for the Yen currency
symbol
char yenSymbol =
'u00a5';
// Display the values of some of the
variables declared above.
System.out.println("Selected values: " + digit3 + newLine + tab
+
backslash + space + yenSymbol);
} }
Integer literals
-
Represent an integer value
-
Can be expressed in decimal
(the default), octal (base , or hexadecimal (base 16)
-
Are not enclosed in any special
characters
-
Are automatically int (32 bits) unless the suffix
'L' is appended to make
it long (64 bits)
Example: This program
declares and initializes several integer variables and displays some of their
values.
public class App { public static void
main(String[] args) {
// The decimal
value 28 expressed as a decimal literal
byte x =
28;
// The decimal value 28 expressed as an octal
literal. The value // must begin with "0" and the
digits must be in the range 0 to 7.
byte xAsOctal
= 034;
// The decimal value 28 expressed as a
hexadecimal literal. The value // must begin with "0x"
and the digits must be in the range 0 to F. // Upper
and lower case letters are accepted.
byte xAsHex_1
= 0x1c; byte xAsHex_2 = 0x1C;
byte xAsHex_3 = 0X1c; byte xAsHex_4 =
0X1C;
// Decimal value 123456789 as a long
literal
long bigOldUselessNumber = 123456789L;
// Display some of the values
System.out.println(x);
System.out.println(xAsOctal);
System.out.println(xAsHex_3);
System.out.println(bigOldUselessNumber);
} }
Floating-point
literals
-
Represent a real number (having
a decimal point)
-
Can be expressed as a standard
decimal value or in scientific notation
-
Are not enclosed in any special
characters
-
Are automatically double (64 bits) unless the
suffix 'F' is appended to
make it float (32 bits)
Example: This program
declares and initializes several floating-point variables and displays some of
their values.
public class App { public static void
main(String[] args) {
// Some double literals in
both standard and scientific notation
double
amount = 1234.56; double amountInScientificNotation =
1.23456e+3; double tiny =
.0000123; double tinyInScientificNotation =
1.23e-5;
// For a literal to be float, "F" or "f"
must be appended
float value =
567.89F; float valueInScientificNotation =
5.6789e+2F;
// Display some of the
values
System.out.println(amount);
System.out.println(amountInScientificNotation);
System.out.println(tiny);
System.out.println(tinyInScientificNotation);
System.out.println(value); } }
String literals
-
Represent a string of
characters, such as "Java is fun"
-
Must be enclosed in double
quotes
-
Are automatically stored as
String class objects by
the compiler. They will be covered later.
Example: This program
contains three string literals (look for the double quotes).
public class App { public static void
main(String[] args) {
// Declare a String object
and initialize it.
String firstLine = "At Ferris
State University,";
// Display the string after
advancing to a new line and tabbing. // Then, display
another string
System.out.println("
" +
firstLine); System.out.println(" Java is
fun!"); } }
Constants
-
Are similar to variables but,
once initialized, their contents may NOT be changed
-
Are declared with the keyword
final
-
By convention, have all capital
letters in their identifier. This makes them easier to see within the code.
Example 1: This program
defines a number of constants and then displays some of their values.
public class App { public static void
main(String[] args) {
final boolean YES =
true; final char DEPOSIT_CODE =
'D'; final byte INCHES_PER_FOOT =
12; final int FEET_PER_MILE =
5280; final float PI = 3.14F;
final double SALES_TAX_RATE = .06; final String
ADDRESS = "119 South Street";
// Display some of the
values
System.out.println(INCHES_PER_FOOT);
System.out.println(ADDRESS); } }
Example 2: This program will
not compile because an attempt is made to change the value of its
constant.
public class App { public static void
main(String[] args) {
final double SALES_TAX_RATE = .06; SALES_TAX_RATE =
.04;
// Display the sales tax
rate
System.out.println(SALES_TAX_RATE);
} }
Review questions
-
Which of the following
variable declarations will compile successfully? (choose three)
-
float cost = 12.75;
-
double temperature = -1.72604e+7;
-
char dollar = "$";
-
short quantity = 0x1f;
-
boolean OK;
-
Which of these literals are
16 bits in size? (choose two)
-
2.5F
-
'u029A'
-
' '
-
"b"
-
0123
-
What will happen if an
attempt is made to compile and execute the following code? You may assume the
statements are within a valid application class and that the line numbers are
for reference purposes only.
1 2 3 4 5 6 7 8 9 |
public
static void main(String[] args) { String x =
"abc"; { String y =
"def"; System.out.println(x);
}
System.out.println(y); } |
-
the program will compile
and run to display two lines of output
-
the program will compile
and run to display one line of output
-
the program will compile
but an error will occur at run time
-
a compile error will occur
at line 6
-
a compile error will occur
at line 8
-
Which of these statements
follows Java programming conventions to properly define a short constant having a decimal value of
23? (choose two)
-
short smallNumber = 23;
-
final short littleNumber = 23;
-
final short TINY_NUMBER = 23D;
-
final short ITTY_BITTY_NUMBER = 0x17;
-
final short PETITE_NUMBER = 027; Printer Friendly Page
Send to a Friend
..
Search here again if you need more info!
|
|
|