0% found this document useful (0 votes)
6 views

08 String and String Buffer Class

Uploaded by

chintuunagar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

08 String and String Buffer Class

Uploaded by

chintuunagar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

QUE: Explain the String class in Java with all its methods with proper

examples.
ANS:
The String class in Java is part of the java.lang package and is widely used for
representing sequences of characters. It's important to note that String objects
in Java are immutable, meaning once a String object is created, its value cannot
be changed. Any operation that appears to modify a String actually creates a new
String object.

Here's a detailed explanation of some commonly used methods of the String


class along with examples:

(1) length():
• Returns the length of the string.
• Example:

String str = "Hello, World!";


int length = str.length(); // length is 13

(2) charAt(int index):


• Returns the character at the specified index.
• Example:

char charAtIndex = str.charAt(7); // charAtIndex is 'W'

(3) substring(int beginIndex):


• Returns a substring starting from the specified index.
• Example:

String substring = str.substring(7); // substring is "World!"

(4) substring(int beginIndex, int endIndex):


1. Returns a substring from the beginIndex to the endIndex.
2. Example:

String sub = str.substring(7, 12); // sub is "World"

(5) equals(Object obj):


• Compares the content of two strings for equality.
• Example:

String anotherStr = "Hello, World!";


boolean isEqual = str.equals(anotherStr); // isEqual is true

(6) equalsIgnoreCase(String anotherString):


• Compares two strings ignoring case.
• Example:

String s1 = "Hello";
String s2 = "HELLO";
boolean isEqual = s1.equalsIgnoreCase(s2);
// isEqual is true

(7) compareTo(String anotherString):


• Compares two strings lexicographically.
• Example:

String str1 = "apple";


String str2 = "banana";
int result = str1.compareTo(str2); // result is a negative value (-1 in this
case)

(8) toUpperCase() and toLowerCase():


• Converts the string to upper or lower case, respectively.
• Example:

String upperCaseStr = str.toUpperCase(); // upperCaseStr is "HELLO,


WORLD!"
String lowerCaseStr = str.toLowerCase(); // lowerCaseStr is "hello,
world!"

(9) trim():
• Removes leading and trailing whitespaces.
• Example:

String withSpaces = " Hello, World! ";


String trimmedStr = withSpaces.trim(); // trimmedStr is "Hello, World!"

(10) startsWith(String prefix) and endsWith(String suffix):


• Checks if the string starts or ends with the specified prefix or suffix.
• Example:

boolean startsWithHello = str.startsWith("Hello"); // true


boolean endsWithWorld = str.endsWith("World!"); // true

(11) indexOf(String str):


• Returns the index of the first occurrence of the specified substring.
• Example:

int indexOfComma = str.indexOf(",");


// indexOfComma is 5

(12) replace(char oldChar, char newChar):


• Replaces all occurrences of a specified character.
• Example:

String replacedStr = str.replace('o', 'x');


// replacedStr is "Hellx, Wxrld!"

(13) concat(String str):


• Concatenates the specified string to the end of the current string.
• Example:

String concatStr = str.concat(" How are you?");


// concatStr is "Hello, World! How are you?"

(14) startsWith(String prefix, int toffset) and endsWith(String suffix):


• Checks if the string starts or ends with the specified prefix or suffix,
considering a specified starting offset.
• Example:

boolean startsWithWorld = str.startsWith("World", 7); // true


boolean endsWithHello = str.endsWith("Hello"); // false
These are just a few examples of the many methods provided by the String class
in Java. Each method serves a specific purpose, allowing developers to
manipulate and work with strings effectively.

Example:
public class StringFunctionsExample {

public static void main(String[] args) {


// Creating a string
String originalStr = "Hello, World!";

// 1. length()
int length = originalStr.length();
System.out.println("Length of the string: " + length);

// 2. charAt(int index)
char charAtIndex = originalStr.charAt(7);
System.out.println("Character at index 7: " + charAtIndex);

// 3. substring(int beginIndex)
String substring = originalStr.substring(7);
System.out.println("Substring from index 7: " + substring);

// 4. substring(int beginIndex, int endIndex)


String sub = originalStr.substring(7, 12);
System.out.println("Substring from index 7 to 12: " + sub);

// 5. equals(Object obj)
String anotherStr = "Hello, World!";
boolean isEqual = originalStr.equals(anotherStr);
System.out.println("Are the strings equal? " + isEqual);

// 6. equalsIgnoreCase(String anotherString)
String caseSensitive = "Hello";
String caseInsensitive = "HELLO";
boolean isEqualIgnoreCase =
caseSensitive.equalsIgnoreCase(caseInsensitive);
System.out.println("Are the strings equal (ignoring case)? " +
isEqualIgnoreCase);
// 7. compareTo(String anotherString)
String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2);
System.out.println("Comparison result: " + result);

// 8. toUpperCase() and toLowerCase()


String upperCaseStr = originalStr.toUpperCase();
String lowerCaseStr = originalStr.toLowerCase();
System.out.println("Uppercase: " + upperCaseStr);
System.out.println("Lowercase: " + lowerCaseStr);

// 9. trim()
String withSpaces = " Hello, World! ";
String trimmedStr = withSpaces.trim();
System.out.println("Trimmed string: " + trimmedStr);

// 10. startsWith(String prefix) and endsWith(String suffix)


boolean startsWithHello = originalStr.startsWith("Hello");
boolean endsWithWorld = originalStr.endsWith("World!");
System.out.println("Starts with Hello? " + startsWithHello);
System.out.println("Ends with World!? " + endsWithWorld);

// 11. indexOf(String str)


int indexOfComma = originalStr.indexOf(",");
System.out.println("Index of comma: " + indexOfComma);

// 12. replace(char oldChar, char newChar)


String replacedStr = originalStr.replace('o', 'x');
System.out.println("String after replacing 'o' with 'x': " + replacedStr);

// 13. concat(String str)


String concatStr = originalStr.concat(" How are you?");
System.out.println("Concatenated string: " + concatStr);

// 14. startsWith(String prefix, int toffset)


boolean startsWithWorldFromIndex = originalStr.startsWith("World", 7);
System.out.println("Starts with World from index 7? " +
startsWithWorldFromIndex);
}
}
QUE: Explain the StringBuffer class in Java with all its methods with
proper examples.
ANS:
In Java, the StringBuffer class is a part of the java.lang package and is
used to represent mutable sequences of characters. Unlike the String
class, which is immutable, the StringBuffer class allows you to modify
the content of the sequence of characters it represents without
creating a new object. This makes it more efficient for operations
involving frequent modifications, such as concatenation or insertion.
Here's an overview of the StringBuffer class and its methods with
examples:
(1) Constructors:

• StringBuffer(): Creates an empty StringBuffer with an initial


capacity of 16 characters.

StringBuffer sb1 = new StringBuffer();

• StringBuffer(int capacity): Creates an empty StringBuffer with


the specified initial capacity.

StringBuffer sb2 = new StringBuffer(20);

• StringBuffer(String str): Creates a StringBuffer with the specified


initial value.

StringBuffer sb3 = new StringBuffer("Hello");

(2) length() and capacity():

• length(): Returns the number of characters in the StringBuffer.


• capacity(): Returns the current capacity of the StringBuffer.
• Example:
StringBuffer sb = new StringBuffer("Hello");
int length = sb.length(); // length is 5
int capacity = sb.capacity(); // capacity is at least 21 (initial length + 16)

(3) append():

• Appends the string representation of various types to the end of the


StringBuffer.
• Example:

StringBuffer sb = new StringBuffer("Hello");


sb.append(" World");
sb.append(123);
sb.append('!');

(4) insert():

• Inserts the string representation of various types at the specified position.


• Example:

StringBuffer sb = new StringBuffer("Hello");


sb.insert(5, " Beautiful");

(5) delete() and deleteCharAt():

• delete(int start, int end): Deletes characters from start to end - 1.


• deleteCharAt(int index): Deletes the character at the specified index.
• Example:

StringBuffer sb = new StringBuffer("Hello World");


sb.delete(6, 11); // Deletes "World"
sb.deleteCharAt(5); // Deletes the space at index 5

(6) reverse():

• Reverses the characters in the StringBuffer.


• Example:

StringBuffer sb = new StringBuffer("Hello");


sb.reverse(); // sb is now "olleH"

(7) replace():

• Replaces characters from a specified start index to an end index with a


given string.
• Example:

StringBuffer sb = new StringBuffer("Hello World");


sb.replace(0, 5, "Hi"); // Replaces "Hello" with "Hi"

(8) charAt() and setCharAt():

• charAt(int index): Returns the character at the specified index.


• setCharAt(int index, char ch): Sets the character at the specified index.
• Example:

StringBuffer sb = new StringBuffer("Hello");


char charAtIndex = sb.charAt(2); // charAtIndex is 'l'
sb.setCharAt(2, 'x'); // Changes 'l' to 'x'

(9) substring():
• Returns a new String that contains a subsequence of characters from the
StringBuffer.
• Example:
StringBuffer sb = new StringBuffer("Hello, World!");
String subString = sb.substring(7); // subString is "World!"
(10) indexOf() and lastIndexOf():

• indexOf(String str): Returns the index of the first occurrence of the


specified substring.
• lastIndexOf(String str): Returns the index of the last occurrence of the
specified substring.
• Example:

StringBuffer sb = new StringBuffer("Hello, World!");


int indexOfComma = sb.indexOf(",");
int lastIndexOfSpace = sb.lastIndexOf(" ");
(11) toString():

• Converts the StringBuffer to a String.


• Example:

StringBuffer sb = new StringBuffer("Hello");


String result = sb.toString(); // result is "Hello"

These are some of the commonly used methods provided by the StringBuffer
class in Java. It's important to note that StringBuffer is synchronized, making it
safe for use in multithreaded environments. However, if synchronization is not
needed, the non-synchronized StringBuilder class can be used, which is similar
to StringBuffer but more efficient in a single-threaded context.
Example:
public class StringBufferExample {

public static void main(String[] args) {


// Creating a StringBuffer
StringBuffer stringBuffer = new StringBuffer("Hello");

// 1. append()
stringBuffer.append(" World");
System.out.println("1. append(): " + stringBuffer);

// 2. insert()
stringBuffer.insert(5, " Beautiful");
System.out.println("2. insert(): " + stringBuffer);

// 3. delete() and deleteCharAt()


stringBuffer.delete(6, 11); // Deletes "World"
stringBuffer.deleteCharAt(5); // Deletes the space at index 5
System.out.println("3. delete() and deleteCharAt(): " + stringBuffer);

// 4. reverse()
stringBuffer.reverse();
System.out.println("4. reverse(): " + stringBuffer);

// 5. replace()
stringBuffer.replace(0, 2, "Hi"); // Replaces "He" with "Hi"
System.out.println("5. replace(): " + stringBuffer);

// 6. charAt() and setCharAt()


char charAtIndex = stringBuffer.charAt(2); // charAtIndex is 'i'
stringBuffer.setCharAt(2, 'x'); // Changes 'i' to 'x'
System.out.println("6. charAt() and setCharAt(): " + stringBuffer);

// 7. substring()
String subString = stringBuffer.substring(2, 5); // Substring from index 2 to 4
System.out.println("7. substring(): " + subString);

// 8. length() and capacity()


int length = stringBuffer.length();
int capacity = stringBuffer.capacity();
System.out.println("8. length(): " + length);
System.out.println(" capacity(): " + capacity);

// 9. indexOf() and lastIndexOf()


int indexOfHi = stringBuffer.indexOf("Hi");
int lastIndexOfX = stringBuffer.lastIndexOf("x");
System.out.println("9. indexOf() and lastIndexOf(): " + indexOfHi + ", " +
lastIndexOfX);

// 10. toString()
String result = stringBuffer.toString();
System.out.println("10. toString(): " + result);
}
}
QUE: Explain the StringJoiner class in Java with all its methods with
proper examples.
The StringJoiner class in Java is part of the java.util package and was
introduced in Java 8 as a utility for constructing sequences of characters
separated by a delimiter, with optional prefix and suffix. It is particularly useful
when you need to concatenate multiple strings with a specified separator.
Here's an overview of the StringJoiner class and its methods with examples:
(1) Constructors:
• StringJoiner(CharSequence delimiter): Creates a StringJoiner with
the specified delimiter.
StringJoiner joiner = new StringJoiner(", ");

• StringJoiner(CharSequence delimiter, CharSequence prefix,


CharSequence suffix): Creates a StringJoiner with the specified
delimiter, prefix, and suffix.

StringJoiner joiner = new StringJoiner(", ", "[", "]");

(2) add(CharSequence newElement):


• Adds a new element to the StringJoiner.
joiner.add("Apple");
joiner.add("Banana");
joiner.add("Orange");

(3) merge(StringJoiner other):


• Merges another StringJoiner into the current one.
• Example:

StringJoiner fruits = new StringJoiner(", ");


fruits.add("Apple").add("Banana");

StringJoiner moreFruits = new StringJoiner(", ");


moreFruits.add("Orange").add("Mango");
fruits.merge(moreFruits);

(4) length():
• Returns the length (number of characters) of the current sequence.
• Example:

int length = joiner.length();


(5) setEmptyValue(CharSequence emptyValue):
• Sets the default value to return if the StringJoiner is empty.
• Example:
joiner.setEmptyValue("No fruits available");
(6) toString():
• Returns the concatenated string.
• Example:

String result = joiner.toString();


Here's a complete example demonstrating the usage of StringJoiner:
import java.util.StringJoiner;
public class StringJoinerExample {
public static void main(String[] args) {
// Creating a StringJoiner with a delimiter
StringJoiner fruits = new StringJoiner(", ");

// Adding elements
fruits.add("Apple").add("Banana").add("Orange");

// Creating another StringJoiner with a delimiter and merging it


StringJoiner moreFruits = new StringJoiner(", ");
moreFruits.add("Pineapple").add("Mango");

fruits.merge(moreFruits);

// Displaying the result


System.out.println("Concatenated fruits: " + fruits);

// Getting the length


int length = fruits.length();
System.out.println("Length of concatenated string: " + length);

// Setting the default value for an empty StringJoiner


StringJoiner emptyJoiner = new StringJoiner(", ", "[", "]");
emptyJoiner.setEmptyValue("No fruits available");
System.out.println("Empty StringJoiner: " + emptyJoiner);

// Creating a StringJoiner with prefix and suffix


StringJoiner names = new StringJoiner(", ", "[", "]");
names.add("John").add("Doe").add("Alice");

// Displaying the final result


String finalResult = names.toString();
System.out.println("Concatenated names: " + finalResult);
}
}
QUE: Explain the Wrapper class in Java with proper examples of
autoboxing and unboxing.
ANS:
A Wrapper class in Java is a class whose object wraps or contains primitive data
types. When we create an object to a wrapper class, it contains a field and in
this field, we can store primitive data types. In other words, we can wrap a
primitive value into a wrapper class object. Let’s check on the wrapper classes
in Java with examples:
❖ Need of Wrapper Classes
There are certain needs for using the Wrapper class in Java as mentioned below:
1. They convert primitive data types into objects. Objects are needed if we
wish to modify the arguments passed into a method (because primitive
types are passed by value).
2. The classes in java.util package handles only objects and hence wrapper
classes help in this case also.
3. Data structures in the Collection framework, such as ArrayList and Vector,
store only objects (reference types) and not primitive types.
4. An object is needed to support synchronization in multithreading.
❖ Advantages of Wrapper Classes
1. Collections allowed only object data.
2. On object data we can call multiple methods compareTo(), equals(),
toString()
3. Cloning process only objects
4. Object data allowed null values.
5. Serialization can allow only object data.
Below are given examples of wrapper classes in Java with their corresponding
Primitive data types in Java.
❖ Primitive Data Types and their Corresponding Wrapper Class
Primitive Data Type Wrapper Class

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

boolean Boolean

❖ Autoboxing and Unboxing


1. Autoboxing
The automatic conversion of primitive types to the object of their
corresponding wrapper classes is known as autoboxing. For example –
conversion of int to Integer, long to Long, double to Double, etc.
// Java program to demonstrate Autoboxing

import java.util.ArrayList;
class Autoboxing {
public static void main(String[] args)
{
char ch = 'a';
// Autoboxing- primitive to Character object
// conversion
Character a = ch;

ArrayList<Integer> arrayList
= new ArrayList<Integer>();

// Autoboxing because ArrayList stores only objects


arrayList.add(25);

// printing the values from object


System.out.println(arrayList.get(0));
}
}

2. Unboxing
It is just the reverse process of autoboxing. Automatically converting an object
of a wrapper class to its corresponding primitive type is known as unboxing. For
example – conversion of Integer to int, Long to long, Double to double, etc.
// Java program to demonstrate Unboxing
import java.util.ArrayList;

class Unboxing {
public static void main(String[] args)
{
Character ch = 'a';

// unboxing - Character object to primitive


// conversion
char a = ch;

ArrayList<Integer> arrayList
= new ArrayList<Integer>();
arrayList.add(24);
// unboxing because get method returns an Integer
// object
int num = arrayList.get(0);

// printing the values from primitive data types


System.out.println(num);
}
}

Below is the complete example of Java Wrapper class

// Java program to demonstrate Wrapping and UnWrapping


// in Classes
import java.io.*;

class GFG {
public static void main(String[] args)
{
// byte data type
byte a = 1;

// wrapping around Byte object


Byte byteobj = new Byte(a);
// Use with Java 9
// Byte byteobj = Byte.valueOf(a);

// int data type


int b = 10;

// wrapping around Integer object


Integer intobj = new Integer(b);
// Use with Java 9
// Integer intobj = Integer.valueOf(b);

// float data type


float c = 18.6f;
// wrapping around Float object
Float floatobj = new Float(c);
// Use with Java 9
// Float floatobj = Float.valueOf(c);

// double data type


double d = 250.5;

// Wrapping around Double object


Double doubleobj = new Double(d);
// Use with Java 9
// Double doubleobj = Double.valueOf(d);

// char data type


char e = 'a';

// wrapping around Character object


Character charobj = e;

// printing the values from objects


System.out.println(
"Values of Wrapper objects (printing as objects)");
System.out.println("\nByte object byteobj: "+ byteobj);
System.out.println("\nInteger object intobj: "+ intobj);
System.out.println("\nFloat object floatobj: "+ floatobj);
System.out.println("\nDouble object doubleobj: "+ doubleobj);
System.out.println("\nCharacter object charobj: "+ charobj);

// objects to data types (retrieving data types from


// objects) unwrapping objects to primitive data
// types
byte bv = byteobj;
int iv = intobj;
float fv = floatobj;
double dv = doubleobj;
char cv = charobj;
// printing the values from data types
System.out.println("\nUnwrapped values (printing as data
types)");
System.out.println("\nbyte value, bv: " + bv);
System.out.println("\nint value, iv: " + iv);
System.out.println("\nfloat value, fv: " + fv);
System.out.println("\ndouble value, dv: " + dv);
System.out.println("\nchar value, cv: " + cv);
}
}

You might also like