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;

// Define a variable following Java naming conventions (camelCase)
int variable123 = 123;
System.out.println(variable123);
123

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 DivisionExample {
    public static void main(String[] args) {
        // Integer division
        int intA = 7;
        int intB = 2;
        int intResult = intA / intB; // Results in 3 (integer division)
        System.out.println("Integer Division: " + intA + " / " + intB + " = " + intResult);

        // Floating-point division
        double doubleA = 7.0;
        double doubleB = 2.0;
        double doubleResult = doubleA / doubleB; // Results in 3.5 (floating-point division)
        System.out.println("Floating Point Division: " + doubleA + " / " + doubleB + " = " + doubleResult);
    }
}
// Q2.2 Hack: Show in code the differnt number types in Java and how they behave.
public class NumberTypesExample {
    public static void main(String[] args) {
        // Integer Types
        byte byteVar = 100; // 8-bit signed integer
        short shortVar = 10000; // 16-bit signed integer
        int intVar = 100000; // 32-bit signed integer
        long longVar = 100000L; // 64-bit signed integer

        System.out.println("Byte: " + byteVar);
        System.out.println("Short: " + shortVar);
        System.out.println("Int: " + intVar);
        System.out.println("Long: " + longVar);

        // Floating Point Types
        float floatVar = 3.14f; // 32-bit floating-point number
        double doubleVar = 3.14159; // 64-bit floating-point number

        System.out.println("Float: " + floatVar);
        System.out.println("Double: " + doubleVar);
    }
}

Behave means definition and assignment.

Integer Division: In the first example, integer division truncates the decimal, resulting in only the whole number part. Floating-point Division: The second example demonstrates that floating-point division retains decimal precision. Number Types: The second code snippet shows various number types (byte, short, int, long, float, double), their sizes, and how they behave when assigned values.

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 NonNumberPrimitivesExample {
    public static void main(String[] args) {
        // Boolean type
        boolean booleanVarTrue = true; // Represents true
        boolean booleanVarFalse = false; // Represents false
        
        // Char type
        char charVar = 'A'; // Represents a single character
        
        // Output the values and their behaviors
        System.out.println("Boolean True: " + booleanVarTrue);
        System.out.println("Boolean False: " + booleanVarFalse);
        System.out.println("Character: " + charVar);
    }
}
// Q3.2 Hack: Show in code the String data type and how it behaves.
public class StringExample {
    public static void main(String[] args) {
        // String type
        String stringVar = "Hello, World!"; // Represents a sequence of characters
        
        // String methods
        int length = stringVar.length(); // Get length of the string
        String upperCaseString = stringVar.toUpperCase(); // Convert to uppercase
        String subString = stringVar.substring(7, 12); // Get substring from index 7 to 12

        // Output the values and their behaviors
        System.out.println("String: " + stringVar);
        System.out.println("Length of String: " + length);
        System.out.println("Uppercase String: " + upperCaseString);
        System.out.println("Substring: " + subString);
    }
}

Question 4

Answer the following questions based on the code cell:

a. What kind of types are person1 and person2? Answer: Reference types (they are instances of the Person class).

b. Do person1 and person3 point to the same value in memory? Answer: Yes, both person1 and person3 point to the same Person object in memory.

c. Is the integer “number” stored in the heap or in the stack? Answer: The integer “number” is stored in the stack.

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.

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.

(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.

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

Primitive Types: Primitive types are the basic data types in Java that hold simple values. Examples include int, double, boolean, and char. In the banking application, you might use: int accountNumber to represent the unique identifier for each customer. double balance to represent the customer’s account balance. Reference Types: Reference types are objects that store references to the actual data. They are instances of classes and can hold more complex data structures. In the banking application, you could use: String name to represent the customer’s name. A custom class like Account to encapsulate the customer information and behaviors related to the account.

(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.

Memory Allocation Concepts: Stack: Primitive types like int and double are typically stored in the stack. The stack is a region of memory that stores method call frames, including local variables and method parameters. When a method is called, its variables are created on the stack, and they are discarded when the method finishes.

Heap: Reference types, like String or instances of classes (e.g., Account), are stored in the heap. The heap is used for dynamic memory allocation, where objects are created and can be accessed via references. When you create an Account object, the memory for that object is allocated on the heap, and the variable storing the reference (like Account myAccount) is stored on the stack.

Instance: Each time you create an object (an instance of a class), memory is allocated in the heap for the instance, including its fields (both primitive and reference types). The reference to that instance is stored in the stack.

public class Account {
    // Primitive types
    private int accountNumber; // Unique identifier for the account
    private double balance; // Balance in the account

    // Reference type
    private String name; // Customer's name

    // Static variable to create unique account numbers
    private static int lastAccountNumber = 0; // Last assigned account number

    // Static variable for interest rate
    private static double interestRate = 0.05; // 5% interest rate

    // Constructor to initialize name and balance
    public Account(String name, double balance) {
        this.name = name;
        this.balance = balance;
        lastAccountNumber++; // Increment account number
        this.accountNumber = lastAccountNumber; // Assign unique account number
    }

    // Method to calculate interest and update balance
    public void calculateInterest() {
        balance += balance * interestRate; // Update balance with interest
    }

    // Getters for balance and account number
    public double getBalance() {
        return balance;
    }

    public int getAccountNumber() {
        return accountNumber;
    }
}

(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 the 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 {
    // Primitive types
    private int accountNumber; // Unique identifier for the account
    private double balance; // Balance in the account

    // Reference type
    private String name; // Customer's name

    // Static variable to create unique account numbers
    private static int lastAccountNumber = 0; // Last assigned account number

    // Static variable for interest rate
    private static double interestRate = 0.05; // 5% interest rate

    // Constructor to initialize name and balance
    public Account(String name, double balance) {
        this.name = name;
        this.balance = balance;
        lastAccountNumber++; // Increment account number
        this.accountNumber = lastAccountNumber; // Assign unique account number
    }

    // Method to calculate interest and update balance
    public void calculateInterest() {
        balance += balance * interestRate; // Update balance with interest
    }

    // Getters for balance and account number
    public double getBalance() {
        return balance;
    }

    public int getAccountNumber() {
        return accountNumber;
    }

    public String getName() {
        return name; // Getter for name
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating multiple customers
        Account customer1 = new Account("Alice", 1000.00);
        Account customer2 = new Account("Bob", 1500.00);

        // Calculate interest for each customer
        customer1.calculateInterest();
        customer2.calculateInterest();

        // Print account details
        System.out.println("Account Number: " + customer1.getAccountNumber() + ", Name: " + customer1.getName() + ", Balance: " + customer1.getBalance());
        System.out.println("Account Number: " + customer2.getAccountNumber() + ", Name: " + customer2.getName() + ", Balance: " + customer2.getBalance());
    }
}