Fundamental Data Types

Constants and Utilities

A Java class contains definitions of fields and methods. These fields and methods do not belong to the class; they belong to the objects created from the class.

Writing the word "static" in front of a field or method definition means the field or method belongs to the class, not the objects. These fields and methods can be accessed by qualifying them with the name of the class (or the name of an object).

Often constants are declared as static fields. Utilities (well known formulas that don't need an object input) are defined as static methods. For example:

public class Physics {
   // from http://www.physics.nist.gov/cuu/Constants/index.html
   public static final double G = 6.6742e-11; // gravitation
   public static final double h = 6.6260693e-34; // Planck constant
   public static final double c = 299792458.0; // speed of light
   // E = mc^2
   public static double energy(double mass) {
      return mass * c * c;
   }
   // F = Gm1m2/d^2
   public static double gravity(double m1, double m2, double dist) {
      return G * m1 * m2 / (dist * dist);
   }
}

Here is how they might be called in another program:

System.out.println("Planck's constant = " + Physics.h);
System.out.println("E = " + Physics.energy(213.48));

Numbers

Classification of Java values:

Value
   Object
   Primitive
      boolean
      char
      Number
         Exact
            byte <: short <: int <: long
         Inexact
            float <: double

The formula:

S <: T

Means that S is a subtype of T. This relationship is transitive. In other words:

S <: T <: U implies S <: U

In addition, we also have:

long <: float
char <: int

If S is a subtype of T, then values of type S can masquerade as values of type T. For example:

float x = 42; // x = 42.0

In this case the int 42 is masquerading as the float 42.0.

Values in a supertype can masquerade as values in a subtype, but this requires an explicit cast:

int y = (int)3.14; // y = 3

In this case the double 3.14 is truncated to 3 in order to be shoehorned into z.

The type of a number indicates how many bytes are used to represent it:

byte, boolean (1)
short, char (2)
int, float (4)
long, double(8)

Boxing

Pure object-oriented programming only likes to deal with objects. Every primitive value can be placed in an object wrapper. Java provides the following wrapper classes:

Boolean, Char, Byte, Short, Integer, Long, Float, Double

For example:

Integer w = 42;
System.out.println("w + 1 = " + (w + 1)); // prints 43

Note that wrappers can masquerade as primitives and vice-versa:

int <: Integer <: int

Wrapping a primitive in an object wrapper is called boxing. Removing a primitive from its wrapper us called unboxing.

In Java 1.5 and later boxing and unboxing is automatic.

The wrapper classes contain useful constants:

public class Limits {
   public static void main(String[] args) {
      System.out.println("biggest int = " + Integer.MAX_VALUE);
      // = 2^31 – 1

      System.out.println("biggest int + 1 = " +
         (Integer.MAX_VALUE + 1));

      System.out.println("biggest long = " + Long.MAX_VALUE);
      // = 2^63 - 1

      System.out.println("biggest float = " + Float.MAX_VALUE);
      // = (2 - 2^-23) * 2^127

      System.out.println("smallest positive float = " +
         Float.MIN_VALUE); // = 2^-149
      System.out.println("biggest double = " + Double.MAX_VALUE);
      // = (2 - 2^-52) * 2^1023
      System.out.println("smallest positive double = " +
         Double.MIN_VALUE); // = 2^-1074
   }
}

Here is the output produced:

biggest int = 2147483647
biggest int + 1 = -2147483648
biggest long = 9223372036854775807
biggest float = 3.4028235E38
smallest positive float = 1.4E-45
biggest double = 1.7976931348623157E308
smallest positive double = 4.9E-324

In addition, Java provides objects for representing arbitrarily large and small numbers using multiple precision arithymetic:

import java.math.*;
public class Big {

   public static void main(String[] args) {
      BigInteger num = new BigInteger("99999999999999999999");
      BigInteger one = new BigInteger("1");
      System.out.println("num + 1 = " + num.add(one));
   }
}

The output:

num + 1 = 100000000000000000000

Math

The Math class contains a number of static utility methods:

trig, exp, log, pow, floor, ceil, round, sqrt, abs, max, min

You should know all of these.

Operators

Java also provides built-in operators:

Arithmetic: +, *, -, /, %

Comparisons: <, <=, >, >=

Equality: ==, !=

Logic: &&, ||, !

Bitwise: &, |, <<, >>, >>>, ~

Assignment: =, +=, *=, etc.

pre/post increment/decrement: ++x, x++, --x, x—

Example:

public class Operators {

   public static void main(String[] args) {
      int num = 23;
      System.out.println("num++ = " + num++);
      System.out.println("num = " + num);
      System.out.println("++num = " + ++num);
      System.out.println("num = " + num);

      System.out.println("num-- = " + num--);
      System.out.println("num = " + num);
      System.out.println("--num = " + --num);
      System.out.println("num = " + num);

      num *= 2;
      System.out.println("num = " + num);
   }

}

Here's the output produced:

num++ = 23
num = 24
++num = 25
num = 25
num-- = 25
num = 24
--num = 23
num = 23
num = 46

Each operator has a precedence and associativity that help determine its execution priority. For example:

2 + 3 – 2 * 4 = (2 + 3) – (2 * 4) = 5 – 8 = -3

Use parentheses to specify the execution order of operators until you learn their precedence and associativity rules.

String Processing

Strings are objects too. They have methods for locating, extracting, and replacing substrings.

Example 1

public class PathTest {
   public static void main(String[] args) {


      String path = "C:\\cs46a\\hw\\hw1\\Test.java";


      int slashPos = path.lastIndexOf("\\");
      int dotPos = path.lastIndexOf(".");


      String fileName = path.substring(slashPos + 1, dotPos);
      fileName = fileName + ".class";
      System.out.println("file name = " + fileName);

      path = path.replace("hw1", "hw2");
      System.out.println("now path = " + path);

      path = path.replaceAll("hw", "HW");
      System.out.println("now path = " + path);

      String extension = path.substring(dotPos + 1);
      System.out.println(".java? = " + extension.equals("java"));
   }
}

Program output:

file name = Test.class
now path = C:\cs46a\hw\hw2\Test.java
now path = C:\cs46a\HW\HW2\Test.java
.java? = true

Example 2

Converting strings to numbers:

double d = new Double("3.14");
String s = "" + (d + 1);
System.out.println(s); // prints 4.1400000000000001

int i = new Integer("42");
s = "" + (i + 1);
System.out.println(s); // prints 43

 

Example 3

public class Document {
   private String text;
   private int nextPosition;
   private int wordCount;

   public Document() {
      text = "";
      nextPosition = 0;
      wordCount = 0;
   }

   public String getText() {
      return text;
   }

   public int getWordCount() {
      return wordCount;
   }

   public void addWord(String word) {
      text = text + ' ' + word;
      wordCount++;
   }

   public int find(String word) {
      nextPosition = 0;
      return findNext(word);
   }

   public int findNext(String word) {
      nextPosition = text.indexOf(" " + word + " ", nextPosition);
      return nextPosition++;
   }
}

Test Driver

public class TestDocument {

   public static void main(String[] args) {
      Document report = new Document();
      report.addWord("a");
      report.addWord("squid");
      report.addWord("eating");
      report.addWord("dough");
      report.addWord("in");
      report.addWord("a");
      report.addWord("polyehtylene");
      report.addWord("bag");
      report.addWord("is");
      report.addWord("fast");
      report.addWord("and");
      report.addWord("bulbous");
      System.out.println(report.getText());
      int pos = report.find("a");
      System.out.println("pos = " + pos);
      pos = report.findNext("a");
      System.out.println("pos = " + pos);
      pos = report.findNext("a");
      System.out.println("pos = " + pos);
      pos = report.find("squid");
      System.out.println("pos = " + pos);
   }
}

Program output:

a squid eating dough in a polyehtylene bag is fast and bulbous
pos = 0
pos = 24
pos = -1
pos = 2

Input/Output

import java.util.*;

public class TempConverter {

   private static final double FACTOR = 5.0/9.0;
   private static final double SHIFT = 32.0;

   public static void main(String[] args) {
      Scanner kbd = new Scanner(System.in);
      System.out.print("Enter temperature in degrees Fahrenheit: ");
      double fDegrees = kbd.nextDouble();
      double cDegrees = FACTOR * (fDegrees - SHIFT);
      System.out.printf("Degrees centigrade = %5.2f%n", cDegrees);
   }
}

Here's the ouput produced:

Enter temperature in degrees Fahrenheit: 98.6
Degrees centigrade = 37.00

Notes:

%5.2f%n

is a format specifier. It indicates that a floating point number (or a double) should be printed in a field of width 5 with two decimal place accuracy. %n indicates a platform-independent newline.

FACTOR and SHIFT are defined as constants to avoid magic numbers.