0% found this document useful (0 votes)
58 views11 pages

Java String Class Overview and Usage

The document discusses the Java String class and StringBuffer class. String objects are immutable and represent fixed-length character sequences. StringBuffer represents growable and writable character sequences that can have characters inserted or appended. It automatically grows in size as needed. The document provides examples of creating String and StringBuffer objects, performing operations like concatenation and modification, and explains methods like append, insert, and length. It also discusses when to use String versus StringBuffer based on whether frequent modifications are needed.

Uploaded by

ghazi members
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views11 pages

Java String Class Overview and Usage

The document discusses the Java String class and StringBuffer class. String objects are immutable and represent fixed-length character sequences. StringBuffer represents growable and writable character sequences that can have characters inserted or appended. It automatically grows in size as needed. The document provides examples of creating String and StringBuffer objects, performing operations like concatenation and modification, and explains methods like append, insert, and length. It also discusses when to use String versus StringBuffer based on whether frequent modifications are needed.

Uploaded by

ghazi members
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Java String Class Lab # 4

LAB # 4

STRING CLASS

OBJECTIVE:
To Study String class and String Buffer.

THEORY:

4.1 STRINGS
In JAVA, Ordinary strings are objects of the class String. The String class is a
standard class, and it is specifically designed for creating and processing strings.

The Java platform provides the String class to create and manipulate strings.

Creating String Objects:


Just to make sure there is no confusion in your mind, a String variable is simply a
variable that stores a reference to an object of the class String. You declare a
String variable in much the same way as you define a variable of one of the basic
types. You can also initialize it in the declaration, which is generally a good idea:

This declares the variable myString as type String and initializes it with a
reference to a String object encapsulating the string “My inaugural string”. You
can store a reference to another string in a String variable, once you have
declared it, by using an assignment. For example, you can change the value
of the String variable myString to the statement:
The effect of this is illustrated in Figure

Object Oriented Programming - OOPs 1


Java String Class Lab # 4

You should also keep in mind that characters in a string are Unicode characters,
so each one typically occupies 2 bytes, with the possibility that they can be 4
bytes if you are using characters represented surrogates.

Of course, you can declare a variable of type String in a method without initializing
it:

Arrays of Strings:

You can create arrays of strings. You declare an array of String objects with the
same mechanism that you used to declare arrays of elements for the basic types.
You just use the type String in the declaration. For example, to declare an array of
five String objects, you could use the statement

It should now be apparent that the argument to the method main()is an array of
String objects because the definition of the method always looks like this:

Object Oriented Programming - OOPs 2


Java String Class Lab # 4

You could also declare an array of String objects where the initial values
determine the size of the array:

This array will have 7 elements because there are 7 initializing string literals
between the braces.

Of course, as with arrays storing elements of primitive types, you can create
arrays of strings with any number of dimensions. You can try out arrays of
strings with a small example.

Let’s create a program to generate your lucky star for the day:

Output:

Operations on Strings:

There are many kinds of operations that can be performed on strings, but let’s
start with one you have used already, joining two or more strings together to
form a new, combined string. This is often called string concatenation.
Joining Strings:

To join two String objects to form a new, single string you use the +operator,
just as you have been doing with the argument to the println()method in the
program examples thus far. The simplest use of this is to join two strings
together:

Object Oriented Programming - OOPs 3


Java String Class Lab # 4

This will join the two strings on the right of the assignment and store the result
in the String variable myString. The +operation generates a completely new
String object that is separate from the two original String objects that are the
operands, and this new object is stored in myString. Of course, you also use
the +operator for arithmetic addition, but if either of the operands for the
+operator is a String object or literal, then the compiler will interpret the
operation as string concatenation and will convert the operand that is not a
String object to a string. Here’s an example of concatenation strings
referenced by String variables:

If a String variable that you use as one of the operands to + contains null,
then this will automatically be converted to the string “null”. So if the month
variable contained null instead of a reference to the string “December”, the
result of the concatenation with date would be the string “31st null”. Note that
you can also use the +=operator to concatenate strings. For example:

String Methods:
Here are the list methods supported by String class:

Object Oriented Programming - OOPs 4


Java String Class Lab # 4

Program#1
This program uses different string classes.

public class StringClass{


public static void main (String[] args){

String s1 = new String("ABC");


String s2 = new String("ABC");
String s3 ="ABC";
String s4 ="ABC";
String s5 = new String("abc");

[Link]("\t\t\ts1="+s1);
[Link]("\t\t\ts2="+s2);
[Link]("\t\t\ts3="+s3);

Object Oriented Programming - OOPs 5


Java String Class Lab # 4

[Link]("\t\t\ts4="+s4);
[Link]("\t\t\ts5="+s5);

[Link]("\n** == **");
[Link]("\ns1==s2 -> "+(s1==s2));
[Link]("s1==s3 -> "+(s1==s3));
[Link]("s3==s4 -> "+(s3==s4));

//Equals
[Link]("\n**Equals**");
[Link]("[Link](s2) -> "+[Link](s2));
[Link]("[Link](s5) -> "+[Link](s5));
[Link]("XYZ".equals("XYZ"));

//Equals Ignore Case


[Link]("\n**Equals Ignore Case**");
[Link]([Link](s5));
[Link]("XYZ".equalsIgnoreCase("xyz"));

//Starts With
[Link]("\n**Starts With**");
[Link]([Link]("A"));

//Ends With
[Link]("\n**Ends With**");
[Link]([Link]("C"));
[Link]("SSUET Karachi".endsWith("i"));

//Compare To
[Link]("\n**Compare To**");
[Link]([Link](s2));

//Character At
[Link]("\n**Character At**");
[Link]([Link](0));

//Length
[Link]("\n**Length**");
[Link]([Link]());

//To Lower Case


[Link]("\n**To Lower Case**");
[Link]([Link]());

//Index Of
[Link]("\n**Index Of**");
[Link]([Link]('A'));

//last Index Of
[Link]("\n**last Index Of**");

Object Oriented Programming - OOPs 6


Java String Class Lab # 4

[Link]([Link]('A'));

//Sub String
[Link]("\n**Sub String**");
[Link]([Link](1,2));

//Replace
[Link]("\n**Replace**");
[Link]([Link]('A','Z'));

}
}

Output:

Object Oriented Programming - OOPs 7


Java String Class Lab # 4

Note: The String class is immutable, so that once it is created a String object
cannot be changed. If there is a necessity to make a lot of modifications to
Strings of characters then you should use String Buffer & String Builder
Classes.

4.2 STRING BUFFER

StringBuffer is a peer class of String that provides much of the functionality


of strings. As you know, String represents fixed-length, immutable character
sequences. In contrast, StringBuffer represents growable and writeable
character sequences. StringBuffer may have characters and substrings
inserted in the middle or appended to the end. StringBuffer will automatically
grow to make room for such additions and often has more characters pre
allocated than are actually needed, to allow room for growth.

StringBuffer Constructors:

StringBuffer defines these three constructors:

StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
The default constructor (the one with no parameters) reserves room for 16
characters without reallocation. The second version accepts an integer
argument that explicitly sets the size of the buffer. The third version accepts a
String argument that sets the initial contents of the StringBuffer object and
reserves room for 16 more characters without reallocation. StringBuffer
allocates room for 16 additional characters when no specific buffer length is
requested, because reallocation is a costly process in terms of time. Also,
frequent reallocations can fragment memory. By allocating room for a few

Object Oriented Programming - OOPs 8


Java String Class Lab # 4

extra characters, StringBuffer reduces the number of reallocations that take


place.

Program#2
Creating String Buffer Objects. length, capacity, ensureCapacity, setLength,
append, insert, charAt, setChatAt and toString Functions.

public class str{


public static void main (String[] args){

StringBuffer s1 = new StringBuffer("ABC");


StringBuffer s2 = new StringBuffer();
StringBuffer s3 = new StringBuffer(50); // Capacity 50

[Link]("s1= "+s1); //Print data


[Link]("[Link]() = "+[Link]()); //Print length = 3
[Link]("[Link]() = "+[Link]()); //print capacity. Default
16 + 3 = 19
[Link]("[Link]() = "+[Link]()); //print length = 0
[Link]("[Link]() = "+[Link]()); //print default capacity
16
[Link]("[Link]() = "+[Link]()); //Print 50

//Append
[Link]("**\nAppend**");
[Link]("Capacity of S2 = "+[Link]()); //Capacity remain 16
[Link]("Length of S2 = "+[Link]());
[Link]("ABCDEF");
[Link](s2);
[Link]("Capacity of S2 = "+[Link]()); //Capacity remain 16
[Link]("Length of S2 = "+[Link]());
[Link]("GHIJKLMNOP");
[Link]("Capacity of S2 = "+[Link]()); //Capacity remain 16
[Link]("Length of S2 = "+[Link]());
[Link]("Q");
[Link]("Capacity of S2 = "+[Link]()); //Capacity 34 after
length 16+
[Link]("Length of S2 = "+[Link]());

//Character At
[Link]("\n**Character At**");
[Link]([Link](0));

//Set Character At
[Link]("\n**Set Character At**");
[Link](s1); //Original Value
[Link](0,'X');
[Link](s1); //After Change

Object Oriented Programming - OOPs 9


Java String Class Lab # 4

//To String
[Link]("\n**To String**");
[Link](s1); //Original Value in String Buffer
String s = [Link]();
[Link](s); // Convert from String Buffer to String
}
}

Output:

Object Oriented Programming - OOPs 10


Java String Class Lab # 4

LAB TASK

[Link] a java program to compare any two strings lexicographically and to


get the character at the 3 and 4 index within the String.
Sample Output:
String 1: This is Exercise 1
String 2: This is Exercise 2
"This is Exercise 1" is less than "This is Exercise 2"
The character at position 0 is T
The character at position 4 is s

2. Write a Java program to convert all the characters in a string to lowercase.


Sample Output:
Original String: The Quick BroWn FoX!
String in lowercase: the quick brown fox!

3. A PALINDROME is a word which has SAME SPELLING whether it is


read from Left to Right or from Right to Left. Example: MOM, DAD, DEED,
PEEP and NOON. Other words which are not PALINDROME are HELLO,
DOOR and FEET. Write a program that can read a String as user input in
Capital Letters and then Print YES as Output if the Input is a PALINDROME
otherwise NO.

[Link] a program that extracts username & domain information from Email
address.
Example:
if the email address is "user@[Link]", your program will print
User name = user              
Domain = my                             
Extension = com

Object Oriented Programming - OOPs 11

Common questions

Powered by AI

The immutability of the Java String class means that once a String object is created, it cannot be altered. This feature influences memory management by allowing the Java Virtual Machine (JVM) to optimize the use of memory, through the implementation of a string pool. When a new string is created, the JVM checks the pool to see if an equivalent string already exists. If it does, the new variable will point to the existing object, saving memory space. The immutability also ensures thread safety when strings are shared across multiple threads without requiring additional synchronization .

StringBuffer is used in Java when frequent modifications to strings are necessary, offering a mutable sequence of characters. Unlike the immutable String, modifications to StringBuffer (such as append, insert, and delete operations) do not result in the creation of new objects with every change. This reduces the overhead and fragmentation associated with multiple strings, leading to better performance in scenarios where numerous modifications are made .

In Java, string concatenation is the process of joining two or more strings to form a new, single one. This is achieved using the '+' operator. When used between two String objects or a String and another operand, it converts the non-String operand to a String (if applicable) and then concatenates them. The result is a new String object. This operation generates a completely new String, distinct from the original operands .

In Java, arrays of strings are created similarly to arrays of basic data types, using the `new` keyword and specifying the type as `String`. For instance, `String[] array = new String[5];` creates an array of five String objects. Arrays can be initialized at creation using brace-enclosed lists of strings. Being able to store sequences of strings efficiently, this functionality is vital for handling structured or grouped textual data, enabling batch operations, like sorting and searching, across multiple strings .

To modify strings frequently without the overhead of creating new objects, Java provides the StringBuffer and StringBuilder classes. They are mutable sequences of characters allowing frequent modifications without creating new objects for each change. StringBuffer is synchronized for thread safety, whereas StringBuilder is non-synchronized, offering better performance where thread safety is not an issue. This use contrasts with the String class, where each modification results in creating a new, immutable object .

The main difference between StringBuffer and StringBuilder is synchronization. StringBuffer is synchronized, making it safe for use in a multi-threaded environment where multiple threads might access the same StringBuffer object. In contrast, StringBuilder is not synchronized, providing better performance in single-threaded scenarios due to lower overhead. Thus, StringBuffer is suited for applications requiring thread safety, whereas StringBuilder is preferred in performance-critical, single-threaded contexts .

The 'capacity' in the StringBuffer class refers to the number of characters it can store before needing to reallocate more space. By preallocating space for additional characters (default is 16 extra characters), StringBuffer reduces the frequency of reallocations, which are time-consuming operations that can fragment memory. This feature enhances performance by minimizing the overhead associated with memory reallocation during continuous modifications .

The `String.indexOf()` method in Java returns the index of the first occurrence of a specified character or substring within the string, or -1 if not found. It's useful for cases where the starting position of a substring within a text needs to be identified, such as searching in logs. `String.lastIndexOf()`, on the other hand, returns the index of the last occurrence of a character or substring, advantageous in scenarios requiring the last position, like finding the last period in a file path before the suffix .

Java String class handles character encoding with Unicode, which allows for the representation of a vast array of global scripts and symbols, supporting internationalization. Each character in a Java String is a Unicode character, typically occupying 2 bytes, with support for 4 bytes when using surrogate pairs. This extensive character repertoire enables Java applications to be written and run on any platform, using any language .

`String.equals()` in Java compares the contents of two strings for equality, checking each character. In contrast, the '==' operator compares the memory references of the objects, determining if the two variables point to the same object in memory. A common pitfall is assuming '==' checks for content equality, potentially causing bugs if two different objects with identical content are seen as unequal .

You might also like