int [] numbers = {3, -4, 6, -7, 2};
for(int i = 0; i < numbers.length; i += 2)
{
System.out.println(numbers[i]);
}
3
6
2
Unit 2: Using Objects
Section 1
The relationship between classes and objects, in my own words:
- Classes are blueprints or templates that define the structure and behavior of objects. Objects are instances of classes, representing specific entities with unique attributes and behavior defined by their corresponding class.
Section 2
public class Student {
// instance variables
String name;
String teacher;
int period;
// constructor
public Student(String name, String teacher, int period) {
this.name = name;
this.teacher = teacher;
this.period = period;
}
// Identify, using its signature, the correct constructor being called.
// There is only one constructor method. However, I can specify that this class uses parameters to be set
// for each instance. This means that on initialization, the instance must have the parameters, as
// demonstrated in the following main method I created:
public static void main(String[] args) {
Student student = new Student("Paaras", "Mr. Mortensen", 1);
// Student errorStudent = new Student(); This line is commented out as it will cause errors, as
// discussed above.
}
}
Student.main(null);
Section 3
public class MyClass {
// Static method
public static void staticMethod() {
System.out.println("This is a static method.");
}
// Non-static (instance) method
public void nonStaticMethod() {
System.out.println("This is a non-static method.");
}
// Method with void return type
public void methodWithVoidReturnType() {
System.out.println("This method has a void return type.");
}
public static void main(String[] args) {
// Calling the static method
staticMethod();
// Creating an object of MyClass
MyClass myObject = new MyClass();
// Calling the non-static method on the object
myObject.nonStaticMethod();
// Calling the method with void return type
myObject.methodWithVoidReturnType();
}
}
MyClass.main(null);
This is a static method.
This is a non-static method.
This method has a void return type.
Section 5
Which method in this class is a non-void method? Edit the cell below to call the Calculator method.
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
int sum = calculator.add(5, 3);
// Printing the result
System.out.println("Sum: " + sum); // Output: Sum: 8
}
}
The add()
function is a non-void method. It will return an integer.
Section 6
Challenge: Display the background of the quote while displaying the quote in one line: “Give me liberty or give me death!” - Patrick Henry.
System.out.println("This is a famous quote written by Patrick Henry in the Virginia Convention: \n\"Give me liberty or give me death!\"");
// This code works because of the \n syntax. The syntax creates a new line when used.
This is a famous quote written by Patrick Henry in the Virginia Convention:
"Give me liberty or give me death!"
Question: If we have a string, what is its lower bound index and what is its upper bound index, if the string length is equal to the variable ‘str’?
Answer: The lower bound would be 0, unless CollegeBoard still uses a starting index of 1, and the upper bound would be one less than the length of the string, or str - 1
.
Question: What is the error for an out of bound string? Display it in the cell below.
String str = "Hello";
System.out.println(str.substring(0, 1000))
Answer: The error is that 1000 is out of bounds for a string with only five characters, or a length of 5.
FRQ Hacks
Question 1: Create a void method that takes an integer input and adds it to an ArrayList. Then, add a non-void method that is able to call a certain index from the ArrayList.
public class NumberList {
private ArrayList<Integer> numbersList;
public NumberList() {
numbersList = new ArrayList<>();
}
public void addNumber(int number) {
numbersList.add(number);
}
public int getNumberAtIndex(int index) {
if (index >= 0 && index < numbersList.size()) {
return numbersList.get(index);
} else {
throw new IndexOutOfBoundsException("Index out of bounds");
}
}
public static void main(String[] args) {
NumberList numberList = new NumberList();
Scanner scanner = new Scanner(System.in);
// Prompt the user to add numbers
System.out.println("Enter numbers to add to the list (enter 'done' to finish):");
String input;
while (true) {
input = scanner.nextLine();
if (input.equalsIgnoreCase("done")) {
break;
}
try {
int number = Integer.parseInt(input);
numberList.addNumber(number);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a number or 'done' to finish.");
}
}
// Print the ArrayList
System.out.println("Numbers in the ArrayList: " + numberList.numbersList);
// Prompt the user to enter an index
System.out.print("Enter an index to retrieve a number: ");
try {
int index = scanner.nextInt();
int numberAtIndex = numberList.getNumberAtIndex(index);
System.out.println("Number at index " + index + ": " + numberAtIndex);
} catch (IndexOutOfBoundsException e) {
System.out.println("Index out of bounds: " + e.getMessage());
} catch (java.util.InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid index.");
}
}
}
NumberList.main(null);
Enter numbers to add to the list (enter 'done' to finish):
Numbers in the ArrayList: [72308, 12838, 5, 7, 1, 1823]
Enter an index to retrieve a number: Number at index 0: 72308
Question 2: Create a simple guessing game with random numbers in math, except the random number is taken to a random exponent (also includes roots), and the person has to find out what the root and exponent is (with hints!). Use at least one static and one non-static method in your class.
public class GuessingGame {
private static Random random = new Random();
private int base;
private int exponent;
public GuessingGame() {
base = generateRandomBase();
exponent = generateRandomExponent();
}
private int generateRandomBase() {
return random.nextInt(10) + 1;
}
private int generateRandomExponent() {
return random.nextInt(10) + 1;
}
public void playGame() {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the guessing game!");
System.out.println("Guess the base and exponent (both between 1 and 10) for the number.");
System.out.println("Type 'exit' to quit the game.");
System.out.print("Enter your guess for the base: ");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
System.out.println("The correct base was " + base);
System.out.println("The correct exponent was " + exponent);
System.out.println("Thanks for playing. Exiting the game.");
return;
}
int guessedBase = Integer.parseInt(input);
System.out.print("Enter your guess for the exponent: ");
input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
System.out.println("The correct base was " + base);
System.out.println("The correct exponent was " + exponent);
System.out.println("Thanks for playing. Exiting the game.");
return;
}
int guessedExponent = Integer.parseInt(input);
if (guessedBase == base && guessedExponent == exponent) {
System.out.println("Congratulations! You guessed correctly.");
} else {
System.out.println("Wrong guess. Here's a hint:");
System.out.println("Hint: Base is " + (base % 2 == 0 ? "even" : "odd") +
", Exponent is " + (exponent % 2 == 0 ? "even" : "odd"));
System.out.print("Enter your second guess for the base: ");
input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
System.out.println("The correct base was " + base);
System.out.println("The correct exponent was " + exponent);
System.out.println("Thanks for playing. Exiting the game.");
return;
}
guessedBase = Integer.parseInt(input);
System.out.print("Enter your second guess for the exponent: ");
input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
System.out.println("The correct base was " + base);
System.out.println("The correct exponent was " + exponent);
System.out.println("Thanks for playing. Exiting the game.");
return;
}
guessedExponent = Integer.parseInt(input);
if (guessedBase == base && guessedExponent == exponent) {
System.out.println("Congratulations! You guessed correctly on your second try.");
} else {
System.out.println("Wrong guess. The base was " + base + " and the exponent was " + exponent);
}
}
}
public static void main(String[] args) {
GuessingGame game = new GuessingGame();
game.playGame();
}
}
GuessingGame.main(null)
Welcome to the guessing game!
Guess the base and exponent (both between 1 and 10) for the number.
Type 'exit' to quit the game.
Enter your guess for the base: Enter your guess for the exponent: Wrong guess. Here's a hint:
Hint: Base is even, Exponent is even
Enter your second guess for the base: The correct base was 8
The correct exponent was 2
Thanks for playing. Exiting the game.
Question 3: Create a class of your choosing that has multiple parameters of different types (int, boolean, String, double) and put 5 data values in that list. Show that you can access the information by givng some samples.
public class Person {
private int age;
private boolean getsPlay;
private String name;
private double height;
public Person(int age, boolean getsPlay, String name, double height) {
this.age = age;
this.getsPlay = getsPlay;
this.name = name;
this.height = height;
}
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Gets Play: " + getsPlay);
System.out.println("Height: " + height + " inches");
System.out.println();
}
public static void main(String[] args) {
// Create 5 instances of Person with different data values
Person person1 = new Person(16, true, "Tanay", 100.0);
Person person2 = new Person(16, false, "Shreyas", 7.2);
Person person3 = new Person(16, false, "Yuri", 6.0);
Person person4 = new Person (16, false, "Paaras", 6.5);
// Display information for each person
person1.displayInfo();
person2.displayInfo();
person3.displayInfo();
person4.displayInfo();
}
}
Person.main(null);
Name: Tanay
Age: 16
Gets Play: true
Height: 100.0 inches
Name: Shreyas
Age: 16
Gets Play: false
Height: 7.2 inches
Name: Yuri
Age: 16
Gets Play: false
Height: 6.0 inches
Name: Paaras
Age: 16
Gets Play: false
Height: 6.5 inches
Question 4: Using your preliminary knowlege of loops, use a for loop to iterate through a person’s first and last name, seperated by a space, and create methods to call a person’s first name and a person’s last name by iterating through the string.
public class PersonNameIterator {
private String fullName;
public PersonNameIterator(String fullName) {
this.fullName = fullName;
}
public String getFirstName() {
// Split the full name into parts based on the space separator
String[] nameParts = fullName.split(" ");
// Return the first part as the first name
return nameParts.length > 0 ? nameParts[0] : "";
}
public String getLastName() {
// Split the full name into parts based on the space separator
String[] nameParts = fullName.split(" ");
// Return the last part as the last name
return nameParts.length > 1 ? nameParts[1] : "";
}
public static void main(String[] args) {
String fullName = "Tanay Patel";
PersonNameIterator iterator = new PersonNameIterator(fullName);
// Display the first and last name using the methods
System.out.println("First Name: " + iterator.getFirstName());
System.out.println("Last Name: " + iterator.getLastName());
}
}
PersonNameIterator.main(null);
First Name: Tanay
Last Name: Patel