AP Computer Science A Unit 2 Review with Java Code…
1. Objects – Instances of Classes
public class Dog {
String breed; // Breed of the dog
int age; // Age of the dog
void bark() {
System.out.println("Woof!"); // Print bark sound
}
}
public class ObjectExample {
public static void main(String[] args) {
// Creating an object of a class
Dog myDog = new Dog();
// Accessing and modifying object's properties
myDog.breed = "Labrador";
myDog.age = 3;
// Calling object's methods
myDog.bark();
}
}
2. Creating and Storing Objects (Instantiation)
public class ObjectInstantiationExample {
public static void main(String[] args) {
// Instantiating an object using the 'new' keyword
Dog myDog = new Dog();
// Storing the created object in a variable
Dog anotherDog = myDog;
}
}
3. Calling a Void Method
public class VoidMethodExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.bark(); // Calling a void method
}
}
4. Calling a Void Method with Parameters
public class VoidMethodWithParametersExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.feed("bones"); // Calling a void method with parameters
}
}
5. Calling a Non-void Method
public class NonVoidMethodExample {
public static void main(String[] args) {
Dog myDog = new Dog();
int dogAge = myDog.getAge(); // Calling a non-void method
}
}
6. String Objects – Concatenation, Literals, and More
public class StringExample {
public static void main(String[] args) {
// Concatenating string objects
String fullName = "John" + " " + "Doe";
// String literals
String message = "Hello, World!";
}
}
7. String Methods
public class StringMethodsExample {
public static void main(String[] args) {
String str = "Hello, World!";
// Using string methods
int length = str.length();
char firstChar = str.charAt(0);
String subStr = str.substring(0, 5);
}
}
8. Wrapper Classes – Integer and Double
public class WrapperClassExample {
public static void main(String[] args) {
// Using wrapper classes
Integer intObject = Integer.valueOf(5);
Double doubleObject = Double.valueOf(3.14);
}
}
9. Using the Math Class
public class MathExample {
public static void main(String[] args) {
// Using methods of the Math class
double pi = Math.PI;
double sqrtValue = Math.sqrt(16);
}
}