Kunal Java Unit-3
Kunal Java Unit-3
IndexOf: Returns the index of the first occurrence of the specified character or
substring.
int indexOfChar = str.indexOf('e');
int indexOfSubstring = str.indexOf("lo");
// Append
sb.append(" World");
System.out.println(sb); // Hello World
// Insert
sb.insert(5, " Java");
System.out.println(sb); // Hello Java World
// Replace
sb.replace(5, 10, "Awesome");
System.out.println(sb); // HelloAwesome World
// Delete
sb.delete(5, 12);
System.out.println(sb); // Hello World
// Reverse
sb.reverse();
System.out.println(sb); // dlroW olleH
// Capacity
System.out.println("Capacity: " + sb.capacity()); // Capacity: 21
// Ensure capacity
sb.ensureCapacity(50);
System.out.println("New Capacity: " + sb.capacity()); // New Capacity: 50
}
}
3. What are wrapper classes in Java? Why we need them?
ANS- Wrapper classes in Java are used to convert primitive data types into objects.
They are part of the java.lang package and provide a way to use primitive data types
(like int, char, boolean, etc.) as objects. Each primitive data type has a corresponding
wrapper class:
1. Integer: Wraps the primitive type int.
2. Boolean: Wraps the primitive type boolean.
3. Character: Wraps the primitive type char.
4. Byte: Wraps the primitive type byte.
5. Short: Wraps the primitive type short.
6. Long: Wraps the primitive type long.
7. Float: Wraps the primitive type float.
8. Double: Wraps the primitive type double.
Example Usages
1. Integer
int primitiveInt = 5;
Integer integerObj = Integer.valueOf(primitiveInt); // Boxing
int unboxedInt = integerObj.intValue(); // Unboxing
2. Boolean
boolean primitiveBoolean = true;
Boolean booleanObj = Boolean.valueOf(primitiveBoolean); // Boxing
boolean unboxedBoolean = booleanObj.booleanValue(); // Unboxing
3. Character
char primitiveChar = 'a';
Character characterObj = Character.valueOf(primitiveChar); // Boxing
char unboxedChar = characterObj.charValue(); // Unboxing