Strings
Strings
Java - Strings
Java Strings
➢
Strings - Generally it is Sequence of characters But in Java,
Strings are called as objects.
➢
Strings - The Java platform provides the String class to create and
manipulate strings.
➢
Strings - In java, string is basically an immutable object.
➢
Strings - All computer languages have strings, look similar in
“Double quotes"
➢
Strings - Example:
➢
String str = "Hello";
Creating String object
➢
Two ways to create String Object is
➢
By string literal
➢
By new keyword
Creating String object
➢
Two ways to create String Object is
➢
By string literal
➢
By new keyword
String Literal
➢
String Literal - String literal is created by double quote.
➢
String Literal - Example:
➢
String s="Hello";
➢
String Literal - Each time a string literal is created,the JVM checks the
string constant pool first.
➢
String Literal - If the string already exists in the pool, a reference to
the pooled instance returns.
➢
String Literal - If the string does not exist in the pool, a new String
object will be created, then is placed in the pool.
String Literal
➢
Example:
➢
String s1="Welcome";
➢
String s2="Welcome";//no
new object will be created.
➢
Why java uses concept of
string literal?
➢
To make Java more memory
efficient (because no new
objects are created if it exists
already in string constant
pool).
Creating String object
➢
Two ways to create String Object is
➢
By string literal
➢
By new keyword
New Keyword
➢
New Keyword - String s=new String("Welcome");//creates two
objects and one reference variable.
➢
New Keyword - Here JVM will create a new String object in
normal(nonpool) Heap memory and the literal "Welcome" will be
placed in the string constant pool.
➢
New Keyword - The variable s will refer to the object in
Heap(nonpool).
new
Welcome
String constant
S pool
Heap
Immutable String
Immutable String in Java
➢
Immutable String - Means unmodifiable or unchangeable.
➢
Immutable String - Once string object is created its data or state can't be changed
but a new string object can be created.
➢
Example:
class Simple{
➢
➢
Since they're 2 different addresses, it's just natural to assume that
those are 2 different persons.That's how the operator == behaves.
➢
So it will say that datos[0]==usuario is false, because it only compares
the addresses.
String comparison in Java
➢
Three ways to compare String objects
➢
By equals() method(for authentication)
➢
By = = operator(for reference matching)
➢
By compareTo() method(for sorting)
By compareTo() method
➢
compareTo() method compares values and returns an int which tells if
the values compare less than, equal, or greater than.
➢
Suppose s1 and s2 are two string variables.If:
➢
s1 == s2 :0
➢
s1 > s2 :positive value
➢
s1 < s2 :negative value
By compareTo() method(Cont'd)
➢
Example:
➢
class Simple{
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
String Concatenation in Java
➢
Concating strings form a new string i.e. the combination of multiple
strings.
➢
There are two ways to concat string objects:
➢
By + (string concatenation) operator
➢
By concat() method
String Concatenation in Java
➢
Concating strings form a new string i.e. the combination of multiple
strings.
➢
There are two ways to concat string objects:
➢
By + (string concatenation) operator
➢
By concat() method
By + operator
➢
String concatenation operator is used to add strings.
➢
Example:
➢
class Simple{
public static void main(String args[]){ append
String s="Apple"+" Tree";
+
System.out.println(s);//Apple Tree
} }
➢
Output:Apple Tree
By + operator(Cont'd)
➢
The compiler will transform the above code into StringBuilder and append Method.
➢
String s=(new StringBuilder()).append("Apple").append("Tree”).toString();
➢
The string concatenation operator can concat not only string but primitive values also.
➢
Example:
➢
class Simple{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
} }
➢
Output:80Sachin4040
➢
If either operand is a string, the resulting operation will be string concatenation. If both
operands are numbers, the operator will perform an addition.
String Concatenation in Java
➢
Concating strings form a new string i.e. the combination of multiple
strings.
➢
There are two ways to concat string objects:
➢
By + (string concatenation) operator
➢
By concat() method
By concat() method
➢
concat() method concatenates the specified string to the end of current string.
➢
Syntax
➢
public String concat(String another){}
➢
Example:
➢
class Simple{
public static void main(String args[]){
String s1="Apple "; concat
String s2="Orange";
String s3=s1.concat(s2);
System.out.println(s3);//Apple Orange
} }
Substring
Substring in Java
• Substring is a subset of another string.
• In Substring startIndex is inclusive and endIndex is exclusive.
Substring(Cont'd)
➢
To get substring from the given String object use one of the two
methods:
➢
public String substring(int startIndex):
➢
This method returns new String object starting from specified
startIndex (inclusive).
➢
public String substring(int startIndex,int endIndex):
➢
This method returns new String object specified with startIndex to
endIndex.
Substring(Cont'd)
➢
Example of java substring
➢
class Simple{
➢
public static void main(String args[]){
➢
String s="Sachin Tendulkar";
➢
System.out.println(s.substring(6));//Tendulkar
➢
System.out.println(s.substring(0,6));//Sachin Tendulkar
➢
} } 1
Sachin Tendulkar
➢
Output:Tendulkar
s 2 Sachin
Sachin
String Methods
Methods of String class
➢
java.lang.String class provides a lot of methods to work on string.
Method Description
1)public boolean equals(Object anObject) Compares this string to the specified object.
2)public boolean equalsIgnoreCase(String another) Compares this String to another String, ignoring case.
3)public String concat(String str) Concatenates the specified string to the end of this
string.
4)public int compareTo(String str) Compares two strings and returns int
5)public int compareToIgnoreCase(String str) Compares two strings, ignoring case differences.
6)public String substring(int beginIndex) Returns a new string that is a substring of this string.
7)public String substring(int beginIndex,int Returns a new string that is a substring of this string.
endIndex)
8)public String toUpperCase() Converts all of the characters in this String to upper
case
9)public String toLowerCase() Converts all of the characters in this String to lower
case.
10)public String trim() Returns a copy of the string, with leading and trailing
whitespace omitted.
Method Description
11)public boolean startsWith(String prefix) Tests if this string starts with the specified prefix.
12)public boolean endsWith(String suffix) Tests if this string ends with the specified suffix.
13)public char charAt(int index) Returns the char value at the specified index.
14)public int length() Returns the length of this string.
15)public String intern() Returns a canonical representation for the string object.
16)public byte[] getBytes() Converts string into byte array.
17)public char[] toCharArray() Converts string into char array.
18)public static String valueOf(int i) converts the int into String.
19)public static String valueOf(long i) converts the long into String.
20)public static String valueOf(float i) converts the float into String.
21)public static String valueOf(double i) converts the double into String.
22)public static String valueOf(boolean i) converts the boolean into String.
23)public static String valueOf(char i) converts the char into String.
24)public static String valueOf(char[] i) converts the char array into String.
25)public static String valueOf(Object obj) converts the Object into String.
26)public void replaceAll(String Changes the firstString with secondString.
firstString,String secondString)
String Buffer class
StringBuffer class
➢
The StringBuffer class is used to created mutable (modifiable) string.
➢
The StringBuffer class is same as String except it is mutable i.e. it can
be changed.
➢
Constructors of StringBuffer
➢
StringBuffer(): creates an empty string buffer with the initial
capacity of 16.
➢
StringBuffer(String str): creates a string buffer with the specified
string.
➢
StringBuffer(int capacity): creates an empty string buffer with the
specified capacity as length.
Note: StringBuffer class is thread-safe i.e. multiple threads cannot
access it simultaneously .So it is safe and will result in an order.
What is mutable string?
➢
A string that can be modified or changed is known as mutable string.
➢
StringBuffer and StringBuilder classes are used for creating mutable
string.
StringBuffer class
➢
Example Using append() method
➢
The append() method concatenates the given argument with this
string.
➢
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
} }
StringBuffer class
➢
Example Using insert() method
➢
The insert() method inserts the given string with this string at the
given position.
➢
class A{
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 Hello 1,Java
} }
s i ti on
1 st Po
HJavaello
String Builder class
StringBuilder class
➢
The StringBuilder class is used to create mutable (modifiable) string.
➢
The StringBuilder class is same as StringBuffer class except that it is non-
synchronized.
➢
It is available since JDK1.5.
➢
Constructors of StringBuilder class
➢
StringBuilder(): creates an empty string Builder with the initial capacity
of 16.
➢
StringBuilder(String str): creates a string Builder with the specified
string.
➢
StringBuilder(int length): creates an empty string Builder with the
specified capacity as length.
StringBuilder class
➢
Using append() method:
➢
The append() method concatenates the given argument with this string.
➢
Example:
➢
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
} }
toString() method
toString() method
➢
If you want to represent any object as a string, toString() method
comes into existence.
➢
The toString() method returns the string representation of the object.
➢
If you print any object, java compiler internally invokes the toString()
method on the object.
➢
Advantage
➢
By overriding the toString() method of the Object class, we can
return values of the object, so we don't need to write much code.
Without Using toString() method
➢
Example:
➢
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city; }
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
} }
➢
Output:Student@1fee6fc
Student@1eed786
Without Using toString() method
➢
Explanation:
➢
In the above example, It prints the hashcode values of the objects
➢
But we want to print the values of these objects.
➢
Since java compiler internally calls toString() method, overriding
this method will return the specified values.
Using toString() method
➢
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city; }
public String toString() {//overriding the toString() method
return rollno+" "+name+" "+city; }
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
} }
➢
Output:101 Raj lucknow
102 Vijay ghaziabad
String Tokenizer
StringTokenizer in Java
➢
The java.util.StringTokenizer class allows you to break a string into
tokens.
➢
It is simple way to break string.
➢
It doesn't provide the facility to differentiate numbers, quoted strings,
identifiers etc. like StreamTokenizer class.
StringTokenizer in Java(Cont'd)
➢
Example
➢
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());
} } }
➢
Output:my
name
is
khan