Chap02

Chapter Overview

  • Elementary Programming: Covering essentials of programming in Java, moving from simple program execution to solving practical problems.

Motivations

  • Building on knowledge from previous chapters:

    • Creating, compiling, and running Java programs.

  • New focus on solving practical problems programmatically:

    • Understanding Java data types, operators, expressions, input/output.

Objectives

Key Learning Outcomes

  • Writing Java programs for basic calculations.

  • Using the Scanner class for console input.

  • Utilizing identifiers for naming variables, constants, and other methods.

  • Controlling data storage with variables and constants.

  • Implementing assignment statements and expressions.

  • Exploring Java’s primitive data types:

    • byte, short, int, long, float, double, char.

  • Applying operators for numeric expressions.

  • Displaying time and using shorthand operators.

  • Understanding type casting for different value types.

  • Computing values like loan payments and monetary changes.

  • Engaging with Java documentation and programming conventions.

  • Differentiating between syntax, runtime, and logic errors; debugging techniques.

Example Program: Compute the Area of a Circle

Program Code Overview

public class ComputeArea {
  public static void main(String[] args) {
    double radius;
    double area;
    radius = 20;
    area = radius * radius * 3.14159;
    System.out.println("The area for the circle of radius " + radius + " is " + area);
  }
}

Execution Trace

  • Memory Allocation:

    • Variables (radius, area): No initial values.

  • Radius Assignment:

    • radius is assigned a value of 20.

  • Area Calculation:

    • Area computed and stored using the formula.

    • Output: "The area for the circle of radius 20 is 1256.636".

Reading Input from the Console

Steps to Use Scanner

  1. Create Scanner Object: Scanner input = new Scanner(System.in);

  2. Input Methods: Use next() options for different data types (e.g., nextInt() for integers).

    • Example: double d = input.nextDouble();

Identifiers

  • Definition: Sequence of characters (letters, digits, underscores, $).

  • Rules for Identifiers:

    • Must start with a letter, underscore, or dollar sign.

    • Cannot start with a digit.

    • Cannot be a reserved word.

    • Can be of any length.

Variables

  • Variable Declaration and Assignment:

    • Example Calculations:

      • Area calculation using different radius values (e.g., 1.0, 2.0).

Declaring Variables

  • Example Declarations:

    • int x; // integer variable

    • double radius; // double variable

    • char a; // character variable

Assignment Statements

  • Assign values to variables:

    • x = 1;

    • radius = 1.0;

    • a = 'A';

Constants

  • Definition: Values that should not change.

Numerical Data Types

  • Data Type Ranges and Sizes:

    • byte: -128 to 127 (8-bit)

    • short: -32768 to 32767 (16-bit)

    • int: -2147483648 to 2147483647 (32-bit)

    • long: -9223372036854775808 to 9223372036854775807 (64-bit)

    • float and double: Various ranges per IEEE standards.

Numeric Operators

  • Basic Operators:

    • + Addition, - Subtraction, * Multiplication, / Division, % Remainder.

Integer Division

  • Division Examples:

    • 5 / 2 yields 2 (integer).

    • 5.0 / 2 yields 2.5 (double).

Remainder Operator

  • Used for determining even/odd numbers:

    • Example: number % 2.

Floating-Point Precision

  • Important Note: Floating-point numbers may not store exact values.

    • Example: Calculation nuances with 1.0 - 0.1.

Number Literals

  • Definition: Constant values in code (e.g., 34, 5.0).

Integer Literals

  • Must fit data type limits to avoid errors (e.g., byte b = 1000;).

Floating-Point Literals

  • By default treated as double; append f for float (e.g., 5.0f).

Scientific Notation

  • Floating-point literals in scientific notation (e.g., 1.23456e+2).

Arithmetic Expressions

  • Syntax examples to evaluate: 3 + 4 * 10.

Problem: Temperature Conversion

Task

  • Convert Fahrenheit to Celsius with a formula.

Current Time Display Problem

  • Displays time in GMT using currentTimeMillis() method.

Shortcut Assignment Operators

  • Examples: i += 8 is equivalent to i = i + 8.

Increment/Decrement Operators

  • Shorter forms to modify values (e.g., ++var, var--).

Assignment Expressions

  • Allowed expressions for statements post Java 2.

Numeric Type Conversion Rules

  • Automatic type conversions during binary operations based on operand types.

Type Casting

  • Implicit (widening) and Explicit (narrowing) casting rules.

Keeping Decimal Points Program

  • Program requires precision in tax rounding.

Loan Payments Program

  • User input for calculating monthly and total payments.

Character Data Type

  • Uses char for ASCII representations; Unicode compatibility.

Unicode Format

  • Utilizes 16-bit encoding for text representation across languages.

Escape Sequences

  • Special characters denoted with escape sequences (e.g., \, ).

ASCII Character Set

  • Covering encoding in both decimal and hexadecimal indices.

Casting between char and Numeric Types

  • Example conversions between char and int.

Monetary Units Problem

  • Program converts decimal input into monetary equivalents.

String Type

  • Use String for multiple characters; reference type.

String Concatenation

  • Examples of how strings combine.

Programming Style Guidelines

Comments

  • Summarize program function and details.

Naming Conventions

  • Use meaningful names following Java conventions.

Indentation/Spacing

  • Recommend practices for readability.

Block Styles

  • Different styles for coding blocks.

Programming Errors

Types of Errors

  • Syntax: Caught by compiler.

  • Runtime: Program crashes.

  • Logic: Incorrect program outputs.

Debugging Techniques

  • Methods for identifying bugs, including print statements and debuggers.

Using JOptionPane for Input

  • Two methods for input collection from dialogs.

Input Conversion

  • Converting strings to int and double using appropriate methods.