Java Basics

Lecture 4 - 6: Types, condition; loops & arrays I, II

Types, conditions

Primitive types

  • byte: 8-bit integer in the range -128...127
  • short: 16-bit
  • int: 32-bit
  • long: 64-bit
  • double: 64-bit floating-point number
  • float: 32-bit
  • boolean
  • char

Long values are written with an L on the end: long x = 43L; float values are written with an f at the end: float f = 43.9f;

The java.lang library has more operations in

  • the Math class: x = Math.abs(y);
  • the Integer class: int x = Integer.parseInt("1084");
  • the Double class: double d = Double.parseDouble("3.14");

Boolean values can be specified directly (true, false) or be created by the comparison operators.

boolean x = 3 == 5;

A boolean and an integer are not compatible types in Java -- cannot use something like while(1){ }. (can change it to while(1 > 0){ })

Compare variables

  • == cares only about the pattern of bits in the variable.
  • Compare two references using == means it will return true if they reference the same object.
  • Use equal() method to see if two different objects are equal.

Wrapping a primitive

int i = 288;
Integer iWrap = new Integer(i);
// others: Boolean, Character, Byte, Short, Long, Float, Double

int unWrapped = iWrap.intValue(); // others: booleanValue(), charValue()

Conditionals

switch: remember break; !

Loops & arrays I

Relation between while loop and for loop:

    for (initialize; condition; next) {      |    initialize;   
      statements;                            |    while (condition) {
    }                                        |      statements;
                                             |      next;
                                             |    }

Index an array out of range will generate a run-time error.

char[] c;
c = new char[4];

Multi-Dimensional Arrays

int [][] pt = new int[n][];

for (int i = 0; i < n; i++) {
  pt[i] = new int[i+1];
}

Loops & arrays II

Automatic Array Construction

int[][] table = new int[x][y];

By using initializers

Human[] b = {amanda, rishi, new Human("Paolo")};
int[][] c = {{7, 3, 2}, {x}, {8, 5, 0, 0}};

Another subtlety of array declarations (mostly C syntax)

  int[] a, b, c;                           // a, b, and c all reference arrays.
  int a[], b, c[][];           // a is 1D; c is 2D; b is not a reference/array.
  int[] a, b[];            // a references a 1D array; b references a 2D array.

Array of Objects

For objects, Java does not construct the objects automatically.

  String[] sentence = new String[3];
  sentence[0] = "Word";
  sentence[2] = new String();

                          ---      --------------------     ---
                 sentence |.+----->|  .  | null |  .--+---->| |
                          ---      ---+----------------     --- empty String
                                      |
                                      |     --------
                                      \---->| Word |
                                            --------

Constants

final keyword

  • declare a value that can never be changed.
  • For any array x, x.length is a "final" field.
  • can also be initialized in a static initializer
public class Bar {
  public static final double PI; // mark a constant as both static and final
  static {
    PI = 3.14;
  }
}
  • A final variable means you can't change its value.
  • A final method means you can't override the method.
  • A final class means you can't extend the class (i.e. you can't make a subclass).

Aside

Signed number representation

Four ways

  • sign-and-magnitude
    • one bit to represent the sign (often the most significant bit)
    • 0: positive number or positive zero
    • 1: negative number or negative zero
    • range: $$-( 2^{n-1}-1 )$$ ~ $$2^{n-1}-1$$
  • one's complement
    • bitwise NOT - the "complement" of its positive counterpart
    • need to consider carry when adding two numbers
    • range: $$-( 2^{n-1}-1 )$$ ~ $$2^{n-1}-1$$
  • two's complement
    • Negative numbers are represented by the bit pattern which is one greater (in an unsigned sense) than the ones' complement of the positive value. // 负数的补码是在其反码的末位加1
    • 0: 00000000
    • range: $$-2^{n-1}$$ ~ $$2^{n-1}-1$$
  • excess-K (offset binary or biased representation)
    • A value is represented by the unsigned number which is K greater than the intended value.

Bit Manipulation

Bitwise operators

  • NOT: ~
  • AND: &
  • OR: |
  • XOR: ^ (turned on only if exactly one of original bits are turned on)

Shift operators

Java uses two's complement formula to store negative numbers. To change a number's sign, flip all bits, then add 1.

  • right shift: >>
    • sign bit does not change. fills the leftmost bit with original one.
  • unsigned right shift: >>>
    • The sign bit might change. It always fills the leftmost bit with zero.
  • left shift: <<
    • The sign bit might change. The rightmost bits are filled with zeros.

HFJ Reading

The enhanced for loop

for (String name: nameArray){ }
// ':' means in
// 'name' is an iteration variable

Number formatting

Several examples

String s = String.format("%, d", 1000000000); // 1,000,000,000
format("I have %.2f bugs to fix.", 476578.09876); // 476578.10

The format specifier

% [argument number][flags][width][.precision]type
// %,6.1f           ,      6      .1         f
  • type is mandatory.

    • %d decimal
    • %f float point
    • %x hexadecimal
    • %c character
  • flag includes inserting commas, putting negative numbers in parentheses, or to make the numbers left justified.

  • width defines the MINIMUM number of characters that will be used. Longer numbers will be used in full and if it's less than the width, it'll be padded with zeroes.

  • .precisions is the number of decimal places.

results matching ""

    No results matching ""