Skip to the content.
Intro Primitive Types Reference Types Stack and Heap Code Example Quiz

Quiz Questions for APCSA Unit 1

Questions and Code Cells for the Quiz on Unit 1

CSA-Quiz

Unit 1: Primitive Types

Question 1

Which of the following is a valid declaration of a variable of type int in Java?
a) int 123variable;
b) int variable123;
c) int variable#123;
d) int variable 123;

Answer: b) int variable123;

// Q1 Hack: Define variables according to Java naming conventions.
// For instance, is it snake_case, camelCase, or PascalCase? It is in camelCase.

int variable123 = 123;
System.out.println(variable123);

Question 2

What is the value of the following expression in Java: 5 / 2?
a) 2.5
b) 3
c) 2
d) 2.0

Answer: c) 2

// Q2.1 Hack: Show in code difference between integer and floating point division.
public class DivisionDemo {
    public static void main(String[] args) {
        // Integer division
        int intA = 10;
        int intB = 3;
        int intResult = intA / intB; // Truncates decimal part
        System.out.println("Integer Division: 10 / 3 = " + intResult); // Output: 3

        // Floating-point division
        double doubleA = 10;
        double doubleB = 3;
        double doubleResult = doubleA / doubleB; // Includes decimal part
        System.out.println("Floating-point Division: 10 / 3 = " + doubleResult); // Output: 3.3333333
    }
}
// In Java, integer division truncates the decimal part, while floating-point division provides the complete result, including the decimal.
// Q2.2 Hack: Show in code the differnt number types in Java and how they behave.
public class NumberTypesDemo {
    public static void main(String[] args) {
        // Integer type (4 bytes, no decimals)
        int myInt = 100;
        System.out.println("Integer: " + myInt); // Output: 100

        // Long type (8 bytes, larger range of integers)
        long myLong = 10000000000L;
        System.out.println("Long: " + myLong); // Output: 10000000000

        // Float type (4 bytes, less precision than double)
        float myFloat = 5.75f;
        System.out.println("Float: " + myFloat); // Output: 5.75

        // Double type (8 bytes, more precision than float)
        double myDouble = 19.99;
        System.out.println("Double: " + myDouble); // Output: 19.99

        // Byte type (1 byte, small integers)
        byte myByte = 127;
        System.out.println("Byte: " + myByte); // Output: 127

        // Short type (2 bytes, small integers)
        short myShort = 32000;
        System.out.println("Short: " + myShort); // Output: 32000
    }
}

// This demonstrates the different behaviors of number types in Java and the contrast between integer and floating-point division.

Question 3

Which primitive type is used to represent a single character in Java?
a) char
b) String
c) int
d) byte

Answer: a) char

// Q3.1 Hack: Show in code all the the non-number Java primitive data types and how they behave.
public class NonNumberTypesDemo {
    public static void main(String[] args) {
        // Character type (2 bytes, single character/Unicode value)
        char myChar = 'A';
        System.out.println("Character: " + myChar); // Output: A

        // Char can also store Unicode values
        char unicodeChar = '\u0041'; // Unicode for 'A'
        System.out.println("Unicode Character: " + unicodeChar); // Output: A

        // Boolean type (1 bit, true or false)
        boolean isJavaFun = true;
        boolean isFishTasty = false;
        System.out.println("Boolean 1: " + isJavaFun);   // Output: true
        System.out.println("Boolean 2: " + isFishTasty); // Output: false
    }
}
// Java has three non-number primitive data types: char, boolean, and void. The void type is used in method declarations, but the other two can be demonstrated with examples.
// Q3.2 Hack: Show in code the String data type and how it behaves.
public class StringDemo {
    public static void main(String[] args) {
        // String declaration
        String greeting = "Hello, World!";
        System.out.println("Greeting: " + greeting); // Output: Hello, World!

        // String concatenation
        String name = "Anusha";
        String message = greeting + " My name is " + name + ".";
        System.out.println("Concatenated String: " + message); // Output: Hello, World! My name is Anusha.

        // String length
        int length = message.length();
        System.out.println("Length of message: " + length); // Output: 32

        // Accessing characters in a String
        char firstChar = message.charAt(0);
        System.out.println("First character: " + firstChar); // Output: H

        // Substring
        String sub = message.substring(7, 12);
        System.out.println("Substring: " + sub); // Output: World

        // String comparison
        String str1 = "hello";
        String str2 = "Hello";
        boolean isEqual = str1.equalsIgnoreCase(str2); // Case-insensitive comparison
        System.out.println("Are strings equal (ignore case): " + isEqual); // Output: true
    }
}
// This demonstrates the non-number primitives (char, boolean) and the behavior of the String data type in Java, showing common string operations like concatenation, substring extraction, and comparison.

Question 4

Answer the following questions based on the code cell:

  • a) What kind of types are person1 and person2?
  • Answer: person1 and person2 are reference types. Specifically, they are references to objects of the Person class.
  • b) Do person1 and person3 point to the same value in memory?
  • Answer: Yes, person1 and person3 point to the same value in memory. Since person3 = person1, both references point to the same Person object, so any change made via person1 will be reflected when accessing person3.
  • c) Is the integer “number” stored in the heap or in the stack?
  • Answer: The integer number is stored in the stack. Primitive types like int are stored directly on the stack in Java, where the method’s local variables reside.
  • d) Is the value that “person1” points to stored in the heap or in the stack?
  • Answer: The value that person1 points to (the Person object) is stored in the heap. In Java, objects created with new are allocated in the heap, while the reference variable person1 itself is stored on the stack.
public class Person {
    String name;
    int age;
    int height;
    String job;

    public Person(String name, int age, int height, String job) {
        this.name = name;
        this.age = age;
        this.height = height;
        this.job = job;
    }
}

public static void main(String[] args) {
    Person person1 = new Person("Carl", 25, 165, "Construction Worker");
    Person person2 = new Person("Adam", 29, 160, "Truck Driver");
    Person person3 = person1;
    int number = 16;
    System.out.println(number);
}
main(null); // This is required in Jupiter Notebook to run the main method.

Question 5

(a) Define primitive types and reference types in Java. The application is for banking, where you need to represent customer information.

  • Primitive types in Java are basic data types that store values directly in memory. They include int, double, boolean, char, etc. These types are used when we need simple data without additional methods or behavior. In a banking application, primitive types might be used to store customer balances or account numbers.

  • Reference types refer to objects and arrays. Instead of holding the data itself, reference types store the memory address where the actual object resides in the heap. In a banking application, classes like Customer or Account are reference types. These types hold complex data (like customer name, transactions) and behavior (like calculating interest). (b) Add comments for primitive types and reference types. In terms of memory allocation, discuss concepts like instance, stack, and heap where it adds value.

(c) To assist in requirements, here are some required elements:

  • Create multiple customers from the public class Account.
  • Consider key class variables that a Bank may require: name, balance, accountNumber.
  • Create a two argument constructor using name and balance.
  • Consider in constructor how you will create a unique account number using static int lastAccountNumber
  • Define a method calculateInterest that works with getting and setting double balance using private static double interestRate.
public class Account {
    // Class variables (Reference Types)
    String name;        // The name of the account holder (Reference type, stored in heap)
    double balance;     // The balance in the account (Primitive type, stored in heap as part of the object)
    int accountNumber;  // Unique account number (Primitive type, stored in heap as part of the object)

    // Static variable to keep track of the last account number assigned (Primitive type, stored in the heap as part of class memory)
    private static int lastAccountNumber = 1000; 

    // Static interest rate (Primitive type, shared across all instances, stored in the heap)
    private static double interestRate = 0.05;

    // Constructor (Creates instances of Account, memory allocated in the heap)
    public Account(String name, double balance) {
        this.name = name; // Name is a reference to a string, stored in heap
        this.balance = balance; // Balance is a primitive type, part of the object's memory in the heap
        this.accountNumber = ++lastAccountNumber; // Unique account number, increments with each new Account
    }

    // Method to calculate interest (This works with the balance)
    public void calculateInterest() {
        // Calculate interest and update the balance
        double interest = this.balance * interestRate;
        this.balance += interest;
    }

    // Getters and Setters for Balance
    public double getBalance() {
        return this.balance; // Return balance from heap memory
    }

    public void setBalance(double balance) {
        this.balance = balance; // Update balance in heap memory
    }

    public static void main(String[] args) {
        // Creating customer accounts (Reference types stored on the stack, actual objects in the heap)
        Account customer1 = new Account("Alice", 1500.00); // Reference type (stack), object (heap)
        Account customer2 = new Account("Bob", 2000.00);   // Reference type (stack), object (heap)

        // Display customer information
        System.out.println("Customer: " + customer1.name + ", Account Number: " + customer1.accountNumber + ", Balance: $" + customer1.getBalance());
        System.out.println("Customer: " + customer2.name + ", Account Number: " + customer2.accountNumber + ", Balance: $" + customer2.getBalance());

        // Calculate interest and update balances
        customer1.calculateInterest();
        customer2.calculateInterest();

        // Display updated balances after interest calculation
        System.out.println("Updated Balance for " + customer1.name + ": $" + customer1.getBalance());
        System.out.println("Updated Balance for " + customer2.name + ": $" + customer2.getBalance());
    }
}