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(), and equals().
  • 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 of equals()
    
    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 == and equals()
  • 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?

"World"
"World!"
"Worl"
"orld"
The correct answer is A. The substring method returns characters from index 7 to 11 (end index is exclusive), which gives "World".
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?

false true
true true
false false
true false
The correct answer is A. s1 and s2 are different objects (false), but s1 and s3 reference the same object (true).
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?

"Hello, World"
"Hello World,"
"Hello,World"
"Hello World"
The correct answer is A. The code first appends " World" to "Hello", then inserts "," at index 5, resulting in "Hello, World".
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?

"is f"
"is"
"is f"
"is fun"
The correct answer is A. The index of "is" is 12, and substring(12, 16) returns "is f" (end index is exclusive).

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);
              
A. true true
B. true false
C. false true
D. false false
E. Compilation error
Explanation: The answer is B. String literals are stored in the string pool, so str1 and str2 refer to the same object. However, new String() creates a new object, so str3 refers to a different object.

Question 2:

Which of the following is NOT a wrapper class in Java?

A. Integer
B. Double
C. Boolean
D. String
E. Character
Explanation: The answer is D. String is a class but not a wrapper class. Wrapper classes are used to wrap primitive types into objects (e.g., Integer wraps int, Double wraps double).

Question 3:

What is the result of the following code?


String str = "Hello World";
System.out.println(str.substring(6, 11));
              
A. Hello
B. World
C. Hello W
D. World!
E. StringIndexOutOfBoundsException
Explanation: The answer is B. substring(6, 11) extracts characters from index 6 (inclusive) to index 11 (exclusive), which gives "World".

Question 4:

Which method is used to compare two strings in Java?

A. compare()
B. ==
C. equals()
D. compareTo()
E. equalsIgnoreCase()
Explanation: The answer is C. equals() is the standard method for comparing the contents of two strings. The == operator compares object references, not string contents.

Question 5:

What happens when you try to call a method on a null object?

A. The program continues normally
B. A compilation error occurs
C. A NullPointerException is thrown
D. The method returns null
E. The program crashes without an exception
Explanation: The answer is C. When you try to call a method on a null object, a NullPointerException is thrown at runtime.

Practice Problems

  1. Write a program that takes a string as input and prints its length, first character, and last character.
  2. Write a program that extracts and prints the middle three characters of a string.
  3. Write a program that converts a String to an Integer and performs arithmetic operations.
  4. Write a program that checks if a string is null and prints an appropriate message.
  5. Write a program that compares two strings and prints whether they are equal.
  6. Create a program that reverses a string using StringBuilder.
  7. Write a program that counts the number of vowels in a string.
  8. 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:

Test Your Knowledge

1. What is the difference between a class and an object?
A class is a blueprint, while an object is an instance of that class
A class is an instance, while an object is a blueprint
There is no difference
A class is for primitive types, while an object is for reference types
The correct answer is A. A class is a blueprint that defines the properties and behaviors of objects, while an object is a specific instance created from that class.
2. Which of the following correctly creates a String object?
String s = "Hello";
String s = new String("Hello");
String s = new String();
All of the above
The correct answer is D. All of the above are valid ways to create a String object in Java. The first method uses string literals, while the others use the new keyword.
3. What is the purpose of the Scanner class?
To read input from the user
To scan files on the computer
To scan network connections
To scan memory locations
The correct answer is A. The Scanner class is used to read input from various sources, most commonly from the keyboard (System.in).