7 Strings

Download as pdf or txt
Download as pdf or txt
You are on page 1of 80

String

What you’ll Learn

● Introduction to String class


● String class constructors
● String class methods
● Immutability nature of String class
● Problems in String class
● Introduction to String Builder and String Buffer
● String Builder and Buffer methods
● Differences among three classes
String

● A pre-defined class available in java.lang package


● It is basically an object that represents sequence of char values.
● An array of characters works same as string.
char[ ]  ch = {'e’,'t','h','n','u','s'}; 
● Syntax
<String_Type> <string_variable> = “<sequence_of_string>”;
String str="Hello!";
Ways to Create String
Using String literal:
You can create String objects with String literal
String s1="Welcome";
String s2="Welcome"; //It doesn't create a new instance
Using new keyword:
This is the common way to create a String object in java.
String str1= new String("Hello!");
Memory Allocation
String Object is created, two objects will be created
● The Heap Area
● The String constant pool
The String object reference always points to heap area object.
Example: String str = “Ethnus”;
0 1 2 3 4 5 6
E t h n u s \0

0x23452 0x23453 0x23454 0x23455 0x23456 0x23457 0x23458


String class constructors

1. String s1 = new String( );


2. String s2 = new String(String literal);
3. char[] ch1 = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’};
String s3 = new String(ch1);
String Methods

Method Description
char charAt(int index) returns char value for the particular index

int length() returns string length


String substring(int beginIndex) returns substring for given begin index.
boolean equals(Object another) checks the equality of string with the given object.
String concat(String str) concatenates the specified string.
String replace(char old, char replaces all occurrences of the specified char value.
new)
int indexOf(int ch) returns the specified char value index.
charAt() - Example
The java string charAt() method returns a char value at the given
index number

class Main {
public static void main(String args[]){
String name="codemithra";
char ch=name.charAt(4);
System.out.println(ch);
}
}
length() - Example
The java string length() method length of the string. It returns count of
total number of characters

class Main {
public static void main(String args[]){
String s1="ETHNUS";
String s2="Codemithra.com";
System.out.println("string length is: "+s1.length());//6 is
the length of ETHNUS string
System.out.println("string length is: "+s2.length()); //14
}} is the length of Codemithra.com string
subString() - Example

The java string substring() method returns a part of the string

public class Main {


public static void main(String[] args) {
String s1="Ethnus and Codemithra";
String substr = s1.substring(0);//Starts with 0 and goes to end
System.out.println(substr);
String substr2 = s1.substring(5,10);//Starts from 5 and
goes to 10
System.out.println(substr2);
} }
concat() - Example
The java string concat() method combines specified string

public class Main{


public static void main(String args[]){
String s1="Today you";
System.out.println(s1);
s1=s1.concat(" will learn Java String");
System.out.println(s1);
}
}
contains() - Example
The java string contains() method searches the sequence of characters
in this string

class Main{
public static void main(String args[]){
String name="what do you know about me";
System.out.println(name.contains("do you know"));
System.out.println(name.contains("about"));
System.out.println(name.contains("hello"));
}
}
endsWith - Example
The java string endsWith() method checks if this string ends with
given suffix

class Main{
public static void main(String args[]){
String s1="java by ethnus";
System.out.println(s1.endsWith("s"));
System.out.println(s1.endsWith("ethnus"));
}
}
Equals - Example
The String equalsIgnoreCase() method compares the two given strings
on the basis of content of the string irrespective of case of the string
public class Main{
public static void main(String args[]){
String s1="codemithra";
String s2="codemithra";
String s3="CODEMITHRA";
String s4="ethnus";
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
} }
indexOf()
The java string indexOf() method returns index of given character value or substring. 
If it is not found, it returns -1. The index counter starts from zero.
There are 4 types of indexOf method in java

Method Description

int indexOf(int ch) returns index position for the given char value

int indexOf(int ch, int fromIndex) returns index position for the given char value and
from index

int indexOf(String substring) returns index position for the given substring
int indexOf(String substring, int returns index position for the given substring and
fromIndex) from index
indexOf() - Example
public class Main{
public static void main(String args[]){
String s1="this is index of example";
int index1=s1.indexOf("is");
int index2=s1.indexOf("index");
System.out.println(index1+" "+index2);
int index3=s1.indexOf("is",4);
System.out.println(index3);
int index4=s1.indexOf('s');
System.out.println(index4);
}
}
indexOf(substring) - Example
This method takes substring as an argument and returns index of
first character of the substring.

class Main {
public static void main(String[] args) {
String s1 = "This is indexOf method";
int index = s1.indexOf("method");
System.out.println("index of substring "+index);
}
}
isEmpty - Example
The java string isEmpty() method checks if this string is empty or
not. It returns true, if length of string is 0 otherwise false

class Main{
public static void main(String args[]){
String s1="";
String s2="ethnus";
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}
}
lastIndexOf() - Example
The java string lastIndexOf() method returns last index of the given
character value or substring. If it is not found, it returns -1

class Main{
public static void main(String args[]){
String s1="this is index of example";
int index1=s1.lastIndexOf('s');
System.out.println(index1);
}
}
replaceAll() - Example
The java string replaceAll() method returns a string replacing all the
sequence of characters matching regex and replacement string.

class Main{
public static void main(String args[]){
String s1="codemithra is a very good learning platform";
String replaceString=s1.replaceAll("a","e");
System.out.println(replaceString);
}
}
toLowerCase() - Example
The java string toLowerCase() method returns the string in lowercase
letter

class Main{
public static void main(String args[]){
String s1="ETHNUS HELLO guYS";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}
}
toUpperCase() - Example
The java string toUpperCase() method returns the string in uppercase
letter.

class Main{
public static void main(String args[]){
String s1="hello guys";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}
}
trim() - Example
The java string trim() method eliminates leading and trailing spaces.
The unicode value of space character is '\u0020'.

public class Main{


public static void main(String args[]){
String s1=" hello string ";
System.out.println(s1+"ethnus");
System.out.println(s1.trim()+"ethnus");
}
}
Number to String - Example
class Main {
public static void main(String[] args) {
double d = 858.48;
String s = Double.toString(d);
int dot = s.indexOf('.');
System.out.println(dot + " digits " + "before decimal point.");
System.out.println( (s.length() - dot - 1) + " digits after
decimal point.");
}
}
Immutability

● string objects are immutable


● Immutable simply means unchangeable
● Once string object is created, its data or state can't be changed
● However, a new string object can be created
● String constant pool : The string objects will be stored in SCP when using
literals
● Heap / Non-constant pool : The string objects will be stored in SCP when
using new keyword
● Note : If there is any change in the content, a new string object will be
created with new changes. If there is no change, existing objects will be re
used. This behavior is known as immutability
Scenario 1

Creating String using new Keyword


String s1 = new String(“Hello”);

String s2 = new String(“hello”);


String s3 = new String(“Hello”);

String objects will be created in heap area


When using new keyword
Scenario 2

Creating String using literals


String s1 = “Hello”;

String s2 = “hello”;
String s3 = “Hello”;
String objects will be created in String
Constant Pool area when using
literals
Scenario 1
Scenario 3

String s1 = new String(“Hello”);

//there is a change in the content


String s2 = s1.toLowercase();

//there is no change, back to first form


String s3 = s1.toUppercase();
Scenario 1
Scenario 4

String s1 = “Hello”;

//there is a change in the content


String s2 = s1.replace(‘H’, ‘h’);

//there is no change, back to first form


String s3 = s1.replace(‘h’, ‘H’);
Why String is immutable?
● If it is mutable,when string object content is changed, there is always a risk of
losing the previous values. Only the lastly updated value will exist and visible
● Thus,only if the string object is immutable, it won’t affect the changes in the
same string object
● Demerits
● Since it is immutable, everytime there is change in the content, it ends
up creating new string objects
● Leads to Memory Leak issue
● To overcome this, two different mutable classes are introduced
● String Builder & String Buffer
String Builder & Mutable nature

● It’s a mutable class


● Does not create further objects to record the changes
● Changes happen in the same object that is already existing
● Has its own constructors and methods
● However, the operations performed are similar to that in String class
● Note : StringBuilder objects can be created only using new keyword
● String literals are not available in this class. If used, it will again be String class
only.
Scenario 5

StringBuilder sb = new StringBuilder(“Hello”);

//append method merge the strings


sb.append(“World”);

System.out. println(sb);
StringBuilder Constructor

Constructor Description
creates an empty string Builder with the initial
StringBuilder() capacity of 16.
creates a string Builder with the specified
StringBuilder(String str) string.
creates an empty string Builder with the
StringBuilder(int length) specified capacity as length.
StringBuilder Methods
Method Description
is used to append the specified string with this string. The append()
public StringBuilder append(String s) method is overloaded like append(char), append(boolean),
append(int), append(float), append(double) etc.
is used to insert the specified string with this string at the specified
position. The insert() method is overloaded like insert(int, char),
public StringBuilder insert(int offset, String s)
insert(int, boolean), insert(int, int), insert(int, float), insert(int,
double) etc.
public StringBuilder replace(int startIndex, int is used to replace the string from specified startIndex and
endIndex, String str) endIndex.
public StringBuilder delete(int startIndex, int
endIndex) is used to delete the string from specified startIndex and endIndex.
public StringBuilder reverse() is used to reverse the string.
public int capacity() is used to return the current capacity.
StringBuilder Methods

Method Description
public void ensureCapacity(int is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.
public char charAt(int index) is used to return the character at the specified position.
is used to return the length of the string i.e. total number of
public int length() characters.
public String substring(int
beginIndex) is used to return the substring from the specified beginIndex.
public String substring(int is used to return the substring from the specified beginIndex
beginIndex, int endIndex) and endIndex.
StringBuilder append() - Example
class Main{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");
System.out.println(sb);
}
}
StringBuilder insert() - Example
class Main{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");
System.out.println(sb);
}
}
StringBuilder replace() - Example
class Main{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);
}
}
StringBuilder delete() - Example
class Main{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);
}
}
StringBuilder reverse() - Example
class Main{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);
}
}
StringBuilder capacity() - Example
The capacity() method of StringBuilder class returns the current
capacity of the Builder. The default capacity of the Builder is 16.

class Main{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());
sb.append("Hello");
System.out.println(sb.capacity());
sb.append("java is my favourite language");
System.out.println(sb.capacity());
}
}
StringBuilder ensureCapacity() - Example
The ensureCapacity() method of StringBuilder class ensures that the
given capacity is the minimum to the current capacity. If it is greater than
the current capacity, it increases the capacity by (oldcapacity*2)+2
class Main{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());
sb.append("Hello");
System.out.println(sb.capacity());
sb.append("java is my favourite language");
System.out.println(sb.capacity());
sb.ensureCapacity(10);
System.out.println(sb.capacity());
sb.ensureCapacity(50);
System.out.println(sb.capacity());
} }
String Buffer & Mutable nature

● It’s a mutable class


● Does not create further objects to record the changes
● Changes happen in the same object that is already existing
● Has its own constructors and methods
● However, the operations performed are similar to that in String class
● Note : StringBuffer objects can be created only using new keyword
● String literals are not available in this class. If used, it will again be String class
only.
Scenario 6

StringBuffer sb = new StringBuffer(“Hello”);

//append method merge the strings


sb.append(“World”);

System.out. println(sb);
String Buffer constructors

Constructor Description
creates an empty string buffer with the initial
StringBuffer() capacity of 16.
creates a string buffer with the specified
StringBuffer(String str) string.
StringBuffer(int creates an empty string buffer with the
capacity) specified capacity as length.
StringBuffer Methods
Method Description
is used to append the specified string with this string. The
append() method is overloaded like append(char),
append(boolean), append(int), append(float),
public StringBuffer append(String s) append(double) etc.
is used to insert the specified string with this string at the
specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int), insert(int,
public StringBuffer insert(int offset, String s) float), insert(int, double) etc.
public StringBuffer replace(int startIndex, is used to replace the string from specified startIndex and
int endIndex, String str) endIndex.
public StringBuffer delete(int startIndex, int is used to delete the string from specified startIndex and
endIndex) endIndex.
public StringBuffer reverse() is used to reverse the string.
public int capacity() is used to return the current capacity.
String Buffer Methods

Method Description
public void ensureCapacity(int is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.
public char charAt(int index) is used to return the character at the specified position.
is used to return the length of the string i.e. total number
public int length() of characters.
public String substring(int is used to return the substring from the specified
beginIndex) beginIndex.
public String substring(int is used to return the substring from the specified
beginIndex, int endIndex) beginIndex and endIndex.
String VS Stringbuilder

String StringBuilder StringBuffer


Immutable Mutable Mutable
String is slow and
consumes more
memory when you
concat too many
strings because every Fast and consumes less
time it creates new memory when you concat Fast and consumes less memory
instance strings when you concat strings
Methods are not Methods are not
synchronized synchronized Methods are synchronized
Question: 01

String constant pool allocates its memory


in

A. Stack
B. Heap
C. Data Segment
D. Register
Question: 02

class Main{ A. True


public static void main(String args[]){
False
String str = "Hello";
String str1 = "Hello"; B. True
String str2 = new String("Hello"); True
System.out.println(str == str1);
C. False
System.out.println(str == str2);
} True
} D. False
False
Question: 03

class Main{
public static void main(String args[]){
String str1 = "Hello";
String str2 = "Hello"; A. True False True
String s1 = new String("Hello"); B. True False False
String s2 = new String("Hello");
C. False True False
System.out.println(str1 == str2);
System.out.println(str2 == s1); D. False False True
System.out.println(s1 == s2);
}
}
Question: 04

class Main{ A. True


public static void main(String args[]){
False
String s1 = new String("Nepotism");
String s2 = new String("Nepotism"); B. True
System.out.println(s1 == s2); True
System.out.println(s1.equals(s2));
C. False
}
} True
D. False
False
Question: 05

class Main{
public static void main(String args[]){
String s1 = null;
System.out.println(s1 !=null ?
A. null
"Hai this string is not empty" : s1);
B. Hai this string is not empty
}
C. Compilation Error
}
D. Runtime Error
Question: 06

class Main
{
public static void main(String[] args){
String s = "Java"+1+2+"Quiz"+""+(3+4); A. Java3Quiz34
System.out.println(s); B. Java12Quiz34
}
C. Java3Quiz7
}
D. Java12Quiz7
Question: 07

class Main
{
public static void main(String[] args){
String x = "abc"; A. Null
String y = "abc"; B. abcabc
x.concat(y);
C. abc
System.out.print(x);
} D. Compilation error
}
Question: 08

Where is toString method defined?

A. String class
B. Object class
C. String Buffered class
D. None of these
Question: 09

What is the string contained in str after


following lines of code?
class Main
{ A. ello
public static void main(String[] args){ B. Hello
StringBuffer str = new StringBuffer("Hello");
C. Compilation Error
str.deleteCharAt(0);
System.out.print(str); D. Runtime Error
}
}
Question: 10

To overcome immutable nature of string


class we use

A. StringBuffer
B. StringBuilder
C. Both a and b
D. None of these
Question: 11

Which class will you recommend among


String, StringBuffer and StringBuilder
classes if I want mutable and thread safe
objects? A. String
B. StringBuffer
C. StringBuilder
D. None of these
Question: 12

Which of these class is superclass of String


and StringBuffer class?

A. java.util
B. java.lang
C. ArrayList
D. None of the mentioned
Question: 13

Which of these method of class String is


used to obtain length of String object?

A. get()
B. Sizeof()
C. lengthof()
D. length()
Question: 14

Which of these method of class String is


used to extract a single character from a
String object?

A. CHARAT()
B. charat()
C. charAt()
D. ChatAt()
Question: 15

Which of these method of class String is


used to compare two String objects for
their equality?

A. equals()
B. Equals()
C. isequal()
D. Isequal()
Question: 16

Which of these data type value is returned


by equals() method of String class?

A. char
B. int
C. boolean
D. All of the mentioned
Question: 17

What will s2 contain after following lines of


code?
String s1 = “one”;
String s2 = s1.concat(“two”) A. two
B. onetwo
C. One
D. None of the above
Question: 18

Which of these method of class String is


used to remove leading and trailing
whitespaces?

A. startsWith()
B. trim()
C. Trim()
D. doTrim()
Question: 19

Which of the following statement is


correct?
A. replace() method replaces all occurrences
of one character in invoking string with
another character.
B. replace() method replaces only first
occurances of a character in invoking
string with another character.
C. replace() method replaces all the
characters in invoking string with another
character.
D. replace() method replaces last occurrence
of a character in invoking string with
another character.
Question: 20

Which of these method of class String is


used to extract a substring from a String
object?

A. substring()
B. Substring()
C. SubString()
D. None of the mentioned
Question: 21

public class Main


{
public static void main(String[] args) {
char ch[ ]={'a','b','c'};
String s = new String(ch);
A. a,b,c
System.out.println(s); B. abc
} C. ‘a’,’b’,’c’
} D. None of the above
Question: 22

public class Main


{
A. Name: Raju
public static void main(String[] args) {
String name="Raju",marks = "1"; Section: A
String section = "A"; Marks: 560
marks=560; B. Name: Raju
System.out.println("Name:" + name); Section: A
System.out.println("section:" + section); Marks: 1560
System.out.println("marks:" + marks); C. Compilation Error
}
D. Runtime Error
}
Question: 23

public class Main


{
public static void main(String[] args) {
String str = "Aptimithra"; A. Aptimithra
StringBuffer sb = new StringBuffer(str); Aptimithra
System.out.println(str); B. Aptimithra
System.out.println(sb); (EMPTY)
} C. Compilation Error
} D. Runtime Error
Question: 24

public class Main


{
public static void main(String[] args) {
String str = "Aptimithra"; A. Aptimithra
StringBuffer sb = str; Aptimithra
System.out.println(str); B. Aptimithra
System.out.println(sb); (EMPTY)
} C. Compilation Error
} D. Runtime Error
Question: 25

public class Main


{
public static void main(String[] args) {
String str = "Codemithra"; A. Codemithra
StringBuffer sb = new StringBuffer(str); Codemithra
System.out.println(sb); B. Codemithra
sb.setLength(4); Code
System.out.println(sb); C. Compilation Error
} D. Runtime Error
}
Question: 26

public class Main


{
A. output of the ftwollowing
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Output program?
of the following program?"); B. output of the ftwoollowing
sb.insert(15,"two"); program?
System.out.println(sb); C. output of the folloowing
} program?
} D. Compilation Error or Runtime
Error
Question: 27

public class Main


{
public static void main(String[] args) { A. control Switch
StringBuffer sb = new StringBuffer("String control
control switch");
B. c
String s1 = sb.substring(7);
String c
System.out.println(s1);
String s2 = s1.substring(0,7); C. control
System.out.println(s2); contro
} D. Compilation error
}
Question: 28

public class Main{


public static void main(String[] args)
A. Java
{
String s1 = "Java"; Javaforandroid
s1.concat("forandroid"); Javaforandroid
System.out.println(s1); B. Javaforandroid
StringBuilder s2 = new StringBuilder("Java"); Javaforandroid
s2.append("forandroid"); Javaforandroid
System.out.println(s2); C. Compilation Error
StringBuffer s3 = new StringBuffer("Java");
D. Runtime Error
s3.append("forandroid");
System.out.println(s3);
}
}
Question: 29

import java.util.*;
public class Main
{ A. abc
public static void main(String[] args) { B. abc
StringTokenizer stuff = new StringTokenizer(
+def
"abc+def+ghi", "+", true );
C. abc
System.out.println( stuff.nextToken() );
System.out.println( stuff.nextToken() ); def
} D. abc
} +
Question: 30

class Main
{
public static void main(String args[])
{
int ascii[] = { 65, 66, 67, 68}; A. ABC
String s = new String(ascii, 1, 3); B. BCD
System.out.println(s); C. CDA
} D. ABCD
}
/ethnuscodemithra Ethnus Codemithra /ethnus /code_mithra

https://learn.codemithra.com

[email protected] +91 7815 095 095 +91 9019 921 340

You might also like