Google
 

 

up previous next contents
Up: 2. Day 2: The Previous: 2.2 First Steps with Next: 2.4 Arrays   Contents

Subsections

2.3 Variables, constants, and keywords

2.3.1 Primitive data types

  • Java has built-in "primitive" data types.
  • These primitives support integer, floating-point, boolean, and character values.
  • The primitive data types of Java are:

boolean either true or false
char 16-bit Unicode 1.1 character
byte 8-bit integer (signed)
short 16-bit integer (signed)
int 32-bit integer (signed)
long 64-bit integer (signed)
float 32-bit floating-point
double 64-bit floating-point

  • Samples:
      int i = 1;
      int age = 38;
      float balance = 1590.55;
      char a = 'a';
      boolean isTrue = true;
    

2.3.2 Literals

  • A literal is a vlue that can be assigned to a primitive or string variable, or passed as an argument to a method call.

2.3.2.1 boolean literals

  • true
  • false
  • boolean isTrue = true;

2.3.2.2 char literals

  • 'n' - newline
  • 'r' - return
  • 't' - tab

2.3.2.3 Floating-point literals

  • Expresses a floating-point numerical value.
  • 3.1438 - a decimal point
  • 4.33E+11 - E or e; scientific notation
  • 1.282F - F or f; 32-bit float
  • 1355D - D or d; 64-bit double

2.3.2.4 String literals

  • A sequence of text enclosed in double quotes.
  • String fourScore = "Four score and seven years ago";

2.3.3 Constants

  • Constants are variables whose value does not change during the life of the object.
  • Java does not have a constant keyword.
  • In Java you define a constant like this:
      static final String name = "John Jones";
      static final float pi = 3.14159;
    

2.3.4 Reserved keywords

  • Reserved Java keywords:

abstract default if private throw
boolean do implements protected throws
break double import public transient
byte else instanceof return try
case extends int short void
catch final interface static volatile
char finally long super while
class float native switch  
const for new synchronized  
continue goto package this  

Fibonnaci program

  • Here is a Fibonnaci program from The Java Programming Language:
    class Fibonacci {
       public static void main (String args[])
       {
          int lo = 1;
          int hi = 1;
          System.out.println(lo);
          while ( hi < 50 )
          {
             System.out.println(hi);
             hi = lo + hi;
             lo = hi - lo;
          }
      }
    }
    
  • Type this code into the proper filename.
  • Compile and run the program.
  • Discuss the results.