0% found this document useful (0 votes)
233 views9 pages

Java LAB 6 String

The document discusses the Java String class and StringBuffer class. It provides examples of creating Strings using literals and constructors. Strings are immutable while StringBuffer is mutable and growable. The document also includes code examples that demonstrate various String and StringBuffer methods like append, insert, length, compareTo, substring etc. It concludes with tasks to extract email details from a string and check if a string is a palindrome.

Uploaded by

shah rizvi
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
233 views9 pages

Java LAB 6 String

The document discusses the Java String class and StringBuffer class. It provides examples of creating Strings using literals and constructors. Strings are immutable while StringBuffer is mutable and growable. The document also includes code examples that demonstrate various String and StringBuffer methods like append, insert, length, compareTo, substring etc. It concludes with tasks to extract email details from a string and check if a string is a palindrome.

Uploaded by

shah rizvi
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 9

Java String Class Lab # 6

LAB # 6

JAVA STRING CLASS

OBJECTIVE
To Study Java String class and Java String Buffer.

THEORY
Strings, which are widely used in Java programming, are a sequence of characters. In
the Java programming language, strings are objects.
The Java platform provides the String class to create and manipulate strings.

Creating Strings:
The most direct way to create a string is to write:
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String
object with its value in this case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword and
a constructor. The String class has eleven constructors that allow you to provide the
initial value of the string using different sources, such as an array of characters:
public class StringDemo{

public static void main(String args[]){


char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
This would produce following result:
hello.

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 alot of modifications to Strings of
characters then you should use String Buffer & String Builder Classes.

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

Object Oriented Programming - OOPs 1


Java String Class Lab # 6

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");
Object Oriented Programming - OOPs 2
Java String Class Lab # 6

System.out.println("\t\t\ts1="+s1);
System.out.println("\t\t\ts2="+s2);
System.out.println("\t\t\ts3="+s3);
System.out.println("\t\t\ts4="+s4);
System.out.println("\t\t\ts5="+s5);

System.out.println("\n** == **");
System.out.println("\ns1==s2 -> "+(s1==s2));
System.out.println("s1==s3 -> "+(s1==s3));
System.out.println("s3==s4 -> "+(s3==s4));

//Equals
System.out.println("\n**Equals**");
System.out.println("s1.equals(s2) -> "+s1.equals(s2));
System.out.println("s1.equals(s5) -> "+s1.equals(s5));
System.out.println("XYZ".equals("XYZ"));

//Equals Ignore Case


System.out.println("\n**Equals Ignore Case**");
System.out.println(s1.equalsIgnoreCase(s5));
System.out.println("XYZ".equalsIgnoreCase("xyz"));

//Starts With
System.out.println("\n**Starts With**");
System.out.println(s1.startsWith("A"));

//Ends With
System.out.println("\n**Ends With**");
System.out.println(s1.endsWith("C"));
System.out.println("SSUET Karachi".endsWith("i"));

//Compare To
System.out.println("\n**Compare To**");
System.out.println(s1.compareTo(s2));

//Character At
System.out.println("\n**Character At**");
System.out.println(s1.charAt(0));

//Length
System.out.println("\n**Length**");
System.out.println(s1.length());

//To Lower Case


System.out.println("\n**To Lower Case**");
System.out.println(s1.toLowerCase());

//Index Of
System.out.println("\n**Index Of**");
System.out.println(s1.indexOf('A'));

//last Index Of
System.out.println("\n**last Index Of**");
System.out.println(s1.lastIndexOf('A'));

Object Oriented Programming - OOPs 3


Java String Class Lab # 6

//Sub String
System.out.println("\n**Sub String**");
System.out.println(s1.substring(1,2));

//Replace
System.out.println("\n**Replace**");
System.out.println(s1.replace('A','Z'));

}
}

Output:

Object Oriented Programming - OOPs 4


Java String Class Lab # 6

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
Object Oriented Programming - OOPs 5
Java String Class Lab # 6

of time. Also, frequent reallocations can fragment memory. By allocating room for a
few 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

System.out.println("s1= "+s1); //Print data


System.out.println("s1.length() = "+s1.length()); //Print length = 3
System.out.println("s1.capacity() = "+s1.capacity()); //print capacity. Default
16 + 3 = 19
System.out.println("s2.length() = "+s2.length()); //print length = 0
System.out.println("s1.capacity() = "+s2.capacity()); //print default capacity 16
System.out.println("s3.length() = "+s3.capacity()); //Print 50

//Append
System.out.println("**\nAppend**");
System.out.println("Capacity of S2 = "+s2.capacity()); //Capacity remain 16
System.out.println("Length of S2 = "+s2.length());
s2.append("ABCDEF");
System.out.println(s2);
System.out.println("Capacity of S2 = "+s2.capacity()); //Capacity remain 16
System.out.println("Length of S2 = "+s2.length());
s2.append("GHIJKLMNOP");
System.out.println("Capacity of S2 = "+s2.capacity()); //Capacity remain 16
System.out.println("Length of S2 = "+s2.length());
s2.append("Q");
System.out.println("Capacity of S2 = "+s2.capacity()); //Capacity 34 after length 16+
System.out.println("Length of S2 = "+s2.length());

//Character At
System.out.println("\n**Character At**");
System.out.println(s1.charAt(0));

//Set Character At
System.out.println("\n**Set Character At**");
System.out.println(s1); //Original Value
s1.setCharAt(0,'X');
System.out.println(s1); //After Change

//To String
System.out.println("\n**To String**");
System.out.println(s1); //Original Value in String Buffer
String s = s1.toString();
System.out.println(s); // Convert from String Buffer to String
}
}

Object Oriented Programming - OOPs 6


Java String Class Lab # 6

Output:

Object Oriented Programming - OOPs 7


Java String Class Lab # 6

LAB TASK

Task 1:
Write a program that extracts username and the domain information from an E-mail
address. For example, if the email address is "[email protected]", your program
will print
                    User name        = user              
                    Domain             = mydomain                             
                    Extension          = com

SOURCE CODE:
package javaapplication2;
import java.util.Scanner;
public class Domain {
public static void main(String[] args) {
Scanner inp=new Scanner(System.in);
String str=inp.nextLine();
int a=str.indexOf('@');
String str2=str.substring(0, a);
System.out.println("Username="+str2);
int b=str.indexOf('.', a+1);
String str3=str.substring(a+1, b);
System.out.println("Domain="+str3);
String str4=str.substring(b+1);
System.out.println("Extension="+str4);
}

OUTPUT:

TASK 2:
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 take a String as user input in Capital Letters and then Print
YES as Output if the Input is a PALINDROME otherwise NO.

Object Oriented Programming - OOPs 8


Java String Class Lab # 6

SOURCE CODE :

package javaapplication2;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner inp=new Scanner(System.in);
StringBuffer str=new StringBuffer();
str.append(inp.nextLine());
StringBuffer str1=new StringBuffer();
char ch;
for(int a=str.length()-1;a>=0;a--){
ch=str.charAt(a);
str1.append(ch); }
String sb=String.valueOf(str);
String sb1=String.valueOf(str1);
if(sb.equals(sb1))
{
System.out.println("(YES)palindrome");
}
else{
System.out.println("(NO)not palindrome");
}}}

OUTPUT:

CONCLUSION :
String is class which takes input in group of characters and uses class method to
change according to user. String class has many overloaded methods. It is very useful
for advance programming.

Object Oriented Programming - OOPs 9

You might also like