Back

Activity 1.8 Intermediate Data Types and Operations

divider

Introduction

Activity 1.8

Intermediate Data Types and Operations

Topics

  • Escape Sequences
  • Constants
  • Type Casting
  • Compound Assignment Operators
  • Increment and Decrement Operators
  • The Math Class

Escape Sequences

An escape sequence is a special combination of characters that tells a computer to do something other than what those characters normally do.

In Java, an escape sequence starts with a backslash (\) followed by another character.

For example, the sequence \n doesn't print a backslash and the letter 'n'. Instead, the backslash "escapes" the usual meaning of the 'n' and tells the program to insert a new line.

Escape Sequences

  • \n Newline
  • \\ Backslash literal
  • \" Double-Quote literal
  • \t Tab
  • \' Single-Quote literal

Constants

A constant is a variable whose value, once assigned, cannot be changed. It's used to store data that should remain the same throughout a program's execution.

Constants

You define a constant using the final keyword. The convention is to name constants using all uppercase letters, with words separated by underscores.

final double TAX_RATE = 0.08;
...
double total = subtotal * TAX_RATE;

Why Use Constants

Readability: Using a descriptive name like PI or MAX_CONNECTIONS is much clearer than using a "magic number" like 3.14159 or 100.

Preventing Errors: Since the value can't be changed after initialization, you're protected from accidentally overwriting it later in your code.

Type Casting

The process of explicitly converting a value from one data type to another. For the AP Computer Science A exam, this involves:

Narrowing (double -> int)
This truncates (cuts off) any decimal portion of the number.
Widening (int -> double)
This is often done to ensure that a calculation (especially division) produces a decimal result rather than an integer.

Type Casting

Narrowing
double myDouble = 7.99;
int myInt = (int) myDouble; // myInt becomes 7
Widening
int a = 5;
int b = 2;
double result = (double) a / b; // The cast ensures floating-point division
// The expression is evaluated as 5.0 / 2, and the result is 2.5

Compound Assignment Operators

Compound assignment operators provide a concise way to perform an operation on a variable and then assign the new value back to that same variable.

+= -= *= /= %=
Addition Assignment: x = x + 5 -> x += 5
Subtraction Assignment: x = x - 5 -> x -= 5
Multiplication Assignment: y = y * 2 -> y *= 2
Divison Assignment: y = y / 2 -> y /= 2
Modulus Assignment: y = y % 2 -> y %= 2

Increment and Decrement Operators

The increment (++) and decrement (--) operators are a shorthand way to add or subtract 1 from a variable. These are frequently used in loops and counters. There are two forms for each operator: prefix form and postfix form.

Increment and Decrement Operators

Prefix Form

Prefix Form (++x or --x): The operator comes before the variable. The value is incremented or decremented first, and then the new value is used in the expression.

int x = 5;
int y = ++x; // Prefix increment
// x is incremented to 6, then assigned to y. Both x and y are now 6.

Increment and Decrement Operators

Postfix Form

Postfix Form (x++ or x--): The operator comes after the variable. The original value is used in the expression first, and then the value is incremented or decremented.

int a = 5;
int b = a++; // Postfix increment
// a's original value (5) is assigned to b. Then, a is incremented to 6. a is 6, b is 5.
int x = 5;
x++; // x is simply incremented to the value 6.

The Math Class

The Math class contains a collection of methods and constants for performing common mathematical operations.

Constants:
Math.PI
Represents the mathematical constant PI (Ď€), approximately 3.14159.
Math.E
Represents the base of the natural logarithm (e), approximately 2.718.

The Math Class

Methods:
Math.abs(num)
Returns the absolute value of num. Example: Math.abs(-10) returns 10.
Math.pow(base, exp)
Returns the value of the base raised to the power of the exp. Example: Math.pow(2, 3) returns 8.0. The return type is a double.

The Math Class

Math.sqrt(num)
Returns the positive square root of num. Example: Math.sqrt(25) returns 5.0. The return type is a double.
Math.min(num1, num2) and Math.max(num1, num2)
Returns the smaller or larger of the two values. Example: Math.min(5, 8) returns 5.

The Math Class

Math.random()
Returns a random double value greater than or equal to 0.0 and less than 1.0 (~0.9999).
Example: (int)(Math.random() * 10) + 1 returns a random integer between 1 and 10 (inclusive).

The Math Class

Math.round(num)
Returns the closest long to the argument. This is used to round a decimal number to the nearest whole number.
Example: Math.round(7.6) returns 8.

'F' → Fullscreen

Objectives

  • icon Practice implementing various Java constructs:
    • icon Escape sequences
    • icon Constants
    • icon Type casting
    • icon Compound assignment operations
    • icon Increment and decrement operations
    • icon Math constants and methods
divider

Activity Tasks

  • icon Create a new project named 1-8-Intermediate-Data-Operations.
  • icon Complete each task individually.

Task 1: Increment, Decrement, and Compound Assignment

Program.java
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
// Scanner is only being used to pause between demos.
Scanner input = new Scanner(System.in);
System.out.println("--- Task 1: Increment, Decrement, and Compound Assignment ---");
int score = 10;
System.out.println("Initial score: " + score);
// Compound assignment
score += 5;
System.out.println("Score after += 5: " + score);
// Increment operator
score++;
System.out.println("Score after ++: " + score);
// Decrement operator
score--;
System.out.println("Score after --: " + score);
System.out.print("\nPress enter to continue...");
input.nextLine();
//
}
}

Task 2: Type Casting

Program.java
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
// Scanner is only being used to pause between demos.
Scanner input = new Scanner(System.in);
System.out.println("--- Task 1: Increment, Decrement, and Compound Assignment ---");
int score = 10;
System.out.println("Initial score: " + score);
// Compound assignment
score += 5;
System.out.println("Score after += 5: " + score);
// Increment operator
score++;
System.out.println("Score after ++: " + score);
// Decrement operator
score--;
System.out.println("Score after --: " + score);
System.out.print("\nPress enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("--- Task 2: Type Casting ---");
double price = 29.99;
System.out.println("Original price (double): " + price);
// Narrowing conversion (double to int)
int intPrice = (int) price;
System.out.println("Price after casting to int: " + intPrice);
int items = 3;
// Explicit casting for accurate division
double average = (double) intPrice / items;
System.out.println("Average price with explicit casting: " + average);
System.out.print("\nPress enter to continue...");
input.nextLine();
//
}
}

Task 3: The Math Class and Constants

Program.java
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
// Scanner is only being used to pause between demos.
Scanner input = new Scanner(System.in);
System.out.println("--- Task 1: Increment, Decrement, and Compound Assignment ---");
int score = 10;
System.out.println("Initial score: " + score);
// Compound assignment
score += 5;
System.out.println("Score after += 5: " + score);
// Increment operator
score++;
System.out.println("Score after ++: " + score);
// Decrement operator
score--;
System.out.println("Score after --: " + score);
System.out.print("\nPress enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("--- Task 2: Type Casting ---");
double price = 29.99;
System.out.println("Original price (double): " + price);
// Narrowing conversion (double to int)
int intPrice = (int) price;
System.out.println("Price after casting to int: " + intPrice);
int items = 3;
// Explicit casting for accurate division
double average = (double) intPrice / items;
System.out.println("Average price with explicit casting: " + average);
System.out.print("\nPress enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("--- Task 3: The Math Class and Constants ---");
// Constant declaration
final double PI = 3.14159;
int radius = 5;
// Calculate area using Math.pow()
double area = PI * Math.pow(radius, 2);
System.out.println("Area of circle with radius " + radius + ": " + area);
// Generate a random dice roll (1-6)
int diceRoll = (int) (Math.random() * 6) + 1;
System.out.println("Random dice roll: " + diceRoll);
System.out.print("\nPress enter to continue...");
input.nextLine();
//
}
}

Task 4: Escape Sequences

Program.java
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
// Scanner is only being used to pause between demos.
Scanner input = new Scanner(System.in);
System.out.println("--- Task 1: Increment, Decrement, and Compound Assignment ---");
int score = 10;
System.out.println("Initial score: " + score);
// Compound assignment
score += 5;
System.out.println("Score after += 5: " + score);
// Increment operator
score++;
System.out.println("Score after ++: " + score);
// Decrement operator
score--;
System.out.println("Score after --: " + score);
System.out.print("\nPress enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("--- Task 2: Type Casting ---");
double price = 29.99;
System.out.println("Original price (double): " + price);
// Narrowing conversion (double to int)
int intPrice = (int) price;
System.out.println("Price after casting to int: " + intPrice);
int items = 3;
// Explicit casting for accurate division
double average = (double) intPrice / items;
System.out.println("Average price with explicit casting: " + average);
System.out.print("\nPress enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("--- Task 3: The Math Class and Constants ---");
// Constant declaration
final double PI = 3.14159;
int radius = 5;
// Calculate area using Math.pow()
double area = PI * Math.pow(radius, 2);
System.out.println("Area of circle with radius " + radius + ": " + area);
// Generate a random dice roll (1-6)
int diceRoll = (int) (Math.random() * 6) + 1;
System.out.println("Random dice roll: " + diceRoll);
System.out.print("\nPress enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("--- Task 4: Escape Characters ---");
// Using tab (\t) for formatting
String table = "Item\t\tPrice\nKeyboard\t$75\nMouse\t\t$25";
System.out.println(table);
// Using newline (\n) and quotes (\")
String message = "He said, \"Hello, world!\"\nAnd the program responded, 'Hi.'";
System.out.println(message);
System.out.print("\nPress enter to continue...");
input.nextLine();
//
}
}

Task 5: Combining Concepts

Program.java
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
// Scanner is only being used to pause between demos.
Scanner input = new Scanner(System.in);
System.out.println("--- Task 1: Increment, Decrement, and Compound Assignment ---");
int score = 10;
System.out.println("Initial score: " + score);
// Compound assignment
score += 5;
System.out.println("Score after += 5: " + score);
// Increment operator
score++;
System.out.println("Score after ++: " + score);
// Decrement operator
score--;
System.out.println("Score after --: " + score);
System.out.print("\nPress enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("--- Task 2: Type Casting ---");
double price = 29.99;
System.out.println("Original price (double): " + price);
// Narrowing conversion (double to int)
int intPrice = (int) price;
System.out.println("Price after casting to int: " + intPrice);
int items = 3;
// Explicit casting for accurate division
double average = (double) intPrice / items;
System.out.println("Average price with explicit casting: " + average);
System.out.print("\nPress enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("--- Task 3: The Math Class and Constants ---");
// Constant declaration
final double PI = 3.14159;
int radius = 5;
// Calculate area using Math.pow()
double area = PI * Math.pow(radius, 2);
System.out.println("Area of circle with radius " + radius + ": " + area);
// Generate a random dice roll (1-6)
int diceRoll = (int) (Math.random() * 6) + 1;
System.out.println("Random dice roll: " + diceRoll);
System.out.print("\nPress enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("--- Task 4: Escape Characters ---");
// Using tab (\t) for formatting
String table = "Item\t\tPrice\nKeyboard\t$75\nMouse\t\t$25";
System.out.println(table);
// Using newline (\n) and quotes (\")
String message = "He said, \"Hello, world!\"\nAnd the program responded, 'Hi.'";
System.out.println(message);
System.out.print("\nPress enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("--- Task 5: Challenge Task (Combining Concepts) ---");
int totalStudents = 15;
final double GRADE_INCREASE = 1.05;
double newGrade = 80;
// Compound assignment with a constant
newGrade *= GRADE_INCREASE;
// Round the grade using Math.round()
long roundedGrade = Math.round(newGrade);
// Print a final, formatted message that includes all variables
String finalMessage = "Out of " + totalStudents + " students, the new rounded grade is: " + roundedGrade + ".\n\tThis is a " + (GRADE_INCREASE - 1) * 100 + "% increase.";
System.out.println(finalMessage);
//
}
}
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
--- Task 1: Increment, Decrement, and Compound Assignment ---
Initial score: 10
Score after += 5: 15
Score after ++: 16
Score after --: 15
Press enter to continue...
--- Task 2: Type Casting ---
Original price (double): 29.99
Price after casting to int: 29
Average price with explicit casting: 9.666666666666666
Press enter to continue...
--- Task 3: The Math Class and Constants ---
Area of circle with radius 5: 78.53975
Random dice roll: 2
Press enter to continue...
--- Task 4: Escape Characters ---
Item Price
Keyboard $75
Mouse $25
He said, "Hello, world!"
And the program responded, 'Hi.'
Press enter to continue...
--- Task 5: Challenge Task (Combining Concepts) ---
Out of 15 students, the new rounded grade is: 84.
This is a 5.000000000000004% increase.
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. Think about the concept of compound assignment. What is a real-world scenario (outside of a programming context) where you might perform a similar "shortcut" operation—where you update a value by combining it with another? For example, is there a situation where you keep a running total of expenses by adding each new cost to your existing total, rather than recalculating from scratch each time?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete