MCS024 : Question 3 (a) String class Vs String Buffer class in Java | June 2023 Paper Solution

mcs024 june 2023 Paper

Question 3. (a) What is string class ? How is it different from String Buffer class ? Write a java program to find the length of a given string.


String Class:
The String class in Java is used to work with text-based data. It represents a sequence of characters, such as words or sentences. Once a String object is created, its value cannot be changed. In other words, it is "immutable". We can perform operations like concatenation (joining strings), comparison, and extracting substrings with the String class.

String Buffer Class:
The String Buffer class is similar to the String class as it also stores sequences of characters. However, unlike String objects, String Buffer objects are "mutable," meaning their values can be modified after creation. The String Buffer class provides methods to append (add to the end), insert, delete, and modify characters within the string. It is more efficient when we need to make frequent changes to a string.

Difference between String and String Buffer:

1. Mutability: String objects are fixed and cannot be changed once created, while StringBuffer objects can be modified.

2. Performance: Since String objects are immutable, when we modify a String, it creates a new String object in memory. This can be inefficient if we perform many modifications. String Buffer, being mutable, allows us to modify the string without creating new objects, making it more efficient for frequent modifications.

Java Program to Find the Length of a Given String:
Here's a simple Java program that calculates the length of a given string:

public class StringLengthExample {
public static void main(String[] args) {
String str = "Welcome to Lawtantra!";
int length = str.length();
System.out.println("The length of the string is: " + length);

In this program, we have a string variable named "str", which holds the value "
Welcome to Lawtantra!". We use the "length()" method of the String class to find the length of the string and store it in the "length" variable. Finally, we display the length on the console using "System.out.println()".

When you run this program, it will output: "The length of the string is: 13". This indicates that the given string has a length of 13 characters.

Post a Comment