Elementary Java Programming – Chapter 2 Comprehensive Notes

Objectives of Chapter

  • Master foundational skills for writing simple Java programs.
    • Write programs to perform basic computations (§2.2).
    • Obtain keyboard input with the Scanner class (§2.3).
    • Employ identifiers to name variables, constants, methods, and classes (§2.4).
    • Store data using variables (§§2.5–2.6).
    • Manipulate data with assignment statements/expressions (§2.6).
    • Preserve fixed data with constants (§2.7).
    • Follow Java naming conventions (§2.8).
    • Utilize numeric primitive types: byte, short, int, long, float, double (§2.9.1).
    • Read numeric input from keyboard (§2.9.2).
    • Apply arithmetic operators +,,×,/,+,-,\times,/,% (§2.9.3).
    • Perform exponentiation with Math.pow(a,b)Math.pow(a,b) (§2.9.4).
    • Write numeric literals, including scientific notation (§2.10).
    • Evaluate numeric expressions (§2.11).
    • Acquire current system time with System.currentTimeMillis() (§2.12).
    • Use augmented-assignment operators (§2.13).
    • Differentiate post/pre-increment/decrement (§2.14).
    • Cast values between types (§2.15).
    • Understand the software-development process via a loan-payment example (§2.16).
    • Convert large monetary amounts into smaller units (§2.17).
    • Avoid common elementary-programming pitfalls (§2.18).

Example: Computing the Area of a Circle (Listing 2.1)

  • Program: ComputeArea — calculates the area given a fixed radius.
  • Key lines (annotated):
  double radius;   // variable declaration
  double area;     // variable declaration
  radius = 20;     // assignment statement
  area = radius * radius * 3.14159; // computation
  System.out.println("The area for the circle of radius " + radius + " is " + area);
  • Execution trace (memory model):
    1. Declarations allocate memory (uninitialized).
    2. radius assigned 2020.
    3. area assigned 20×20×3.14159=1256.63620\times20\times3.14159 = 1256.636.
    4. Console displays: "The area for the circle of radius 20.0 is 1256.636".

Console Input with Scanner

  • Step 1: Create object
  Scanner input = new Scanner(System.in);
  • Step 2: Retrieve value e.g. double d = input.nextDouble();
  • Supported numeric reads:
    nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble().

Identifiers

  • Composition: letters, digits, underscore _, dollar $.
  • Must start with letter, _, or $; NOT a digit.
  • Cannot be reserved words or literals true, false, null.
  • Unlimited length.

Variables & Declarations

  • General syntax: datatype variableName;
    • Examples: int x;, double radius;, char a;.
  • Initialization styles:
  x = 1;
  double radius = 1.0;
  char a = 'A';

Assignment Statements & Expressions

  • Simple assignment: variable = expression;
  • Can combine declaration + initialization in one step.
  • Augmented form (§2.13): x op= y; (equivalent to x = (type)x op y;).

Constants (Named Constants)

  • Declared with final:
  final double PI = 3.14159;
  final int SIZE = 3;
  • Value cannot change after initialization.

Naming Conventions

  • Variables/Methods: lower-case first word, camelCase thereafter (radius, computeArea).
  • Classes: Capitalize each word (ComputeArea).
  • Constants: ALLCAPSWITH_UNDERSCORES (MAX_VALUE).
  • Rule of thumb: choose descriptive names.

Numeric Primitive Types

  • Signed integer types:
    byte (8-bit) [128,127][-128,127]
    short (16-bit) [32768,32767][-32768,32767]
    int (32-bit) [231,2311][-2^{31},2^{31}-1]
    long (64-bit) [263,2631][-2^{63},2^{63}-1]
  • Floating-point types (IEEE 754):
    float 32-bit (≈ ±3.4×1038\pm3.4\times10^{38}±1.4×1045\pm1.4\times10^{-45})
    double 64-bit (≈ ±1.8×10308\pm1.8\times10^{308}±4.9×10324\pm4.9\times10^{-324})

Numeric Operators

  • Addition +, Subtraction -, Multiplication *, Division /, Remainder %.
  • Integer division truncates: 5/2=25/2=2.
  • Mixing with double promotes result: 5.0/2=2.55.0/2 = 2.5.
  • Remainder use-cases: even/odd test, calendar calculations e.g. (6+10)%7=2    Tuesday(6+10)\%7=2\;\Rightarrow\;\text{Tuesday}.
  • Floating-point arithmetic is approximate: e.g. 1.00.9=0.099999999999999981.0-0.9 = 0.09999999999999998.

Exponentiation

  • Use Math.pow(a,b).
    • Examples: Math.pow(2,3)8.08.0, Math.pow(2.5,-2)0.160.16.

Literals

  • Integer literals default to int; append L for long (e.g., 12345678901L).
  • Floating-point literals default to double; append F for float, D optional for double.
  • Scientific notation: 1.23456e+2123.456123.456, 1.23456e-20.01234560.0123456.
  • double holds ~16 decimal digits; float ~7.

Arithmetic Expressions & Evaluation Order

  • Java follows standard precedence; parentheses override.
  • Example evaluation:
    3+44+5(4+3)1=533 + 4 * 4 + 5 * (4 + 3) - 1 = 53 (detailed six-step order illustrated).
  • Translation of complex formula: (3+4*x)/5 - 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y).

Practical Programming Exercises

  • Fahrenheit → Celsius
    • Formula: celsius=59(fahrenheit32)celsius = \frac{5}{9}(fahrenheit - 32).
    • In code: celsius = (5.0 / 9) * (fahrenheit - 32); (force floating arithmetic).
  • Display Current GMT Time
    • Steps: obtain System.currentTimeMillis(), convert to seconds, minutes, hours (mod 60,60,2460,60,24).
    • Epoch reference: 00:00:00 GMT, 1 Jan 1970.
  • Display Sales Tax with Two Decimal Places (§2.16 example): use System.out.printf("%.2f", tax); or casting/math.
  • ComputeChange (monetary units): decompose amount into dollars, quarters, dimes, nickels, pennies via successive division and remainder.

Augmented Assignment Operators (§2.13)

  • +=, -=, *=, /=, %=.
  • Equivalent expansion performs implicit cast to variable’s type.
    • Example: int sum=0; sum+=4.5;sum = (int)(sum + 4.5);sum == 4.

Increment / Decrement (§2.14)

  • Postfix (i++, i--) returns old value, then updates.
  • Prefix (++i, --i) updates first, returns new value.
  • Sample transformations:
  int i = 10;
  int newNum = 10 * i++;   // uses old i (10), then i becomes 11
  int newNum = 10 * (++i); // i becomes 11, then used
  • Guideline: avoid in overly complex expressions (int k = ++i + i;).

Assignment Expressions vs. Statements (§2.18)

  • Since Java 2, only specific expression forms qualify as standalone statements: augmented assignments & unary ++/--.

Numeric Type Conversion (§2.15)

  • Automatic promotion rules for binary ops:
    1. If either operand is double ⇒ both become double.
    2. Else if float present ⇒ both float.
    3. Else if long present ⇒ both long.
    4. Else ⇒ both int.
  • Example chain:
  byte i = 100;             // 100 promoted to int in expression
  long k = i * 3 + 4;       // result promoted to long
  double d = i * 3.1 + k/2; // entire result promoted to double
  • Casting
    • Implicit (widening): double d = 3; (int→double).
    • Explicit (narrowing): int i = (int)3.9; (fraction truncated ⇒ 3).
    • Illegal without cast: int x = 5 / 2.0; (requires (int)(5 / 2.0) or double x).

Formatting to Two Decimal Places

  • Multiply, cast, divide strategy: value = (int)(value * 100) / 100.0;.
  • Or use System.out.printf("%.2f", value);.

Common Errors & Pitfalls (§2.18)

  • Error 1: Undeclared/Uninitialized or misspelled variables (interestrate vs. interestRate).
  • Error 2: Integer overflow: int value = 2147483647 + 1; ⇒ wrap-around to 2147483648-2147483648.
  • Error 3: Floating round-off — demonstrable via 1.0-0.1*5.
  • Error 4: Unintended integer division:
    • (number1 + number2) / 2 yields 1 not 1.5.
    • Fix: divide by 2.0 or cast.
  • Error 5: Redundant Scanner objects — create one per System.in to avoid resource leaks.

Software-Development Reminder (§2.16)

  • Follow five phases: requirements → design → implementation → testing → maintenance.
  • The loan-payment example in text illustrates iterative refinement and modular testing.