Strings: Developed by
Strings: Developed by
The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new instance is
created. For mutable string, you can use StringBuffer and StringBuilder classes.
Java provides 4 types of string handling classes
String class -defined in “java.lang” package
- Once an object is created, no modifications can be done on that.
StringBuffer class and StringBuilder class– defined in “java.lang” package
- Modifications can be allowed on created object.
StringTokenizer class - defined in “java.util” package
- Used to divide the string into substrings based on tokens.
Declaration & Creation of String:
We can declare a string using String data type.
Syntax: String string_name; //Decl
Different Ways to Create String
There are many ways to create a string object in java, some of the popular ones are given below.
1. Using string literal
This is the most common way of creating string. In this case a string literal is enclosed with double quotes.
Example:String str = "abc";
When we create a String using double quotes, JVM looks in the String pool to find if any other String is
stored with same value. If found, it just returns the reference to that String object else it creates a new
String object with given value and stores it in the String pool.
2. Using new keyword
We can create String object using new operator, just like any normal java class. Java also supports the
creation & usage of arrays that contain strings .
Example
1 Developed by: Rajani, CSE Dept, RGUKT
String str = newString("abc");
char[] a = {'a', 'b', 'c'};
String str2 = newString(a);
//String( char chars[], int startIndex, int numChars)
//To create a string by specifying positions from an array of characters
char chars[]={„a‟,‟b‟,‟c‟,‟d‟,‟e‟,‟f‟};
String s=new String(chars,2,3);
Examples:-
// Construct one String from another.
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
Output:
Java
Java
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
Output:
ABCDEF
CDE
String Methods:-
Method Call Return Task Performed
Type
s2=s1.trim() String Remove white spaces at the beginning & end of the
string s1
s1.getChars(m,n,c,0) Void Extracts more than one character at a time & copies
into a character array „c‟
m-source start
n-source end
0-Target start
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println (buf);
}
}
Output:
demo
class GetBytesDemo{
public static void main(String[] args){
String str = "abc“ + ”ABC”;
byte[] b = str.getBytes();
//char[] c=str.toCharArray();
System.out.println(str);
for(int i=0;i<b.length;i++){
System.out.print(b[i]+"");
//System.out.print(c[i]+"");
}
}
}
Output:
97 98 99 65 66 67
//a b c A B C
String Comparison:
1. boolean equals(Object str)
To compare two strings for equality. It returns true if the strings contain the same characters in the
same order, and false otherwise.
2. boolean equalsIgnoreCase(String str)
To perform a comparison that ignores case differences.
Example 4
// Demonstrate equals() and equalsIgnoreCase().
Java Stringsplit method is used for splitting a String into its substrings based on the given delimiter.
Syntax
String[] split(String regex)
String[] split(String regex, int limit)
This Java String split method is used when we want the substrings to be limited. The only difference
between this method and above method is that it limits the number of strings returned after split up. For
e.g. split("anydelimiter", 3) would return the array of only 3 strings even if the delimiter is present in the
string more than 3 times.
If the limit is negative then the returned array would be having as many substrings as possible however
when the limit is zero then the returned array would be having all the substrings .
Java String join() Method
The java.lang.string.join() method concatenates the given elements with the delimiter and returns the
concatenated string.Note that if an element is null, then null is added
Example
import java.util.Arrays;
System.out.println(gfg1);
}
}
StringBuffer Class:
Java StringBuffer class is used to create mutable (modifiable) string object. A string buffer is like a String,
but can be modified.
As we know that String objects are immutable, so if we do a lot of modifications to String objects, we may
end up with a memory leak. To overcome this we use StringBuffer class.
StringBuffer class represents growable and writable character sequence. It is also thread-safe i.e. multiple
threads cannot access it simultaneously.
Every string buffer has a capacity. As long as the length of the character sequence contained in the string
buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the
internal buffer overflows, it is automatically made larger.
StringBuffer Constructors
StringBuffer ( ) : Creates an empty string buffer with the initial capacity of 16.
StringBuffer ( int capacity ) : Creates an empty string buffer with the specified capacity as
length.
StringBuffer ( String str ) : Creates a string buffer initialized to the contents of the specified
string.
Methods
The insert() method inserts the given string with this string at the given position.
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
The replace() method replaces the given string from the specified beginIndex and endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity
of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity
by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
StringBuilder
StringBuilder is same as the StringBuffer , that is it stores the object in heap and it can also be
modified .
The main difference between the StringBuffer and StringBuilder is that StringBuilder is not thread
safe. StringBuilder is fast as it is not thread safe .
Constructors:
StringBuilder demo2= new StringBuilder("Hello");
The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
Above statement is right as it modifies the value which is allowed in the StringBuilder
If the flag is false, delimiter characters serve to separate tokens. For example, if string is "hello
RGUKT" and delimiter is "", then tokens are "hello" and "RGUKT".
If the flag is true, delimiter characters are considered to be tokens. For example, if string is "hello
RGUKT" and delimiter is " ", then tokens are "hello", " " and "RGUKT".
Methods
int countTokens( ) //returns number of tokens in the string.
boolean hasMoreTokens( ) //checks whether tokens are there or not
String nextToken( ) //returns the token in the string
Example 1
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Example 2:-
import java.util.StringTokenizer;
public class StringTokenizer_Test {
static String str = "Hello,Welcome,to,Java,Programming";
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(str);
StringTokenizer st1 = new StringTokenizer(str,",");
StringTokenizer st2 = new StringTokenizer(str,",",true);
while(st.hasMoreTokens()) {
String tokens = st.nextToken();
System.out.print(tokens + "\n");
}
while(st1.hasMoreTokens()) {
String tokens = st1.nextToken();
System.out.print(tokens + "\n");
}
while(st2.hasMoreTokens()) {
String tokens = st2.nextToken();
System.out.print(tokens + "\n");
}
}
}
Output:
12 Developed by: Rajani, CSE Dept, RGUKT
Hello,Welcome,to,Java,Programming
Hello
Welcome
to
Java
Programming
Hello
,
Welcome
,
to
,
Java
,
Programming
Exercise
}
}
2. Write a Java program to read a string and return true if it ends with "ing".?
import java.util.Scanner;
class test {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String s = in.next();
13 Developed by: Rajani, CSE Dept, RGUKT
int l=s.length()-3;
if(s.substring(l).equals("ing"))
System.out.println("string ends with ing");
else
System.out.println("String not ends with ing");
}
}
3. Write a java program that reads a line of integers and then displays each integer and find the
sum of the integers (using StringTokenizer)?
import java.util.Scanner;
import java.util.*;
class Token{
static int sum=0;
public static void main(String sree[]){
Scanner s=new Scanner(System.in);
System.out.print("Enter sum of integers: ");
String str=s.next();
StringTokenizer st=new StringTokenizer(str,"+");
while(st.hasMoreTokens()){
sum=sum+Integer.parseInt(st.nextToken());
}
System.out.println("Sum of "+str+“is: "+sum);
}
}
Input:
Enter sum of integers: 10+20+30+40
Output:
Sum of 10+20+30+40 is: 100