0% found this document useful (0 votes)
25 views

3.java Strings

java strings concept

Uploaded by

sumityadavit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

3.java Strings

java strings concept

Uploaded by

sumityadavit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Strings

String:
String is a sequence of characters. In java, objects of String are immutable
which means a constant and cannot be changed once created. Strings are immutable
because java uses the concept of string literal. Suppose there are 5 reference
variables, all refers to one object. If one reference variable changes the value of the
object, it will be affected to all the reference variables. That is why string objects are
immutable in java.

Types of String creation:


Strings can be created in two ways. They are
A) String literal or without new keyword,
B) Using new keyword.
A) String literal or without new keyword:
Syntax: String variable_name= “string data”;
Ex: String s1= “hi”;
String s2= “hi”;
In java there is a concept of String Constant Pool in Heap. To cut down the number of
String objects created, the String class keeps a pool of strings in Heap. Each time you
create a string literal, and then JVM checks the string literal pool first. If the string
already exists in the pool, a reference to the pooled instance returns. If the string does
not exist in the pool, a new String object instantiates then it is placed in the pool.

B) Using new keyword:


Syntax: String variable_name= new String(“ string data”);
Ex: String s1= new String(“hello”);
String s2= new String(“hello”);
In this case, JVM will create a new string object in normal (non pool) heap memory
and the literal "hello" will be placed in the string constant pool. The variables will
refer to the object in heap (non pool).
Methods of String class:
The java.lang.String class provides many useful methods to perform operations
on string. Some methods are given below
1. length(): Returns the length of string.
Syntax:
string_variable.length();
2. charAt(int index): Returns the character at that index value.
Syntax:
string_variable.charAt(int index);
3. substring (int startOfIndex): returns the string characters from startOfIndex
to end of string.
Syntax:
string_variable.substring( int startOfIndex);
4. substring (int startOfIndex, int UptoTheIndex): Returns the string
characters from startOfIndex to UptoTheIndex(excluded it).
Syntax:
string_variable.substring(int startOfIndex,int UptoTheIndex);
5. concat(String str): Concatenating the str with another string at the end.
Syntax:
string_variable1.concat(string_variable2);
6. equals(String str): Returns boolean value by checking all characters(case
sensitive) in one string with another String.
Syntax:
string_variable1.equals(string_variable2);
7. equalsIgnoreCase(String str): Returns boolean value by checking all
characters(not case sensitive) in one string with another String.
Syntax:
string_variable1.equalsIgnoreCase(string_variable2);
8. toLowerCase(): Returns a string with all characters of given string in lower
cases.
Syntax:
string_variable.toLowerCase();
9. toUpperCase(): Returns a string with all characters of given string in upper
cases.
Syntax:
string_variable.toUpperCase();
10. toCharArray(): Returns a character array with all characters of given string.
Syntax:
String_variable.toCharArray();

Strings Comparison:
We can compare string in java on the basis of content and reference.
There are three ways to compare string in java:
 By equals() method
 By = = operator
 By compareTo() method

A) By equals() Method:
The String equals() method compares the original content of the string. It
compares values of string for equality. String class provides two methods:
 public boolean equals(Object another): compares this string to the specified
object.
 public boolean equalsIgnoreCase(String another): compares this String to
another string, ignoring case.

Example:
Class Test{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";

System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}
Output:
false
true

B) By == operator:

The = = operator compares references not values.

Example:
class Test{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true
System.out.println(s1==s3);//false
} }
Output:
true
false
C) By compareTo() Method:
The String compareTo() method compares values lexicographically and returns
an integer value that describes if first string is less than, equal to or greater than
second string.
Suppose s1 and s2 are two string variables. If:
 s1 == s2 :0
 s1 > s2 :positive value
 s1 < s2 :negative value

Example:
class Test{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output:
0
1
-1

String Concatenation:
In java, string concatenation forms a new string that is the combination of
multiple strings. There are two ways to concat string in java:
 By + (string concatenation) operator
 By concat() method
A) By + (String Concatenation) operator:
It is used add strings.
Example:
class Test{
public static void main(String args[]){
String s="Second"+" Campus";
System.out.println(s);
}
}
Output:
Second Campus
B) By concat() method:
It concatenates the specified string to the current String.
Example:
class Test{
public static void main(String args[]){
String s1="Second";
String s2=" Campus";
String s3=s1.concat(s2);
System.out.println(s3);
}
}
Output:
Second Campus

StringBuffer:
Java StringBuffer is a class which is used to create mutable (modifiable) string.
The StringBuffer class in java is same as String class except it is mutable i.e. it can be
changed. It is synchronized.
Some important methods in StringBuffer class:
1. append(): Concatenates the given argument with this string.
2. insert(int indexPosition, String s): Inserts the given string with in the
string at the given index position.
3. capacity(): 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.
4. length(): The length of a StringBuffer can be found by the length( )
method.

StringBuilder:
Java StringBuilder is a class which is used to create mutable (modifiable)
string. The Java StringBuilder class is same as StringBuffer class except that it is
non-synchronized. It is available since JDK 1.5.
String Vs StringBuffer Vs StringBuilder:

Index String StringBuffer StringBuilder


Storage Area String Constant Heap Heap
Pool
Modifiable No(immutable) Yes(mutable) Yes(mutable)
Thread Safe Yes Yes No
Speed Fast Very slow Fast
StringTokenizer:
StringTokenizer is a class which is used to break a string into tokens. A
StringTokenizer object internally maintains a current position within the string to be
tokenized. Some operations advance this current position past the characters
processed.
A token is returned by taking a substring of the string that was used to create
the StringTokenizer object.
StringTokenizer Constructors:
 StringTokenizer (String str): Constructs a string tokenizer for the
specified string. The tokenizer uses the default delimiter set, which is
"\t\n\r\f": the space character, the tab character, the newline character, the
carriage-return character, and the form-feed character. Delimiter characters
themselves will not be treated as tokens.
 StringTokenizer (String str, String delim): Constructs a string tokenizer
for the specified string. The characters in the delim argument are the
delimiters for separating tokens. Delimiter characters themselves will not be
treated as tokens.
 StringTokenizer (String str, String delim, boolean returnDelim):
Constructs a string tokenizer for the specified string. All characters in the
delim argument are the delimiters for separating tokens. If the returnDelims
flag is true, then the delimiter characters are also returned as tokens. Each
delimiter is returned as a string of length one. If the flag is false, the
delimiter characters are skipped and only serve as separators between
tokens.
Note:
if delim is null, this constructor does not throw an exception. However, trying
to invoke other methods on the resulting StringTokenizer may result in a
NullPointerException.

You might also like