Today I learned about Object class, String, StringBuffer, StringBuilder. html
The most common methods which are applicable for any java object are defined in Object class, it acts as root for all java classes. java
There are 11 methods in Object class, I am going to explain about some. api
1. toString(): oracle
We use this method to get String representation of an object, if our class do not contain a toString() method then Object class toString() executes. app
class Student { String name; int rollno; Student(String name, int rollno) { this.name = name; this.rollno = rollno; } public static void main(String[] args) { Student s1 = new Student("sri",476); Student s2 = new Student("Mohan",467); System.out.println(s1); // We did not override toString() hence Object class toString() is called System.out.println(s2); }} /* the output is Student@1c78e57 Student@5224ee */
In the above example Object class toString() is executed which returns Classname@hexadecimalString_representation_of_hashcode. ide
In String classes, StringBuffer, all Wrapper classes, all Collection classes toString() is overridden for meaningful representation of an object. ui
Now lets override toString() in our class to return name. this
class Student { String name; int rollno; Student(String name, int rollno) { this.name = name; this.rollno = rollno; } public String toString() { return name; } public static void main(String[] args) { Student s1 = new Student("sri",476); Student s2 = new Student("Mohan",467); System.out.println(s1); // We did not override toString() hence Object class toString() is called System.out.println(s2); }} /* the output is sri Mohan */
For every object JVM will generate a unique number which is known as hashcode.JVM will use this hashcode while saving objects into hashing related datastructures like hashset, hashmap, hashtable. spa
We can override hashCode() based on our requirement but its good if we have a unique number as hashcode for every object. .net
If in our class, object class toString() executes then it calls hashCode() internally.
Lets override hashCode() in the below example and observe the output.
class Test { int i; Test(int i) { this.i = i; } public int hashCode() { return i; } public static void main(String[] args) { Test t1 = new Test(10); Test t2 = new Test(100); System.out.println(t1);//Test@a System.out.println(t2);//Test@64 }}
You can observe that output for t1 is Test@a , since we overridden hashCode in our class to return i , toString() internally calls our hashCode() in place of Object class hashCode().
3. equals()
Object class equals() is used for reference comparision. In String , Wrapper, Collection classes .equals() is overridden for content comparison, but in StringBuffer class .equals() isn’t overridden hence even if both objects are equal .equals() returns false.
class Test1 { public static void main(String[] args) { String s1 = new String("harsha"); String s2 = new String("harsha"); System.out.println(s1.equals(s2)); //true System.out.println(s1.hashCode() == s2.hashCode());//true StringBuffer a1 = new StringBuffer("harsha"); StringBuffer a2 = new StringBuffer("harsha"); System.out.println(a1.equals(a2)); //false System.out.println(a1.hashCode() == a2.hashCode());//false }}
If two objects are equal by .equals() then their hashcodes are equal.
Strings are Immutable i.e., once we create any String object then we cannot make any changes to it, if we make any then with those changes a new object will be created this is known as Immutability.
class StringDemo { public static void main(String[] args) { String s1 = new String("harsha"); s1.concat(" solutions"); String s2 = s1.concat("innovations!"); s1.concat("soft"); System.out.println(s2); System.out.println(s1); }}
In above example eight objects are created, 4 in heap and 4 in SCP.
In Heap:
「harsha」 is created and assigned to s1, 「harsha solutions」 is created in heap and has no reference, now 「harsha innovations」 is created and is assigned to s2 and at last 「harsha soft」 is also dynamically created and eventually lost as it has no reference.
In String Constant Pool:
「harsha」, 「solution」,」innovations」,」soft」 are created.
Some points you need to know about Strings
class StringDemo2 { public static void main(String[] args) { String s1 = new String("I am the boss!"); String s2 = new String("I am the boss!"); System.out.println(s1 == s2); //false //since s1 and s2 are two different objects created in heap. String s3 = "I am the boss!"; System.out.println(s1 == s3); //false //since s1 is an object created in heap and s3 is object created in SCP. String s4 = "I am the boss!"; System.out.println(s3 == s4);//true //s3 and s4 points to same object in SCP, since duplicate objects are not allowed in SCP. String s5 = "I am" +" the boss!"; System.out.println(s3 == s5);//true //for runtime operation, a new object will be created in heap and the above isn't a runtime operation! //so it points to same object previously created in SCP. String s6= "I am"; String s7 = s6 + " the boss!"; System.out.println(s3 == s7);//false //s7 is an object created during Runtime so it is created in heap. }}
intern():
By using heap object if we want to get corresponding SCP object then we should go for intern() method.
class StringInternDemo { public static void main(String[] args) { String s1 = new String("harsha"); String s2 = s1.intern(); System.out.println(s1 == s2); //false //since s2 is created in SCP String s3 = "harsha"; System.out.println(s2 == s3); //true //since s3 is created in SCP }}
//Program demonstrating some methods of String class class StringDemo3 { public static void main(String[] args) { String s = "Sri Harsha"; System.out.println(s.charAt(3)); s = s.concat(" Bolisetti"); System.out.println("Sri".equals(s)); //this is overriding version of .equals() in Object class System.out.println("sri harsha bolisetti".equalsIgnoreCase(s)); String lname = s.substring(11); System.out.println(lname); String fname = s.substring(0,10); System.out.println(fname); System.out.println("length of my name is " +s.length()); String s2 = s.replace('s','Z'); System.out.println(s2); System.out.println(s.toLowerCase()); System.out.println(s.toUpperCase()); System.out.println(" Sri Harsha Bolisetti ".trim()); //trim() removes spaces at the begining and end of the String but not middle blank spaces. System.out.println(s.indexOf('B')); System.out.println(s.lastIndexOf('i')); }} /* Output of the above program is false true Bolisetti Sri Harsha length of my name is 20 Sri HarZha BoliZetti sri harsha bolisetti SRI HARSHA BOLISETTI Sri Harsha Bolisetti 11 19 */
StringBuffer is mutable i.e, we can make changes in an object without need to create a new object.
Constructors:
1. StringBuffer sb = new StringBuffer();
It creates an empty StringBuffer object with default initial capacity 16. Once it reaches its maximum capacity, a new StringBuffer object is created with capacity (current capacity + 1)* 2.
2. StringBuffer sb = new StringBuffer(int initial capacity);
It creates StringBuffer with specified initial capacity.
3. StringBuffer sb = new StringBuffer(String s);
Creates an equivalent StringBuffer object for the given String with capacity equal to s.length()+16.
class StringBufferDemo1 { public static void main(String[] args) { StringBuffer sb = new StringBuffer(); System.out.println(sb.capacity()); sb.append("0123456789123456"); System.out.println(sb.capacity()); //16 sb.append("1"); System.out.println(sb.capacity()); //34 StringBuffer sb1 = new StringBuffer(11); System.out.println(sb1.capacity());//11 StringBuffer sb2 = new StringBuffer("harsha"); System.out.println(sb2.capacity());// 22 (16+6 ) } }
Program to demonstrate methods in StringBuffer
class StringBufferDemo2 { public static void main(String[] args) { StringBuffer sb = new StringBuffer("I will win no matter the consequences"); System.out.println(sb.charAt(3)); sb.setCharAt(3,'I'); System.out.println(sb); sb.append(" Cool!"); System.out.println(sb); sb.insert(12,"!!Inserted here!!"); System.out.println(sb); sb.delete(12,28); System.out.println(sb); sb.deleteCharAt(12); System.out.println(sb); System.out.println(sb.reverse()); System.out.println(sb.reverse()); sb.setLength(14); System.out.println(sb); sb.ensureCapacity(100); System.out.println(sb.capacity()); sb.trimToSize(); System.out.println(sb.capacity()); }} /* Output i I wIll win no matter the consequences I wIll win no matter the consequences Cool! I wIll win n!!Inserted here!!o matter the consequences Cool! I wIll win n!o matter the consequences Cool! I wIll win no matter the consequences Cool! !looC secneuqesnoc eht rettam on niw llIw I I wIll win no matter the consequences Cool! I wIll win no 108 14 */
Its almost same as StringBuffer including methods and constructors, except that every method present inside StringBuffer is synchronized while methods in StringBuilder aren’t synchronized.