knowt logo

2. Using Classes & Objects

/* 
Writer: SP
Date: March 21st
References: knowt & Fiveable
Unit 2: Using Objects & Classes */

Objects and Classes Overview

  • Object- An instance of a class that is usually created with attributes

    • It is a reference data type.

  • Class- A template that defines what an object is like and what the object can do.

  • Object is known as an instance of class.

Constructor & Object

class Car {
// Attributes (variables) of the Car class
String brand;
int year;

// Default constructor (no arguments)
public Car() {
brand = "Unknown";
year = 2000; // Set default values
}

// Parameterized constructor (accepts arguments)
public Car(String brand, int year) {
this.brand = brand; // Use 'this' keyword to differentiate from local variable
this.year = year;
}
}

public class Main {
public static void main(String[] args) {

// Create object using default constructor
Car car1 = new Car();
System.out.println("Car 1: Brand = " + car1.brand + ", Year = " + car1.year);

// Create object using parameterized constructor
Car car2 = new Car("Tesla", 2023);
System.out.println("Car 2: Brand = " + car2.brand + ", Year = " + car2.year);
}
}
  • We can know that the constructor shows what does object has.

Constructor & Exceptions

Teacher(String name, int age, boolean sex) // true is male, vice versa
Teacher(int age, String name, boolean sex)

If we write Teacher mrDeWet = new Teacher(“Mr. De Wet”, 29, true); calls first constructor.

Teacher mrDeVilliers = new Teacher(49, "Mr. De Villiers”, true); calls second constructor.

If you do not follow the order of parameter, it will result IllegalArgumentException

Person invisibile = null;
  • We can make an object that doesn’t store a value. We use ‘null’ to make empty object.

  • When we call it or using method with it, it will return NullPointerException

Method

  • Method is a piece of code that is created for specific task.

  • Void Method vs. Non-Void Method

// void method
public void greetUser(String name) {
System.out.println("Hello, " + name + "!");
}

// non-void method
public int addNumbers(int num1, int num2) {
int sum = num1 + num2;
return sum; // Return the calculated sum
}
  • Method addNumbers return type is int.

  • Methods will overload if we do not put proper number of parameters inside of the parenthesis.

  • Static vs. Non-Static Methods

class MathHelper {
// Static method (no object required)
public static double calculateArea(int length, int width) {
return length * width;
}

// Non-static method (requires an object)
public void greet(String name) {
System.out.println("Hello, " + name + "!");
}
}

public class Main {
public static void main(String[] args) {
// Call static method directly using class name
double area = MathHelper.calculateArea(5, 3);
System.out.println("Area: " + area);

// Create an object to call non-static method
MathHelper helper = new MathHelper();
helper.greet("Alice"); // Call on the specific object
}
}
  • Static Method: We need a ‘class’ to operate the method. We don’t have to make an object.

  • Non-Static Method: We don’t need a class. Instead we use a particular object to operate.

String

Two ways to assign String

String var = "Mr. MacIsaac";

String mrLee = new String("Mr. Lee");

Comparing:

String phone = "Samsung Galaxy";
String pphone = new String("Samsung Galaxy");

System.out.println(phone == pphone); // return false;
System.out.println(phone.equals(pphone)); // return true;

‘==’ compares the value in the same object.

‘.equals’ compares the value.

.compareTo Method:

  • Comparing the unicode value of the first character.

public class Main {
public static void main(String[] args) {
String myStr1 = "Hello";
String myStr2 = "Bye";
System.out.println(myStr1.compareTo(myStr2));
}
}

Above code’s result is 6 because H’s unicode value is 72, and B’s unicode value is 66. 72 - 66 = 6.

.indexOf Method:

  • Return the index number of certain character.

String one = "Hello World";
one.indexOf("e");

// return 1.
  • If there is no character in the string, it returns -1.

Concatenation:

"3"+"3" = "33"
3 + "3" = "33"
3.0 + "3" = "3.03"
"3" + 3.0 = 33.0

String fName = "Peter ";
String sName = "Cao";
System.out.println(fName + sName); // Peter Cao
  • When there is a mathematical expression on one side, then it will operate first and do concatenation.

  • To do concatenation using String object, using “toString()” method. => Convert object to String

API

  • When we program we can import external libraries and APIs (Application Program Interfaces).

Substring

  • Substring is a String inside of String.

  • If there is a string, we can access to the string inside of the string.

  • .length Method: return the length of the String. Start with 1.

  • Index in Java starts at 0.

String str = "AP CSA";

// To print only CSA.
System.out.println(str.substring(3, 6));

// Or
System.out.println(str.substring(3));

Wrapper Class (Integer & Double)

Integer Class and Double Class are wrapper class because they transform primitive data type to reference data type like object.

Integer numBooks = new Integer(10);

This object has a value of 10.

There are two key variables:

  • Integer.MIN_VALUE returns the minimum value that an int type can store. This value is -2147683648

  • Integer.MAX_VALUE returns the maximum value that an int type can store. This value is 2147683647.

.intValue()

  • Returns the object value as a primitive type value.

Double Wrapper Class:

Double height = new Double(6.4);

.doubleValue()

  • Returns the object value as a primitive type value

Autoboxing

  • Converting a primitive data type to its corresponding wrapper class.

int a = 5;
Integer b = a;

// Unboxing

Integer x = new Integer(10);
int y = x; // the value of y is 10.

Math Class

  • Math methods are static.

  • We don’t need to create the objects in this class.

Absolute Value:

  • Math.abs(number)

  • Return type is depending on its type.

Exponents and Square Roots:

  • Exponent Code: Math.pow(base, exponen)

  • The return type is double.

  • Square Root Code: Math.sqrt(a)

  • The return type is double.

Random Number:

  • Math.random()

  • It will return a double greater than or equal to 0, and less than 1.

  • If you want to make a random number greater than or equal to number a and less than number b.

    • (int)(Math.random() * (b-a) + a)

      • If we don’t cast int, it will return double.

    • Example: How to generate random integer from 5 to 555?

      • (int)(Math.random() * (556-5) + 5);

        • because it returns b-1, we need to add 1.

  • Here are the main ones used on the AP Exam:

    • Ex: Say you want to calculate the amount of candy each person gets amongst your group of 5 friends. You have 14 chocolates, and you didn’t feel like doing the math so you decide on using your amazing IDE to help you out. What line of code would best fit your needs?

a. Math.abs(14/5);

b.Math.pow(14,5);

c. double chocAmount = 14.0/5.0;

//chose between these 3 options

Answer: C would be the only option that fits your needs because you don’t want an absolute value for your number of chocolates. It has to be accurate, and you don’t need exponents either. You just want to find out how to split the chocolate amount. So, this would be your answer.

SS

2. Using Classes & Objects

/* 
Writer: SP
Date: March 21st
References: knowt & Fiveable
Unit 2: Using Objects & Classes */

Objects and Classes Overview

  • Object- An instance of a class that is usually created with attributes

    • It is a reference data type.

  • Class- A template that defines what an object is like and what the object can do.

  • Object is known as an instance of class.

Constructor & Object

class Car {
// Attributes (variables) of the Car class
String brand;
int year;

// Default constructor (no arguments)
public Car() {
brand = "Unknown";
year = 2000; // Set default values
}

// Parameterized constructor (accepts arguments)
public Car(String brand, int year) {
this.brand = brand; // Use 'this' keyword to differentiate from local variable
this.year = year;
}
}

public class Main {
public static void main(String[] args) {

// Create object using default constructor
Car car1 = new Car();
System.out.println("Car 1: Brand = " + car1.brand + ", Year = " + car1.year);

// Create object using parameterized constructor
Car car2 = new Car("Tesla", 2023);
System.out.println("Car 2: Brand = " + car2.brand + ", Year = " + car2.year);
}
}
  • We can know that the constructor shows what does object has.

Constructor & Exceptions

Teacher(String name, int age, boolean sex) // true is male, vice versa
Teacher(int age, String name, boolean sex)

If we write Teacher mrDeWet = new Teacher(“Mr. De Wet”, 29, true); calls first constructor.

Teacher mrDeVilliers = new Teacher(49, "Mr. De Villiers”, true); calls second constructor.

If you do not follow the order of parameter, it will result IllegalArgumentException

Person invisibile = null;
  • We can make an object that doesn’t store a value. We use ‘null’ to make empty object.

  • When we call it or using method with it, it will return NullPointerException

Method

  • Method is a piece of code that is created for specific task.

  • Void Method vs. Non-Void Method

// void method
public void greetUser(String name) {
System.out.println("Hello, " + name + "!");
}

// non-void method
public int addNumbers(int num1, int num2) {
int sum = num1 + num2;
return sum; // Return the calculated sum
}
  • Method addNumbers return type is int.

  • Methods will overload if we do not put proper number of parameters inside of the parenthesis.

  • Static vs. Non-Static Methods

class MathHelper {
// Static method (no object required)
public static double calculateArea(int length, int width) {
return length * width;
}

// Non-static method (requires an object)
public void greet(String name) {
System.out.println("Hello, " + name + "!");
}
}

public class Main {
public static void main(String[] args) {
// Call static method directly using class name
double area = MathHelper.calculateArea(5, 3);
System.out.println("Area: " + area);

// Create an object to call non-static method
MathHelper helper = new MathHelper();
helper.greet("Alice"); // Call on the specific object
}
}
  • Static Method: We need a ‘class’ to operate the method. We don’t have to make an object.

  • Non-Static Method: We don’t need a class. Instead we use a particular object to operate.

String

Two ways to assign String

String var = "Mr. MacIsaac";

String mrLee = new String("Mr. Lee");

Comparing:

String phone = "Samsung Galaxy";
String pphone = new String("Samsung Galaxy");

System.out.println(phone == pphone); // return false;
System.out.println(phone.equals(pphone)); // return true;

‘==’ compares the value in the same object.

‘.equals’ compares the value.

.compareTo Method:

  • Comparing the unicode value of the first character.

public class Main {
public static void main(String[] args) {
String myStr1 = "Hello";
String myStr2 = "Bye";
System.out.println(myStr1.compareTo(myStr2));
}
}

Above code’s result is 6 because H’s unicode value is 72, and B’s unicode value is 66. 72 - 66 = 6.

.indexOf Method:

  • Return the index number of certain character.

String one = "Hello World";
one.indexOf("e");

// return 1.
  • If there is no character in the string, it returns -1.

Concatenation:

"3"+"3" = "33"
3 + "3" = "33"
3.0 + "3" = "3.03"
"3" + 3.0 = 33.0

String fName = "Peter ";
String sName = "Cao";
System.out.println(fName + sName); // Peter Cao
  • When there is a mathematical expression on one side, then it will operate first and do concatenation.

  • To do concatenation using String object, using “toString()” method. => Convert object to String

API

  • When we program we can import external libraries and APIs (Application Program Interfaces).

Substring

  • Substring is a String inside of String.

  • If there is a string, we can access to the string inside of the string.

  • .length Method: return the length of the String. Start with 1.

  • Index in Java starts at 0.

String str = "AP CSA";

// To print only CSA.
System.out.println(str.substring(3, 6));

// Or
System.out.println(str.substring(3));

Wrapper Class (Integer & Double)

Integer Class and Double Class are wrapper class because they transform primitive data type to reference data type like object.

Integer numBooks = new Integer(10);

This object has a value of 10.

There are two key variables:

  • Integer.MIN_VALUE returns the minimum value that an int type can store. This value is -2147683648

  • Integer.MAX_VALUE returns the maximum value that an int type can store. This value is 2147683647.

.intValue()

  • Returns the object value as a primitive type value.

Double Wrapper Class:

Double height = new Double(6.4);

.doubleValue()

  • Returns the object value as a primitive type value

Autoboxing

  • Converting a primitive data type to its corresponding wrapper class.

int a = 5;
Integer b = a;

// Unboxing

Integer x = new Integer(10);
int y = x; // the value of y is 10.

Math Class

  • Math methods are static.

  • We don’t need to create the objects in this class.

Absolute Value:

  • Math.abs(number)

  • Return type is depending on its type.

Exponents and Square Roots:

  • Exponent Code: Math.pow(base, exponen)

  • The return type is double.

  • Square Root Code: Math.sqrt(a)

  • The return type is double.

Random Number:

  • Math.random()

  • It will return a double greater than or equal to 0, and less than 1.

  • If you want to make a random number greater than or equal to number a and less than number b.

    • (int)(Math.random() * (b-a) + a)

      • If we don’t cast int, it will return double.

    • Example: How to generate random integer from 5 to 555?

      • (int)(Math.random() * (556-5) + 5);

        • because it returns b-1, we need to add 1.

  • Here are the main ones used on the AP Exam:

    • Ex: Say you want to calculate the amount of candy each person gets amongst your group of 5 friends. You have 14 chocolates, and you didn’t feel like doing the math so you decide on using your amazing IDE to help you out. What line of code would best fit your needs?

a. Math.abs(14/5);

b.Math.pow(14,5);

c. double chocAmount = 14.0/5.0;

//chose between these 3 options

Answer: C would be the only option that fits your needs because you don’t want an absolute value for your number of chocolates. It has to be accurate, and you don’t need exponents either. You just want to find out how to split the chocolate amount. So, this would be your answer.