Unit 2: Using Objects
This unit focuses on object-oriented programming (OOP) concepts in Java, including classes, objects, methods, and the String
class.
Key Concepts
- Objects and Classes: A class is a blueprint for creating objects.
- Methods: Define the behavior of an object.
- Constructors: Special methods used to initialize objects.
- String Class: Used to manipulate text with methods like
length()
,substring()
, andequals()
. - Wrapper Classes: Convert primitive data types into objects (e.g.,
Integer
,Double
). - Null References: A reference that does not point to any object.
Example Code: Basic Objects
// Example: Using Objects in Java
public class UsingObjectsExample {
public static void main(String[] args) {
// Create a String object
String name = new String("Emily Johnson");
// Use String methods
int length = name.length(); // Get the length of the string
String substring = name.substring(0, 5); // Extract "Emily"
int index = name.indexOf("Johnson"); // Find the index of "Johnson"
boolean isEqual = name.equals("Emily Johnson"); // Compare strings
// Output results
System.out.println("Length: " + length);
System.out.println("Substring: " + substring);
System.out.println("Index of 'Johnson': " + index);
System.out.println("Is equal to 'Emily Johnson'? " + isEqual);
// Wrapper class example
Integer num = new Integer(42); // Create an Integer object
int primitiveNum = num.intValue(); // Convert to primitive type
System.out.println("Primitive value: " + primitiveNum);
}
}
Example Code: Advanced Objects
// Example: Advanced Object Operations in Java
public class AdvancedObjectsExample {
public static void main(String[] args) {
// String manipulation
String text = "Hello, World!";
String reversed = reverseString(text);
String[] words = text.split(" ");
// StringBuilder example
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString();
// Wrapper class operations
Double d1 = Double.valueOf("3.14");
Double d2 = Double.valueOf(2.718);
Double sum = d1 + d2; // Auto-unboxing
// Null handling
String nullString = null;
if (nullString != null) {
System.out.println("Length: " + nullString.length());
} else {
System.out.println("String is null");
}
// Print results
System.out.println("Reversed: " + reversed);
System.out.println("Words: " + String.join(", ", words));
System.out.println("StringBuilder result: " + result);
System.out.println("Sum of doubles: " + sum);
}
private static String reverseString(String str) {
StringBuilder reversed = new StringBuilder(str);
return reversed.reverse().toString();
}
}
String Manipulation Techniques
Common String Methods:
Method | Description | Example |
---|---|---|
length() |
Returns the length of the string | "Hello".length() → 5 |
substring(start, end) |
Returns a portion of the string | "Hello".substring(1, 4) → "ell" |
indexOf(str) |
Returns the index of the first occurrence | "Hello".indexOf("l") → 2 |
equals(str) |
Compares strings for equality | "Hello".equals("hello") → false |
compareTo(str) |
Compares strings lexicographically | "apple".compareTo("banana") → negative |
String Concatenation:
// Using + operator
String name = "John";
String greeting = "Hello, " + name + "!"; // "Hello, John!"
// Using concat() method
String s1 = "Hello";
String s2 = "World";
String result = s1.concat(" ").concat(s2); // "Hello World"
// Using StringBuilder (more efficient for multiple concatenations)
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String finalString = sb.toString(); // "Hello World"
String Comparison:
// Using equals() for content comparison
String s1 = "Hello";
String s2 = "hello";
boolean isEqual = s1.equals(s2); // false
// Using equalsIgnoreCase() for case-insensitive comparison
boolean isEqualIgnoreCase = s1.equalsIgnoreCase(s2); // true
// Using compareTo() for lexicographical comparison
int comparison = s1.compareTo(s2); // negative (H comes before h)
String Manipulation Tips:
- Strings are immutable - operations return new strings
- Use
StringBuilder
for multiple concatenations - Remember that string indices start at 0
- Be careful with
substring()
end index (exclusive) - Use
equals()
instead of==
for string comparison
Common Pitfalls and Debugging Tips
Common Mistakes:
- String Comparison: Using
==
instead ofequals()
String s1 = "Hello"; String s2 = new String("Hello"); System.out.println(s1 == s2); // false (compares references) System.out.println(s1.equals(s2)); // true (compares content)
- Null References: Forgetting to check for null
String s = null; System.out.println(s.length()); // NullPointerException
- String Index Out of Bounds: Using invalid indices
String s = "Hello"; System.out.println(s.charAt(5)); // StringIndexOutOfBoundsException
Debugging Tips:
- Use
System.out.println()
to print object states - Check for null references before method calls
- Verify string indices are within bounds
- Use
StringBuilder
for complex string operations - Test edge cases (empty strings, null values)
AP Exam Tips:
- Know the difference between
==
andequals()
- Understand string immutability
- Be able to trace string method calls
- Know when to use
StringBuilder
- Understand string comparison methods
AP Exam-Style Practice Problems
Problem 1: String Manipulation
Consider the following code segment:
String s = "Hello, World!";
String result = s.substring(7, 12);
System.out.println(result);
What is printed as a result of executing the code segment?
Problem 2: String Comparison
Consider the following code segment:
String s1 = "Hello";
String s2 = new String("Hello");
String s3 = s1;
System.out.println(s1 == s2);
System.out.println(s1 == s3);
What is printed as a result of executing the code segment?
Problem 3: StringBuilder
Consider the following code segment:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
sb.insert(5, ",");
System.out.println(sb.toString());
What is printed as a result of executing the code segment?
Problem 4: String Methods
Consider the following code segment:
String s = "Programming is fun!";
int index = s.indexOf("is");
String result = s.substring(index, index + 4);
System.out.println(result);
What is printed as a result of executing the code segment?
Multiple Choice Practice
Question 1:
What is the output of the following code?
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
System.out.println(str1 == str2);
System.out.println(str1 == str3);
Question 2:
Which of the following is NOT a wrapper class in Java?
Question 3:
What is the result of the following code?
String str = "Hello World";
System.out.println(str.substring(6, 11));
Question 4:
Which method is used to compare two strings in Java?
Question 5:
What happens when you try to call a method on a null object?
Practice Problems
- Write a program that takes a string as input and prints its length, first character, and last character.
- Write a program that extracts and prints the middle three characters of a string.
- Write a program that converts a
String
to anInteger
and performs arithmetic operations. - Write a program that checks if a string is
null
and prints an appropriate message. - Write a program that compares two strings and prints whether they are equal.
- Create a program that reverses a string using StringBuilder.
- Write a program that counts the number of vowels in a string.
- Create a program that converts a string to title case (first letter of each word capitalized).
Tips for Success
- Understand object-oriented concepts like classes, objects, and methods.
- Practice using the
String
class and its methods. - Learn how to handle
null
references to avoid runtime errors. - Use wrapper classes to convert between primitive types and objects.
- Write clean, readable code with meaningful variable names and comments.
- Remember that String objects are immutable - use StringBuilder for string manipulation.
- Be careful with string comparison - use equals() instead of == for content comparison.
- Understand the difference between primitive types and their wrapper classes.
Interactive Code Playground
Try out your own object-oriented code here! The code will run in a safe environment.
Output:
Note: This is a simulated environment. For actual Java code execution, please use an IDE or online Java compiler.
For actual code execution, we recommend using: