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?
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.
// Q2.2 Hack: Show in code the differnt number types in Java and how they behave.
// Behave means definition and assignment.
public class DivisionExample {
public static void main(String[] args) {
// Integer division (both operands are integers)
int intResult = 5 / 2;
System.out.println("Integer division: 5 / 2 = " + intResult); // Output: 2
// Floating-point division (one operand is a double)
double doubleResult = 5.0 / 2;
System.out.println("Floating-point division: 5.0 / 2 = " + doubleResult); // Output: 2.5
}
}
DivisionExample.main(null);
Integer division: 5 / 2 = 2
Floating-point division: 5.0 / 2 = 2.5
public class NumberTypesExample {
public static void main(String[] args) {
// Integer types
byte b = 10; // byte: 8-bit integer
short s = 1000; // short: 16-bit integer
int i = 50000; // int: 32-bit integer
long l = 1000000L; // long: 64-bit integer
// Floating-point types
float f = 5.75f; // float: 32-bit floating-point
double d = 3.14159; // double: 64-bit floating-point
// Display the values
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("int: " + i);
System.out.println("long: " + l);
System.out.println("float: " + f);
System.out.println("double: " + d);
}
}
NumberTypesExample.main(null);
byte: 10
short: 1000
int: 50000
long: 1000000
float: 5.75
double: 3.14159
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 NonNumberTypes {
public static void main(String[] args) {
// boolean type
boolean isJavaFun = true;
boolean isFishTasty = false;
// char type
char grade = 'A';
char symbol = '@';
// Display values
System.out.println("boolean isJavaFun: " + isJavaFun);
System.out.println("boolean isFishTasty: " + isFishTasty);
System.out.println("char grade: " + grade);
System.out.println("char symbol: " + symbol);
}
}
NonNumberTypes.main(null);
boolean isJavaFun: true
boolean isFishTasty: false
char grade: A
char symbol: @
// 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 greeting = "Hello, World!";
String name = "Java";
// String concatenation
String message = greeting + " Welcome to " + name + ".";
// Display values
System.out.println("greeting: " + greeting);
System.out.println("name: " + name);
System.out.println("message: " + message);
// String length and character access
System.out.println("Length of greeting: " + greeting.length());
System.out.println("Character at index 0: " + greeting.charAt(0));
}
}
StringExample.main(null);
greeting: Hello, World!
name: Java
message: Hello, World! Welcome to Java.
Length of greeting: 13
Character at index 0: H
Question 4
Answer the following questions based on the code cell:
- a) What kind of types are person1 and person2?
- Answer:
- b) Do person1 and person3 point to the same value in memory?
- Answer:
- c) Is the integer “number” stored in the heap or in the stack?
- Answer:
- d) Is the value that “person1” points to stored in the heap or in the stack?
- Answer:
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.
a) person1 and person2 are reference types
b) Yes, person1 and person3 point to the same value in memory.
c) Is the integer “number” stored in the stack?
d) The value that person1 points to (the Person object) is stored in the heap.
Question 5
(a) Define primitive types and reference types in Java. The application is for banking, where you need to represent customer information.
Ans) Primitive types in Java are predefined by the language and represent simple values like numbers, characters, and booleans. They are not objects and store their values directly in memory (on the stack). Examples include int, double, char, and boolean.
Reference types are objects created from classes. These store references (memory addresses) to the actual data, which resides in the heap. Reference types include classes, arrays, and interfaces. For example, String and custom classes like Account are reference types.
(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
andbalance
. - Consider in constructor how you will create a unique account number using
static int lastAccountNumber
- Define a method
calculateInterest
that works with getting and settingdouble balance
usingprivate static double interestRate
.
public class Account {
// Reference type: The customer's name is a String, stored in the heap
private String name;
// Primitive type: balance is a double, stored in the stack for local variables, or in the heap if part of an instance
private double balance;
// Primitive type: accountNumber is an int, stored in the stack for local variables, or in the heap as part of the instance
private int accountNumber;
// Static variable: shared among all instances of Account, used to create unique account numbers
private static int lastAccountNumber = 1000;
// Private static: Represents the bank's interest rate, shared across all accounts
private static double interestRate = 0.05; // 5% interest rate
// Constructor to initialize a new account with name and balance
public Account(String name, double balance) {
this.name = name;
this.balance = balance;
this.accountNumber = ++lastAccountNumber; // Generate unique account number
}
// Method to calculate interest and update balance
public void calculateInterest() {
// Calculate interest based on the current balance and static interest rate
double interest = this.balance * interestRate;
this.balance += interest; // Add interest to the current balance
}
// Getter for accountNumber
public int getAccountNumber() {
return accountNumber;
}
// Getter for balance
public double getBalance() {
return balance;
}
// Setter for balance
public void setBalance(double balance) {
this.balance = balance;
}
// Display account details
public void displayAccountInfo() {
System.out.println("Account Number: " + accountNumber);
System.out.println("Customer Name: " + name);
System.out.println("Current Balance: $" + balance);
}
public static void main(String[] args) {
// Create new customer accounts
Account customer1 = new Account("Alice", 1000.00);
Account customer2 = new Account("Bob", 1500.00);
// Calculate and update balances with interest
customer1.calculateInterest();
customer2.calculateInterest();
// Display account details
customer1.displayAccountInfo();
customer2.displayAccountInfo();
}
}
Account.main(null);
Account Number: 1001
Customer Name: Alice
Current Balance: $1050.0
Account Number: 1002
Customer Name: Bob
Current Balance: $1575.0