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
Are declared using one of the following general syntax styles:
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.
Must be initialized before they are used or a compile error will result. For example, the following program will not compile:
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.
Multiple variables of the same type can be declared in a single statement but it doesn't document very well and should be avoided. For example, this program declares four byte variables and displays the values of the two that were initialized:
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);
}
}
Can be referenced only in the block in which they are defined and blocks nested within that block ("inner" blocks). This is known as the "scope" of the variable. For example, the program
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
Can only have the value true or false
Can only be assigned to boolean variables
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 = '\n';
char returnKey = '\r';
char tab = '\t';
char backspace = '\b';
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 8), 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("\n\t" + firstLine);
System.out.println("\tJava 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'
'\t'
"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
9public 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;