Unit 1: Primitive Types

This unit introduces the basics of programming in Java, focusing on fundamental data types, variables, and operations.

Key Concepts

  • Variables: Store data in a program.
  • Primitive Data Types: int, double, boolean, char.
  • Operators: Arithmetic, assignment, and compound assignment.
  • Expressions: Combinations of variables, operators, and literals.
  • Type Casting: Converting one data type to another.
  • Constants: Declared with final.
  • Operator Precedence: Order of operations.
  • Escape Sequences: Special characters for formatting strings.

Example Code: Basic Primitive Types


// Example: Primitive Types in Java
public class PrimitiveTypesExample {
  public static void main(String[] args) {
    // Declare variables
    int num1 = 10;
    double num2 = 3.5;
    boolean isJavaFun = true;
    char grade = 'A';
    final double PI = 3.14159; // Constant

    // Perform arithmetic operations
    int sum = num1 + (int) num2; // Type casting double to int
    double product = num1 * num2;

    // Output results
    System.out.println("Sum: " + sum);
    System.out.println("Product: " + product);
    System.out.println("Is Java fun? " + isJavaFun);
    System.out.println("Grade: " + grade);
    System.out.println("PI: " + PI);
  }
}
              

Example Code: Advanced Operations


// Example: Advanced Operations with Primitive Types
public class AdvancedOperations {
    public static void main(String[] args) {
        // Compound assignment operators
        int x = 5;
        x += 3; // x = x + 3
        x *= 2; // x = x * 2
        x %= 4; // x = x % 4
        
        // Type casting examples
        double d = 3.14159;
        int i = (int)d; // Explicit casting
        long l = i; // Implicit casting
        
        // Operator precedence
        int result = 2 + 3 * 4; // Multiplication first
        int result2 = (2 + 3) * 4; // Parentheses first
        
        // Escape sequences
        System.out.println("Line 1\nLine 2"); // New line
        System.out.println("Tab\tSpacing"); // Tab
        System.out.println("Quote: \"Hello\""); // Quote
        System.out.println("Backslash: \\"); // Backslash
        
        // Print results
        System.out.println("x = " + x);
        System.out.println("i = " + i);
        System.out.println("result = " + result);
        System.out.println("result2 = " + result2);
    }
}
              

Common Pitfalls and Debugging Tips

Common Mistakes:

  • Integer Division: Remember that dividing two integers results in integer division (truncation)
    
    int result = 5 / 2;  // result is 2, not 2.5
    double correct = 5.0 / 2;  // correct is 2.5
                      
  • Type Casting: Be careful with narrowing conversions
    
    double d = 3.7;
    int i = (int) d;  // i is 3 (truncates decimal)
                      
  • Character vs String: Remember that char literals use single quotes
    
    char c = 'A';  // correct
    char wrong = "A";  // error: String cannot be converted to char
                      

Debugging Tips:

  • Use System.out.println() to print variable values at key points
  • Check for integer overflow when working with large numbers
  • Verify type casting is working as expected
  • Use parentheses to clarify operator precedence
  • Test edge cases (e.g., division by zero, maximum/minimum values)

AP Exam Tips:

  • Know the range of each primitive type
  • Understand operator precedence rules
  • Be able to trace code with multiple operations
  • Recognize common integer division scenarios
  • Know when to use type casting

AP Exam-Style Practice Problems

Problem 1: Variable Declaration and Initialization

Consider the following code segment:


int x = 5;
double y = 2.0;
int z = (int) (x / y);
System.out.println(z);
                

What is printed as a result of executing the code segment?

2
2.5
3
2.0
The correct answer is A. The division x/y results in 2.5, but when cast to an int, the decimal part is truncated, resulting in 2.
Problem 2: Operator Precedence

Consider the following code segment:


int a = 3;
int b = 4;
int c = 5;
int result = a + b * c;
System.out.println(result);
                

What is printed as a result of executing the code segment?

35
23
60
12
The correct answer is B. Multiplication has higher precedence than addition, so b * c is evaluated first (4 * 5 = 20), then a is added (3 + 20 = 23).
Problem 3: Type Casting

Consider the following code segment:


double d = 3.7;
int i = (int) d;
double result = i + d;
System.out.println(result);
                

What is printed as a result of executing the code segment?

6.7
7.4
7.0
6.0
The correct answer is A. When d is cast to an int, it becomes 3. Then 3 + 3.7 = 6.7. The int is automatically promoted to double for the addition.
Problem 4: Character Operations

Consider the following code segment:


char c = 'A';
int i = c + 1;
char next = (char) i;
System.out.println(next);
                

What is printed as a result of executing the code segment?

'B'
66
'A'
65
The correct answer is A. Characters are stored as Unicode values. 'A' is 65, so 65 + 1 = 66, which is 'B' in Unicode.

Interactive Code Playground

Try out your own primitive types code here!

Output:
Note: This is a simulated environment. For actual Java code execution, please use an IDE or online Java compiler.

For actual code execution, we recommend using:

Test Your Knowledge

1. Which of the following is NOT a primitive type in Java?
int
double
String
boolean
The correct answer is C. String. String is a class in Java, not a primitive type. The primitive types in Java are: byte, short, int, long, float, double, char, and boolean.
2. What is the result of the expression: 5 / 2?
2.5
2
2.0
2.5f
The correct answer is B. 2. When dividing two integers, Java performs integer division and truncates the decimal portion. To get 2.5, you would need to use floating-point numbers (5.0 / 2.0).
3. Which of the following is a valid declaration of a char?
char c = 'A';
char c = "A";
char c = 65;
char c = 'AB';
The correct answers are A and C. A char can be declared using a single character in single quotes ('A') or using its ASCII value (65). Double quotes are used for Strings, and a char can only hold one character.

Practice Problems

  1. Write a program that calculates the area of a rectangle.
  2. Convert a temperature from Fahrenheit to Celsius.
  3. Swap the values of two variables without using a third variable.
  4. Calculate the volume of a sphere using the formula V = (4/3)πr³.
  5. Write a program that converts seconds into hours, minutes, and seconds.

Tips for Success

  • Practice coding regularly.
  • Use comments to explain your code.
  • Test your programs with different inputs.
  • Understand operator precedence to avoid common mistakes.
  • Be careful with type casting to avoid data loss.
  • Use meaningful variable names that describe their purpose.
  • Remember that integer division truncates decimal places.