String Comparison, Concatenation and Substring
- Get link
- X
- Other Apps
String Comparison, Concatenation and
Substring
There's a lot to say about Strings, from the ways you can initialize them to the String Literal Pool, however in this article we'll focus on common operations, rather than the class itself.
Introduction
Simply put, a String is used to store text, i.e. a sequence of characters. Java's most used class is the String class, without a doubt, and with such high usage, it's mandatory for Java developers to be thoroughly acquainted with the class and its common operations.
Java String comparison
We can compare string in java on the basis of content and reference.
- It is used in authentication (by equals() method),
- sorting (by compareTo() method),
- reference matching (by == operator) etc
- By equals() method
- By = = operator
- By compareTo() method
Internal implementation
- public boolean equals(Object anObject) {
- if (this == anObject) {
- return true;
- }
- if (anObject instanceof String) {
- String anotherString = (String) anObject;
- int n = value.length;
- if (n == anotherString.value.length) {
- char v1[] = value;
- char v2[] = anotherString.value;
- int i = 0;
- while (n-- != 0) {
- if (v1[i] != v2[i])
- return false;
- i++;
- }
- return true;
- }
- }
- return false;
- }
Parameter
anotherObject :
another object i.e. compared with this string.Overrides
equals() method of java Object class.
Java String equals() method example
- public class EqualsExample{
- public static void main(String args[]){
- String s1="learnwithreshu";
- String s2="learnwithreshu";
- String s3="LEARNWITHRESHU";
- String s4="python";
- System.out.println(s1.equals(s2));//true because content and case is same
- System.out.println(s1.equals(s3));//false because case is not same
- System.out.println(s1.equals(s4));//false because content is not same
- }}
true
false
false
Java String equals() Method Example 2
The equals() method compares two strings and can be used in if-else control structure.
- public class EqualsExample {
- public static void main(String[] args) {
- String s1 = "learnwithreshu";
- String s2 = "learnwithreshu";
- String s3 = "learnwithreshu";
- System.out.println(s1.equals(s2)); // True because content is same
- if (s1.equals(s3)) {
- System.out.println("both strings are equal");
- }else System.out.println("both strings are unequal");
- }
- }
OutPut
true
both strings are unequal
Java String equals() Method Example 3
Let's see one more example to test the equality of string present in the list.- import java.util.ArrayList;
- public class EqualsExample3 {
- public static void main(String[] args) {
- String str1 = "Mukesh";
- ArrayList<String> list = new ArrayList<>();
- list.add("Ravi");
- list.add("Mukesh");
- list.add("Ramesh");
- list.add("Ajay");
- for (String str : list) {
- if (str.equals(str1)) {
- System.out.println("Mukesh is present");
- }
- }
- }
- }
Mukesh is present
// comparing ints int x, y; x = 10; y = 15; System.out.println(x == y); // prints 'false' // comparing chars char a, b; a = '\n'; b = '\n'; System.out.println(a == b); // prints 'true' // comparing booleans boolean t, f; t = true; f = false; System.out.println(t == f); // prints 'false'
Using the == Operator With Object Types
When it comes to object types, the == operator is used to perform a referential equality comparison. What does that mean? It means that when you use the operator with object types, what you’re actually doing is testing whether the two variables have references that point to the same space in memory. Even if the objects referenced by the variables are identical in regards to their values, the results will still be false. This is somewhat unintuitive, and it can be a source of confusion—and bugs—especially for beginners. Let’s illustrate that with a code example. Suppose you have a Person class, like the one below: public class Person {
private final String name;
private final int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Now, consider the following main method:
public static void main(String[] args) {
Person p = new Person("Alice", 20);
Person p2 = new Person("Alice", 20);
System.out.println(p == p2);
}
public class Student extends Person {
private final String school;
public Student(String name, int age, String school) {
super(name, age);
this.school = school;
}
public String getSchool() {
return school;
}
}
Person p = new Person("Alice", 20);
Person p1 = new Person("Alice", 20);
Student s = new Student("Alice", 20, "Hogwarts");
Student s1 = new Student("Alice", 20, "Hogwarts");
Person p2 = s;
System.out.println(p == p1); // prints 'false'
System.out.println(p2 == s); // prints 'true'
System.out.println(s == s1); // prints 'false'
System.out.println(p == s1); // prints 'false'
System.out.println(p == "test"); // compiler error
The second comparison results in true. Here we’re comparing two variables that are of different, but compatible types, since Person is the parent of Student. The comparison returns true because both variables point to the same object.
The third comparison checks two variables of type Student. The variables point to objects that have the exact same values. Yet, the comparison returns false, since the objects don’t share the same reference.
Following next, we have a comparison between an instance of Person and an instance of Student. The types are compatible, but the result is false since the objects the variables point to aren’t the same.
Finally, we have a comparison between an instance of Person and a string. Since these types aren’t compatible, we get a compiler error.
The compareTo() method lexicographically compares our String with another. The actual comparison of the two strings is based on the Unicode value of each character in the string. The method returns either a positive number, a negative number, or 0.
If all characters in our string were all lower case (or all uppercase) letters, the return value of the compareTo() method can be interpreted as "if the return value was negative, my string would come before the other string in a dictionary".
I emphasize the point that the letters would need to be in the same case, since the function might produce unexpected output otherwise.
The compareTo() method doesn't go through all the characters in our strings, it returns as soon as it reaches the end of any of the strings, or as soon as it finds a non-matching character. In which case the function returns (Unicode value of the mismatched character in our string) - (Unicode value of the mismatched character in the given string).
And in the last line we see -4 is printed because of 'c' - 'g', since that's the first mismatch it found, and it doesn't care about the rest.
Note: The "unexpected" part when using compareTo() happens when we compare strings with different cases.
System.out.println("ORANGE".compareTo("apple"));
We might expect the method to return a positive value, since "apple" should come before "ORANGE". However, the Unicode value for 'O' is less than the Unicode value for 'a'.
This might sometimes be preferred behavior, but in case it isn't - we use compareToIgnoreCase(). That method does essentially the same thing as compareTo(), it just pretends that everything is in the same case, and gives us a "proper" dictionary order.
- By + (string concatenation) operator
- By concat() method
1) String Concatenation by + (string concatenation) operator
Java string concatenation operator (+) is used to add strings. For Example:
Output:Sachin Tendulkar
The Java compiler transforms above code to this:
- String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();
2) String Concatenation by concat() method
The String concat() method concatenates the specified string to the end of current string. Syntax:
Let's see the example of String concat() method.
Output:
Sachin Tendulkar
Substring in Java
A part of string is called substring. In other words, substring is a subset of another string.
In case of substring startIndex is inclusive and endIndex is exclusive.
You can get substring from the given string object by one of the two methods:
public String substring(int startIndex): This method returns new String object
containing the substring of the given string from specified startIndex (inclusive).
public String substring(int startIndex, int endIndex): This method returns new String object
containing the substring of the given string from specified startIndex to endIndex.
In case of string:
startIndex: inclusive
endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
In the above substring, 0 points to h but 2 points to e (because end index is exclusive).
Example of java substring
Output
Tendulkar Sachin
If you like this article please subscribe my blogs to
encourage me to create more content like this.
If you want to understand this in hindi Please click the play button.
Thanks for Watching!!!!!!
Best Regards
Learn with Reshu
#learnwithreshu
- Get link
- X
- Other Apps
Comments
Post a Comment
Please do not comment any spam link in the comment box