Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

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 Go to all tips in Java Lessons by Jon Huhtala


Bookmark and Share
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

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

  • 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 = ' ';
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 Cool, 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

  1. Which of the following variable declarations will compile successfully? (choose three)

  1. float cost = 12.75;

  2. double temperature = -1.72604e+7;

  3. char dollar = "$";

  4. short quantity = 0x1f;

  5. boolean OK;

  1. Which of these literals are 16 bits in size? (choose two)

  1. 2.5F

  2. 'u029A'

  3. ' '

  4. "b"

  5. 0123

  1. 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);
}
  1. the program will compile and run to display two lines of output

  2. the program will compile and run to display one line of output

  3. the program will compile but an error will occur at run time

  4. a compile error will occur at line 6

  5. a compile error will occur at line 8

  1. Which of these statements follows Java programming conventions to properly define a short constant having a decimal value of 23? (choose two)

  1. short smallNumber = 23;

  2. final short littleNumber = 23;

  3. final short TINY_NUMBER = 23D;

  4. final short ITTY_BITTY_NUMBER = 0x17;

  5. final short PETITE_NUMBER = 027;


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy