Testing Objects
Testing Objects
String Object
Notebook: 1_JAVA_BASICS
Created: 10/17/2018 1:07 PM Updated: 11/8/2018 11:23 PM
Author: suja.sadhusundarsingh@photoninfotech.net
URL: https://www.ntu.edu.sg/home/ehchua/programming/java/J3d_String.html
String Object:
1. By string literal
2. By new keyword
1) String Literal
Each time you create a string literal, the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is returned. If the
string doesn't exist in the pool, a new string instance is created and placed in the pool.
For example:
. String s1="Welcome";
. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool, that is why it will create a new
object. After that it will find the string with the value "Welcome" in the pool, it will not
create a new object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as the
"string constant pool
2) By new keyword
In such case, JVM will create a new string object in normal (non-pool) heap memory.
and
Both expression gives you String object, but there is subtle difference between them.
When you create String object using new() operator, it always create a new object in heap
memory. On the other hand, if you create object using String literal syntax e.g. "Java", it
may return an existing object from String pool
This will be much more clear when you compare two String objects created using String
literal and new operator, as shown in below example :
String a = "Java";
String b = "Java";
System.out.println(a == b); // True
Here two different objects are created and they have different references:
Similarly when you compare a String literal with an String object created using new()
operator using == operator, it will return false, as shown below :
String e = "JDK";
String f = new String("JDK");
System.out.println(e == f); // False
In general you should use the string literal notation when possible. It is easier to read and
it gives the compiler a chance to optimize your code
equals( ) method compares the characters inside a String object. The == operator
compares two object references to see whether they refer to the same instance.
Example:
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
The variable s1 refers to the String instance created by "Hello". The object referred to
by s2 is created with s1 as an initializer. Thus, the contents of the two String objects
are identical, but they are distinct objects. This means that s1 and s2 do not refer to the
same objects and are, therefore, not ==.
Consider below code with three concatenation functions with three different types of
parameters, String, StringBuffer and StringBuilder.
Example:
2. Concat2 : In this method, it changes the actual value of the string (in main) .
If a string is going to remain constant throughout the program, then use String class
object because a String object is immutable.
If a string can change (example: lots of logic and operations in the construction of the
string) and will only be accessed from a single thread, using a StringBuilder is good
enough.
If a string can change, and will be accessed from multiple threads, use a StringBuffer
because StringBuffer is synchronous so you have thread-safety.
Here, String length() function will return the length 5 for s1 and 7 for s2
respectively.
Java String compareTo(): The Java String compareTo() method compares the
given string with current string. It is a method of ‘Comparable’ interface which is
implemented by String class. Don’t worry, we will be learning about String
interfaces later. It either returns positive number, negative number or 0. For
example:
This program shows the comparison between the various string. It is noticed that
if s1 > s2, it returns a positive number
if s1 < s2, it returns a negative number
if s1 == s2, it returns 0
Java String concat() : The Java String concat() method combines a specific
string at the end of another string and ultimately returns a combined string. It is
like appending another string. For example:
Java String IsEmpty() : This method checks whether the String contains
anything or not. If the java String is Empty, it returns true else false. For
example:
Java String Trim() : The java string trim() method removes the leading and
trailing spaces. It checks the unicode value of space character (‘\u0020’) before
and after the string. If it exists, then removes the spaces and return the omitted
string. For example:
In the above code, the first print statement will print “hello how are you” while
the second statement will print “hellohow are you” using the trim() function.
Java String toUpper() : The Java String toUpperCase() method converts all
the characters of the String to upper case. For example:
Java String ValueOf(): This method converts different types of values into
string.Using this method, you can convert int to string, long to string, Boolean to
string, character to string, float to string, double to string, object to string and
char array to string. The signature or syntax of string valueOf() method is given
below:
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)
In the above code, it concatenates the Java String and gives the output – 2017.
Java String replace(): The Java String replace() method returns a string,
replacing all the old characters or CharSequence to new characters. There are 2
ways to replace methods in a Java String.
In the above code, it will replace all the occurrences of ‘h’ to ‘t’. Output to the
above code will be “tello tow are you”. Let’s see the another type of using
replace method in java string:
Java String replace(CharSequence target, CharSequence replacement) method :
Java String contains() :The java string contains() method searches the
sequence of characters in the string. If the sequences of characters are found,
then it returns true otherwise returns false. For example:
1 class ContainsExample{
2 public static void main(String args[]){
3 String name=" hello how are you doing?";
4 System.out.println(name.contains("how are you")); // returns true
5 System.out.println(name.contains("hello")); // returns true
6 System.out.println(name.contains("fine")); // returns false
7 }}
In the above code, the first two statements will return true as it matches the
String whereas the second print statement will return false because the
characters are not present in the string.
Java String equals() : The Java String equals() method compares the two
given strings on the basis of content of the string i.e Java String representation.
If all the characters are matched, it returns true else it will return false. For
example:
Java String toCharArray(): This method converts the string into a character
array i.e first it will calculate the length of the given Java String including spaces
and then create an array of char type with the same content. For example:
1 StringToCharArrayExample{
2 public static void main(String args[]){
3 String s1="Welcome to Edureka";
4 char[] ch=s1.toCharArray();
5 for(int i=0;i&<ch.length;i++){
6 System.out.print(ch[i]);
7 }}}
Java String IsEmpty() : This method checks whether the String is empty or
not. If the length of the String is 0, it returns true else false. For example:
1 public class IsEmptyExample{
2 public static void main(String args[]) {
3 String s1="";
4 String s2="hello";
5 System.out.prinltn(s1.isEmpty()); // returns true
6 System.out.prinltn(s2.isEmpty()); // returns false
7 }}
}}
.out.prinltn(s1.isEmpty()); // returns true
System.out.prinltn(s2.isEmpty()); // returns false
}}
In the above code, the first print statement will return true as it does not contain anything while the second print statement
will return false.
Java String endsWith() : The Java String endsWith() method checks if this string ends with the given suffix. If it
returns with the given suffix, it will return true else returns false. For example:
This is not t