String a = "Kunal";
String b = "Kunal";
Now are both a
and b
pointing to different objects or the same object.
Actually, when you initialize an array it is being stored like this :
Here both strings a
(here name
) and b
will be pointing to the same object :
now any change made to string a
should be reflected on the string b
but that is not the case here. The reason is immutability of strings. You can't change / modify this "Kunal" object. If you want to modify the string then create a new string.
String name = "Kunal Kushwaha"; // "String" : everything that starts with a capital letter is a class
String a = "Kunal";
System.out.println(a);
a = "Kushwaha"; // here we are NOT changing the object but are creating a new object instead, Garbage collector will take care of the old object.
System.out.println(a);
It is basically a separate memory structure inside the heap. It makes our program more optimized.
==
: Comparator
==
checks for the values and if the variables are pointing to the same object.String a = new String("Kunal");
String b = new String("Kunal");
a==b
will give us FALSE..equals
method..equals()
method : String a = "Kunal";
String b = "Kunal";
String name1 = new String("Kunal");
System.out.println(a.equals(name1)); // → true
System.out.println(a == name1); // → false
String a = "Kunal";
String b = new String(a);
System.out.println(b); // → Kunal
System.out.println(a == b); // → false
package com.hitarth;
import java.util.ArrayList;
public class temp {
public static void main(String[] args) {
// CHARACTER WAY:
System.out.println('a' + 'b'); // → 195 // ASCII / UNICODE value has been added
// STRING WAY:
System.out.println("a" + "b"); // → ab // concatenates the string
// OTHERS:
System.out.println((char)('a' + 3)); // → d // i.e (char)(100)
System.out.println("a" + 1); // → a1 // after a few steps this is the same as "a" + "1" // integer will be converted to Integer (wrapper class Integer) that will call toString().
System.out.println("Kunal" + new ArrayList<Integer>()); // → Kunal[] // here also the toString() method is called.
System.out.println(new Integer(56) + new Integer(23)); // → 79
System.out.println(new Integer(56) + new ArrayList<>(); // → Error // the + operator is only defined for primitives or when any one of the values is a string
}
}
package com.hitarth;
public class temp {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
for (int i =0; i<26; i++)
{
char ch = (char)('a' + i);
builder.append(ch);
}
System.out.println(builder); // → abcdefghijklmnopqrstuvwxyz
System.out.println(builder.deleteCharAt(0)); // → bcdefghijklmnopqrstuvwxyz
System.out.println(builder.indexOf("c"));
// .split() , .strip() ,
// typing "builder." will list all the functions that we can perform
}
}