Advanced Java Programming

Image
                          Advanced Java Programming Advanced Java Programming :-   Introduction to advance java   As most of us already know that if we want to make normal applications it  can be easily built using core Java concepts. But, when it we need to develop web applications, advanced Java fundamentals, like JSP, Servlets, JDBC etc. needed, so to add capabilities and features of the application advance java is essential for developers. Through the motive of this blog is to explain about Advanced Java, I will be giving you a complete insight into the fundamental concepts of Advance Java. Figure - 1.2 If you want to see complete video on this please  have a look the video below.                              Learn with Resh u Advanced Java Programming Course ...

String Comparison, Concatenation and Substring

 

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

There are three ways to compare string in java:
  1. By equals() method
  2. By = = operator
  3. By compareTo() method
1.Java String equals()

The java string equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.

The String equals() method overrides the equals() method of Object class.

Internal implementation

  1. public boolean equals(Object anObject) {  
  2.       if (this == anObject) {  
  3.           return true;  
  4.       }  
  5.       if (anObject instanceof String) {  
  6.           String anotherString = (String) anObject;  
  7.           int n = value.length;  
  8.           if (n == anotherString.value.length) {  
  9.               char v1[] = value;  
  10.               char v2[] = anotherString.value;  
  11.               int i = 0;  
  12.               while (n-- != 0) {  
  13.                   if (v1[i] != v2[i])  
  14.                           return false;  
  15.                   i++;  
  16.               }  
  17.               return true;  
  18.           }  
  19.       }  
  20.       return false;  
  21.   }

Signature

  1. public boolean equals(Object anotherObject) 

Parameter

anotherObject : 

another object i.e. compared with this string.

Returns

true if characters of both strings are equal otherwise false.

Overrides

equals() method of java Object class.

Java String equals() method example

  1. public class EqualsExample{  
  2. public static void main(String args[]){  
  3. String s1="learnwithreshu";  
  4. String s2="learnwithreshu";  
  5. String s3="LEARNWITHRESHU";  
  6. String s4="python";  
  7. System.out.println(s1.equals(s2));//true because content and case is same  
  8. System.out.println(s1.equals(s3));//false because case is not same  
  9. System.out.println(s1.equals(s4));//false because content is not same  
  10. }}  

Output
true
false
false

Java String equals() Method Example 2

The equals() method compares two strings and can be used in if-else control structure.


  1. public class EqualsExample {  
  2.     public static void main(String[] args) {  
  3.         String s1 = "learnwithreshu";    
  4.         String s2 = "learnwithreshu";    
  5.         String s3 = "learnwithreshu";  
  6.         System.out.println(s1.equals(s2)); // True because content is same    
  7.         if (s1.equals(s3)) {  
  8.             System.out.println("both strings are equal");  
  9.         }else System.out.println("both strings are unequal");     
  10.     }  
  11. }  

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.

  1. import java.util.ArrayList;  
  2. public class EqualsExample3 {  
  3.     public static void main(String[] args) {  
  4.         String str1 = "Mukesh";  
  5.         ArrayList<String> list = new ArrayList<>();  
  6.         list.add("Ravi");   
  7.         list.add("Mukesh");  
  8.         list.add("Ramesh");  
  9.         list.add("Ajay");  
  10.         for (String str : list) {  
  11.             if (str.equals(str1)) {  
  12.                 System.out.println("Mukesh is present");  
  13.             }  
  14.         }  
  15.     }  
  16. }  
Mukesh is present

2.The == Operator

When you use the equality operator with primitive types, you’re just comparing their values. Take a look at the following examples:

 // 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);
}
What do you think our little program will print when we run it? If your answer is false, then you’ve got it right. But why is that the case?

It has to do with references. When we initialize the p variable, we create a new instance of the Person class, which will live somewhere in the memory. The content of p is a reference (an “address”) to the location where the object resides.

When we utilize the p2 variable, we create another instance of Person. However, this instance will live at a different location in memory, and it’s this location that gets assigned to the variable. When using the == operator to compare the variables, we’re actually comparing the references they store, which are obviously different, so we get false as a result.

When using the operator to compare object types, the arguments must be compatible. That means that you can compare arguments of the same type, but also of types that have a child/parent relationship. If the arguments aren’t of the same type neither extend from one another, and you’ll get a compiler error. An example would show this more clearly. Consider the excerpt of code below:


 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;
    }
}

The example above features a new class, Student, that extends from the Person class shown in the first example. Now, take a look at the example below, that shows how we can compare instances of the two classes:

  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 first comparison returns false. Both arguments have the same type (Person). They point to objects which have the exact same values for their fields. But even though their values are equal, they’re not the same objects. They don’t share the same place in memory, and that’s what the operator is comparing.

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.

3.compareTo method

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).

System.out.println("a".compareTo("a"));
System.out.println("a".compareTo("b"));
System.out.println("1".compareTo("12345678"));
System.out.println("2".compareTo("12345678"));
System.out.println("abcd".compareTo("abgggggggggg"));

Output :-
0
-1
-7
1
-4

On the third line of the code above, in this case compareTo returns the difference in string lengths, since it didn't find a mismatched character before it "ran out" of characters in one 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.

Note: compareTo() and compareToIgnoreCase() are often used when we make a Comparator for a custom class.

String Concatenation in Java

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

1) String Concatenation by + (string concatenation) operator

Java string concatenation operator (+) is used to add strings. For Example:


  1. class TestStringConcatenation1{  
  2.  public static void main(String args[]){  
  3.    String s="Sachin"+" Tendulkar";  
  4.    System.out.println(s);//Sachin Tendulkar  
  5.  }  
  6. }

Output:Sachin Tendulkar
The Java compiler transforms above code to this:
  1. 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:


  1. public String concat(String another)  


Let's see the example of String concat() method.


  1. class TestStringConcatenation3{  
  2.  public static void main(String args[]){  
  3.    String s1="Sachin ";  
  4.    String s2="Tendulkar";  
  5.    String s3=s1.concat(s2);  
  6.    System.out.println(s3);//Sachin Tendulkar  
  7.   }  
  8. }  

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.


  1. String s="hello";  
  2. System.out.println(s.substring(0,2));//he  


In the above substring, 0 points to h but 2 points to e (because end index is exclusive).

Example of java substring

  1. public class TestSubstring{  
  2.  public static void main(String args[]){  
  3.    String s="SachinTendulkar";  
  4.    System.out.println(s.substring(6));//Tendulkar  
  5.    System.out.println(s.substring(0,6));//Sachin  
  6.  }  
  7.  
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

Comments

Popular posts from this blog

Learn Complete OOPS Concepts in one Project

Spring Core

Polymorphism in Java Method Overriding and Method OverLoading in Java