0% found this document useful (0 votes)
4 views61 pages

java.lang Package

The document provides comprehensive notes on the Java.lang package, focusing on key classes such as Object, String, StringBuffer, and StringBuilder, along with their methods and functionalities. It covers essential concepts like equals() and hashCode() methods, cloning, and the importance of overriding these methods for effective object comparison and representation. Additionally, it discusses autoboxing and the relationship between wrapper classes and primitive types in Java.

Uploaded by

raj9301560
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
4 views61 pages

java.lang Package

The document provides comprehensive notes on the Java.lang package, focusing on key classes such as Object, String, StringBuffer, and StringBuilder, along with their methods and functionalities. It covers essential concepts like equals() and hashCode() methods, cloning, and the importance of overriding these methods for effective object comparison and representation. Additionally, it discusses autoboxing and the relationship between wrapper classes and primitive types in Java.

Uploaded by

raj9301560
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 61
Core Java with SCJP/ OCIP Notes By Durga Sir java.iang package With SCJP / OCIP Study Material Chapter 10: Java.lang Package DURGA mech (Sun certified & Realtime Exper0 Ex. IBM Employee Trained Lakhs of Students for last 14 years across INDIA India’s No.1 Software Training Institute DURGASOFT 7 | DURGASOFT, #202,2"%loor HUDA Maitrvanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with S61 OCIP Notes By Dur Si ievaling package java.lang package} 1. Introduction 2. Javalang.Object class + toString( ) method + hashCode) method + toString() method vs hashCode() method + equals() method + Simplified version of equals) method + More simplified version of .equals() method + Relationship between .equals() method and ==(double equal operator) + Differences between == (double equal operator) and .equals() method? Agenda Contract between .equals() method and hashCodeQ) method Clone () method Shallow cloning Deep Cloning getClass() method finalize( ) + wait() , notify() , notifyAlI() 3. java.lang String class, + Importance of String constant pool (SCP) Interning of String objects String class constructors Important methods of String class Creation of our own immutable class + Final vs immutabil 4. StringBuffer + Constructors + Important methods of StringBuffer 5. StringBuilder (1.5v) + StringBuffer Vs StringBuilder + String vs StringBuffer vs StringBuilder + Method chaining 6. Wrapper classes + Constructors + Wrapper class Constructor summery 7. Utility methods + valueOfQ method + xxxValue() method + parseXxx() method + toString) method 8. Dancing between String, wrapper object and primitive 9. Partial Hierarchy of java.lang package + Void 10. Autoboxing and Autounboxing + Autoboxing + Autounboxing + Conclusions ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package 11. Over! ading with respect to widening, Autoboxing and var-arg methods + Case 2: Widening vs var-arg method + Case 3: Autoboxing vs var-arg method ‘The following are some of important classes present in java.lang package. Object class String class StringBuffer class StringBuilder class (1.5 v) Wrapper Classes Autoboxing and Autounboxing(1.5 v) + For writing any java program the most commonly required classes and interfaces are encapsulated in the separate package which is nothing but java.lang package. + Itis not required to import java.lang package in our program because available by default to every java program. What is your favorite package? Why java.lang is your favorite package? It is not required to import lang package explicitly but the remaining packages we have to import. lava.lani Dens 1. For any java object whether it is predefine or customized the most commonly required methods are encapsulated into a separate class which is nothing but object class. 2. As object class acts as a root (or) parent (or) super for all java classes, by default 5 methods are available to every java class. Note : If our class doesn't extends any other class then it is the direct child class of object Ifour class extends any other class then it is the indirect child class of Object. a: ‘The following is the list of all methods present in java.lang Object class : public String toString(); public native int hashCode(; public boolean equals(Object 0); protected native Object clone(throws CloneNotSupportedException; public final Class getClass(); protected void finalize()throws Throwable; public final void wait() throws InterruptedException; public final native void wait)throws InterruptedException; public final void wait(long ms,int ns)throws InterruptedException; ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package 10. public final native void notify); 11. public final native void notifyANQ; Sen eho) 1. We can use this method to get string representation of an object. 2. Whenever we are try to print any object reference internally toString() method will be executed. If our class doesn't contain toString() method then Object class toString() method will be executed. 4, Example: 5. System.out.printin(si); => super (s1.toString()) ; 6. Example 1: 7 8 9 + class Student 4 String name; 10. int rolino: 11. Student (String name, int rolino) wd. { 13. this.name=nane; 14. this.rollno=rolino; 5. } 16. public static void main(String args{1) { 17. Student si=new Student ("saicharan” 101); 18. Student s2-new Student ("ashok",102) 19. System.out.printin(s1) ; 20. System.out printin(si.toString()) ; 21. System.cut printin(s2); 22.) 23.) 24. Output: 25. Studento3e25a5 26. Student?3e25a5 27. studente1se2it 28. 29. In the above program Object class toString() method got executed which is implemented as follows. 30. public String tostring() ( 31. return getClass ().getName() + "2" + Integer. toHexstving (hashCode ()) + 32. ) 33. 34. here getClass() getName () => classnamedhexa decimal String representation _of hashCode 35. To provide our own String representation we have to override toString() method in our class. Ex: For example whenever we are try to print student reference to print his a name and roll no we have to override toString) method as follows. 36. public String toString() { 37. return name+" "trollne: 38. } 39. In String class, StringBuffer, StringBuilder, wrapper classes and in all collection classes toString() method is overridden for meaningful string representation. Hence in our classes also highly recommended to override toString() method. 40. ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com core Jav /a with SCJP/ OCIP Notes By Durga Sir java.iang package a. 42. 43. 4a. 45 46. a7. 43. 43 50. 51. 52. 53. 54. 55. 56. 57. 58. 59 Example 2 class Test{ public String tostring() ( return "Test"; } public static void main(String[] args) { Integer i=new Integer (10); String ssnew String ("ashok"); Test t-new Test(); System.out.println (i); ‘System. out .println (5! System.out .printin (t) ; Wien) For every object jvm will generate a unique number which is nothing but hashCode. Jvm will using hashCode while saving objects into hashing related data structures like HashSet, HashMap, and Hashtable ete. If the objects are stored according to hashCode searching will become very efficient (The most powerful search algorithm is hashing which will work based on hashCode). If we didn't override hashCode() method then Object class hashCode() method will be executed which generates hashCode based on address of the object but it doesn't mean hashCode represents address of the object. Based on our programming requirement we can override hashCode() method to generate our own hashcode. Overriding hashCode() method is said to be proper if and only if for every object we have to generate a unique number as hashcode for every object. Example 3: class student class Student { ( nn susie Zev hascode() return 100; { } ee 0} return rollno; } , It is improper way of overriding hashCodeQ method because for every object we are generating same hashcode. ) It is proper way of overriding hashcodeQ, method because for every object we are generating a different hashcode. ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package Sen chee ena anes class Test case. Tost Cea Post tint 4) ( Peas this.i=i; mest (int 4) t ‘this. isi; ) y public int hashCode) { return i; d public static void main(St=ingi] ugaic static void main(String] eee Lesion TeSt{10)/: args) ( Best tomer aascaey. Test ti=new Test (20) ; System. out. printin (tl) ; enteral sin 4 per atesunel: System. out -printin (1): ; : System. out.printin(t2) ; » ) Object—=>tostring() called. Object==>tostring() called. ce tostring () Object=ShashCode() called. frest—ehashcoda() called. In this ease Object class toString() method got executed which is internally calls Object ‘class hashCode() method. 8. Example In this case Object class toString() method got executed which is internally calls Test class hashCode() method. 8. 10. class Test ae { 42. int i; 13. Test (int i) 44a. 15. thie. 16.) 17. public int hashCode () { 18. return i; 19.) 20. public String tostring() 21. { 22. return i 23.) 24. public static void main(string[] args) { 25. Test ti=new Test (10); 26. Test t2=new Test (100); 27. System.out printin (tl) ; 28. System.out printin(t2) ; 29.) 30. } 31. Output 32. 10 33. 100 34. In this case Test class toString() method got executed. Note: 1. if'we are giving opportunity to Object class toString() method it internally calls hashCodeQ method. But if'we are overriding toString method it may not call hashCode() method. ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package 2. We can use toString() method while printing object references and we can use hashCodeQ method while saving objects into HashSet or Hashtable or HashMap. rence 1. We can use this method to check equivalence of two objects. 2. Ifour class doesn't contain .equals() method then object class .equals() method will be executed which is always meant for reference comparison[address comparison]. i.c., if two references pointing to the same object then only .equals( ) method returns true. Example 5: class Student Student (String name,int rolino) t ‘this.name=name; this. rollno=rollno; ) public static void main(string[] args) ( Student si=new student ("vijayabhaskar",101) ; Student s2=new Student ("bhaskar",102) ; Student s3-new Student ("vijayabhaskar", 101) ; Student s4zs: System, out .printIn(si.equals (s2)) ; System, out printIn(s1 equals (s3)) : System. cut -printIn(si.equals(s4)) ; » Output: False False True Diagram: name=vijayabhaskar rollno=101 name=bhaskar rollno=102 st s4 2: name=vijayabhaskar rollno=101 + In the above program Object class .equals() method got executed which is always meant for reference comparison that is if two references pointing to the same object then only .equals(() method returns true. In object class .equals() method is implemented as follows which is meant for reference comparison. ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package Public boolean equals (Object obj) { return (this == obj): } Based on our programming requirement we can override .equals() method for content comparison purpose. ‘When ever we are overriding .equals() method we have to consider the following things : 1. Meaning of content comparison i.e., whether we have to check the names are equal (or) roll numbers (or) both are equal. 2. Ifwe are passing different type of objects (heterogeneous object) our uals() method should return false but not ClassCastException ie., we have to handle ClassCastException to return false. 3. Ifwe are passing null argument our .equals() method should return false but not NullPointerException i.e., we have to handle NullPointerException to return false, 4. The following is the proper way of overriding .equals() method for content comparison in Student class. 5, 6. Example 6: 7. class Student 8 9) String name; int rollno; Student (String name, int rollno) t ‘this.name=name; this.rellno=relino; ) public boolean equals (Object obj) t tay( String namel=this.name; Student 92= String name2=s2. int rollno2=s2.rol1no; if(namel equals (name2) && rollnol—rellno2) t return true; ) else return false; ) catch (ClassCastException e) t return false; ) catch (NullPointerException e) C return false; ? ) public static void main(string!] args) ( Student si=new Student ("vijayabhaskar", 101) ; ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package 41. Student s2enew Student ("bhaskar",102) ; 42. Student s3-new student ("vijayabhaskar",101) ; 43. Student sd=s1; 44. system. out-printIn (st equals (s2)) ; 45. System. out _printIn(s1 equals (#3)) ; 46. System. out.printin(st.equals(s4)) ; 47. System. out. printin(s1.equals ("vijayabhaskar")) ; 48. System. out. printIn(s1.equals ("null")) : 4.) 50. } 51. Output: 52. False 53. True 54. True 55. False 56. False implified version of .equals() method public boolean equals (Object 0) { try( ‘Student =2=(Student)o; if (name equals (22.name) && rollno=s2.rol1no) ( return true; } else return false; ) catch (ClasscastException ¢) [ return false, y catch (NullPointezException e) { return false; } ) er Bek eae public boolean equals (Object 0) { i£(0 instanceof Student) { Student 22=(Student) 07 if(nameequals(s2.name) && rollno—s2.rollno) yetumn true; else wetumn false; return false; » Example 7 : class Student ( String name; int rollno; Student (String name,int rollno) { ‘this-name=name; {9 | DURGASOFT, #202,2"*Fioor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package this. rollno=rolino; ) public boolean equals (Object 0) { if (this: zeturn true; i£(0 instanceof Student) { Student s2=(Student)o; if (name equals (s2.name) &@ rolino: zeturn true; else return false; ) return false: ) public static void main(String] args) { Student s=new Student ("vijayabhaskar",101) ; Integer isnew Integer (10) 7 System, out. printin(s.equals (i)) ; ) } Output: False To make .equals() method more efficient we have to place the following code at the top inside equals) method. if (this=o) return true: Diagram: 2.x0llne) Student s1=new Student("vijayabhaskar",101); Student s4=s1; sl. s If2 references pointing to the same object then .equals() method return true directly without performing any content comparison this approach improves performance of the system StringBuffer s1 = new String ol = new String("ashok") ; attacttaakek hi) String 32 = new String("ashok") ; ee eae eh StringBuffer s2 = new System. out.printIn(si=s2); i : “/false Stringnuffer ("ashok") ; System.out.printin(sl—=s2); //false Ppuekensontrmetntie(stremuate (ea) 12 totem. ut.poiatialal oquaietoe) Jo (fase In StringBuffer class .equals() is not In String class .equals( ) is overridden for overriden for content comparision hence content comparision hence if content is Object class .equals( ) will be executed which same .equals() method returns true, _is meant for reference comparision , hence if even though ths objects are different. objects are different .equals( ) method returns false , even though content is same. 70 | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package Note : In String class , Wrapper classes and all collection classes .equals( ) method is overriden for content comparision REL ee 1. If r==r2 is true then rlequals(r2) is always true i.e, if two objects are equal by operator then these objects are always equal by .equals( ) method also. ESET 2. If r1==12 is false then we can't conclude anything about rl.equals(r2) it may return true (or) false. 3. If requals(r2) is true then we can't conclude anything about rir? it may returns true (or) false. 4. If rLequals(r2) is false then ri==r2 is always false. Dice Cee Te cen ene record == (double equal operator) It is an operator applicable for both primitives and object references. In the case of primitives == (double equal operator) meant for content comparison, but in the case of object references == operator meant for reference comparison. We can't override== operator for content comparison in object references. If there is no relationship between argument types then we will get compile time error saying incompatible types.(relation means child to parent or parent to child or same type) For any object reference r, r==null is always false. String = = new String ("ashok"); equals) method It is a method applicable only for object references but not for primitives. By default .equals() method present in object class is also meant for reference comparison. ‘We can override .equals() method for content comparison, If there is no relationship between argument types then .equals() method simply returns false and we won't get any compile time error and runtime error. For any object reference r, r-equals(null) is also returns false. StringBuffer cb = new StringBuffer ("ashok"); System. out .print1n(s StringBuffer System. cut .printIn(s.equals (sb)); Note: sb); // CE incomparable types : String and / [false in general we can use = (double equal operator) for reference comparison whereas -equals() method for content comparison. 11 ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package ee ene renee ear) 1. If2 objects are equal by .equals() method compulsory their hashcodes must be equal (or) same. That is If r/.equals(r2) is true then rl. hascode()=r2.hashcode() must be true. 2. If2 objects are not equal by .equals() method then there are no restrictions on hashCode() methods. They may be same (or) may be different. That is If rLequals(+2) is false then r1.hashCode(}==r2.hashCode() may be same (or) may be different. 3. Ifhashcodes of 2 objects are equal we can't conclude anything about .equals() method it may returns true (or) false. That is If rl.hashCode()==r2.hashCode() is true then r/.equals(r2) method may returns true (or) false. 4. Ifhashcodes of 2 objects are not equal then these objects are always not equal by -equals() method also. That is If rJ.hashCode(==r2.hashCode() is false then rLequals(r2) is always false. ‘To maintain the above contract between .equals() and hashCode() methods whenever we are overriding .equals() method compulsory we should override hashCode() method. Violation leads to no compile time error and runtime error but it is not good programming practi Example: Consider the following person class. Program: class Person ( String name; int age; Person (String name,int age) ( ‘this-namesname; ‘this. age=age: } public boolean equals (Object 0) ( if (this==o) return true; if(o instanceof Person) { Person p2=(Pezson)o; if (name equals (p2.name) && age==p2. age) return true; else return false; » return false; y public static void main(string{] args) { Person pl=new Person("vijayabhaskar", 101) ; Person p2=new Person("vijayabhaskar",101) ; Integer isnew Integer (102) ; System. cut .printin (pl.equals (p2)) + System. out .printIn (pl.equals(i)) ; } } output: 72 | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package true False ‘Which of the following is appropriate way of overriding hashCode() method? Diagram: x x1)public int hashCode()|2)public int hashCode [z}pubic i Jpublic int hashCode() i : j 4)Any of the above. j return 100; return agetheight;| return name.hashCodel}+age; y 2 Based on whatever the parameters we override ".equals() method" we should use same parameters while overriding hashCodeQ) method also. te: in all wrapper classes, im string class, in all collection classes .equals() method is overridden for content comparison in our classes also it is highly recommended to override .equals() method. Which of the following is valid? 1. If hash Codes of 2 objects are not equal then .equals() method always return false(valid) 2. Example: 3. 4. class Test { 5. int i 6. Test(int i) 7 this isi; 8} 9. public int hashCode () { 10. return i; i ) 12 Public String tostring() ‘ return i+"; y 15. public static void main(string[] args) t 16! ‘Test tienew Test (10); a Test t2=new Test (20) ; 18. System. out .printIn (t1-hashCode ()) ;//10 1s. System. out .printIn (t2.hashCode()) ;//20 20. System.out.printin (t1 hashCode ()—=t2.hashCode()) ;//false a. System-out.printin (t1-equals (£2) ;//false 22. ) 2.) 24. 1f2 objects are equal by == operator then their hash codes must be same.(valid) 25. Example: 26. 27. class Test { 28. int i; 29 Test (int 4) 30. this. 31. } 32. public int hashCode () { 33. return i: 73 | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package 34. 1 35. public string to: nl 36. retura i 37. , 38. public static void main(String!] axgs) fl Test tisnew Test (10); Test t2=t1; System.out _printIn (t1 hashCode ()} ;//10 Syatem.out _printIn (t2 hashCode ()} ;//10 System. out .println (ti=t2) ;//true operator returns false then their hash codes(may be same (or) may be different) must be different. (invalid) 49. Example: 50. 51. class Test { 52. int i; Test(int i) [ this.i=i; ) public int hashCode() { return i; ) public String tostring() ( return i: , public static void main(String{] azgs) ( Test tl=new Test (10) ; Test t2=new Test (10) ; System. out .printin (tl. hashCode ()) ;//10 System.out.printin 2. hashCode ()) ;//10 System. out.printia (ci==t2) 7//false , y 70. If hashcodes of 2 objects are equal then these objects are always equal by operator also.(invalid) GEnEynranes 1. The process of creating exactly duplicate object is called cloning. 2. The main objective of cloning is to maintain backup purposes.(Le., if something goes wrong we can recover the situation by using backup copy.) 3. We can perform cloning by using clone() method of Object class. protected native object clone() throws CloneNotSupportedException: Example class Test implements Cloneable a int 4-10; int 3=20; 74 | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package public static void main(String[] args) throws CloneNotsupportedException Test ti=new Test (); Test t2=(Test)ti.clone(); $2.4=888; €2.5=999; System. out-printIn (t1.i+"~ System. out printin(t2.4+' ‘We can perform cloning only for Cloneable objects. An object is said to be Cloneable if and only if the corresponding class implements Cloneable interface. + Cloneable interface present in java.lang package and does not contain any methods. It is a marker interface where the required ability will be provided automatically by the JVM. + Ifwe are trying to perform cloning or non-clonable objects then we will get RuntimeException saying CloneNotSupportedException. hallow cloning vs Deep cloning een The process of creating bitwise copy of an object is called Shallow Cloning . 2. Ifthe main object contain any primitive variables then exactly duplicate copies will be created in cloned object. 3. If the main object contain any reference variable then the corresponding object won't be created just reference variable will be created by pointing to old contained object. 4. By using main object reference if we perform any change to the contained object then those changes will be reflected automatically to the cloned object , by default Object class clone( ) meant for Shallow Cloning 5. class cat ¢ 6 int 3; 7. Gat(int 3) { 75 | DURGASOFT, #202,2" Floor HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package class Dog implements cat © int i: Dog(cat ¢ , int i) { this.cao ; this.i=i , : Clonable ( Public Object clone( ) throws CloneNotSupportedException { return super.clone( ); class Shallowclone ( public static void main(stzingf ] az) { Cat exnew Cat (20) ; Dog di=new Dog(c , 10) ; Syetem.out.printin(di.i +, stat.g)i 1 10. Dog d2=(Dog) d1-clone( ) ai.ie88 ; al.c.5=999 + System, out.printin(d2.i +. , M1 0..----999 shallow cloning : 37. Shallow cloning is the best choice , if the Object contains only primitive values. 38. In Shallow cloning by using main object reference , if we perform any change to the contained object then those changes will be reflected automatically in cloned copy. 39. To overcome this problem we should go for Deep cloning. 7 | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package Example: Test ti=new Test (); Test 7 Diagram: t1. t2 1. The process of creating exactly independent duplicate object(including contained objects also) is called deep cloning. In Deep cloning , if main object contain any reference variable then the corresponding Object copy will also be created in cloned object. 3. Object class clone) method meant for Shallow Cloning , if we want Deep cloning then the programmer is responsible to implement by overriding clone( ) method. 4. class cat ( 5. int 35 6. cat(int 3) { 7. this.3=3 7 8} 3} 10. 11. class Dog implements Clonable ( w. cate a3. int a: 14. Dog(cat c , ant 4) { 15. this.c=o ; 16. this-i=i ; a7. > 18. Public Object clone( ) throws CloneNotSupportedException { 19. cat cl=new Cat (c.3) 20. Dog di=new Dog(cl » i) ; 21. return di ; 22. ) 23.) 24. 25. class DeepClone { 26. public static void main(String{ ] ar) { 27. Gat c=new Cat (20) ; 28. Dog di=new Doge , 10) ; System. out.printin(dl.i +. stdl.c.3): // 10. Dog d2=(Dog)dt.clone( ) ; d1.i=088 ; a .c.5=999 System.out.printin(@2.i t......482.6.5)7 // 10.064 .20 , 77 | DURGASOFT, #202,2" Floor HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package 36.) 37. deep cloning : d2 38. In Deep cloning by using main Object reference if we perform any change to the contained Object those changes won't be reflected to the cloned object. Example: Test ti=new Test (); Test t2=(Test) ti.clone() ; System.out.printin(tl==t2); _//false System. out.printIn(ti.hashCode()==t2.hashCode()); //false Diagram Which cloning is best ? If the Object contain only primitive variable then Shallow Cloning is the best choice , If the Object contain reference variables then Deep cloning is the best choice. Cloning by default deep clonin; 7g | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package Pre neaee This method returns runtime class definition of an object. Example : class Test implements Cloneable ( public static void main(String[] args) throws CloneNotSupportedException —{ ‘Object omnew String("ashok") : System. out.printIn ("Runtime object type of o is ste. geeciasa ) -geexane() , Output: Runtime object type of o is: java.lang. string Ex : To print Connecton interface implemented vendor specific class name . System. cut.printin(con.getClass( ).getName() ): Ter Just before destroying an object GC calls finalize( ) method to perform CleanUp activities ait( ) , notify() , notifyAll ‘We can use these methods for inter thread communication StringBuffer ab=new StringBuffer ("bhaskar ‘sb. append ("software") ; ‘System. out .printIn(sb) ; String s-new String ("bhaskaz") ; s.concat ("software") ; {//haskaresttvars ‘System, out.printin(s) ;//bhaskar Once we created a StringBuffer Once we create a String object we can't perform any bject we can perform any changes in the existing object. If we are try to changes in the existing object. perform any changes with those changes a new [This behavior is called mutability ‘object will be created. This behavior is called of the StringBuffer object. immutability of the String object. Diagram: Diagram: sb bhaskarsoftware 79 | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package <> Case2: String si=new String(""ashok") ; String s2=new String("achok") ; System. out.printin(si—=s2) ;//false System, out. printin (si-equals(s2)) :/ /true In String class .equals() method is overridden for content comparison hence if the content is same .equals() method returns true even though objects are different. Case 3: String ssnew String ("bhaskar") ; In this case two objects will be created one is on the heap the SCP(String constant pool) and s is always pointing other one is ‘to heap object. Diagram: Heap bhaskarsoftware it has no reference that's why it is eligible for GC. StringBuffer sbi-new StringBuffer ("ashok") ; StringBuffer sb2-new StringBuffer ("ashok") ; System. out.printin (sbi==sb2) ;//false System. out printin (sb1.equals (sb2)) :// false In StringBuffer class .equals() method is not overridden for content comparison hence Object class .equals() method got executed which is always meant for reference comparison. Hence if objects are different ‘equals() method returns false even though content is same. Steing s="bhaskar"; In this case only one “object will be created in SCP and s is always referring that object. Diagram : scp tp so 20 | DURGASOFT, #202,2" Floor HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package 1. Object creation in SCP is always optional 1st JVM will check is any object already created with required content or not. If it is already available then it will reuse existing object instead of creating new object. If it is not already there then only a new object will be created. Hence there is no chance of existing 2 objects with same content on SCP that is duplicate objects are not allowed in SCP. 2. Garbage collector can't access SCP area hence even though object doesn't have any reference still that object is not eligible for GC ifit is present in SCP. 3. All SCP objects will be destroyed at the time of JVM shutdown automatically. Example 1: String si=new string("bhaskar") ; String s2-new String("bhaskaz") ; String 23="bhaskar"; String When ever we are using new operator compulsory a new object will be created on the Heap . There may be a chance of existing two objects with same content on the heap but there is no chance of existing two objects with same content on SCP. i¢., duplicate objects possible in the heap but not in SCP. Hea) scp Example 2: String ssnew String ("bhaskar") ; s.concat ("software") ; s¢5.concat ("solutions") ; Dy | DURGASOFT, #202,2" Floor HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package Heap scp bhaskar bhaskarsoftware bhaskarsolutions i Ss bhaskarsoft ( For every String Constant one object will be created in SCP. Because of runtime operation if an object is required to create compulsory that object should be placed on the heap but not SCP. Example 3: String si-new String("spring") ; si.concat ("fall") ; siésit"winter"; String s2=s1.concat ("sumex") ; System. cut.printin(st) ; System out printin(s2) ; 2a | BURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package Diagram ; Heap ED s1. springwinter total:8(4+4) igible for gc=2 Example class Stringdeno € public static void main(string[] args) 4 String sl=new String("you cannot change me! String =2—new String("you cannot change ma! System. out.printIn(sl—s2) ;//false String s3="you cannot change me!"; System. out-printIn(si=s3) ;//false String s4="you cannot change me!"; Syatem. out.printn (23: String =5="you cannot " System. out .printn (s3: String s6="you cannot String s7=s6+"change me!"; System, out .printIn (s3==s7) ;//false final String s8="you cannot "; String =9=s6+"change me! System. out.printin (s3=s9) ;//true System. out .printin(s6=s8) ;//true 3 | DURGASOFT, #202,2"Floor HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package Heap | SCP. ou cannot change mel a 83 s4 2 5 L____'s9 7 sé L__sg importance of String constant pool (SCP) Voter Registration Form Name: FatherName{___ dos: Age: ( Address:[__ City: State:-—] 1. In our program if any String object is required to use repeatedly then it is not recommended to create multiple object with same content it reduces performance of the system and effects memory utilization. 2. We can create only one copy and we can reuse the same object for every requirement. This approach improves performance and memory utilization we can achieve this by using "sep". 3. In SCP several references pointing to same object the main disadvantage in this approach is by using one reference if we are performing any change the remaining references will be impacted. To overcome this problem sun people implemented immutability concept for String objects. 2a | URGASOFT, #202,2" Floor HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package 4. According to this once we creates a String object we can't perform any changes in the existing object if we are trying to perform any changes with those changes a new String object will be created hence immutability is the main disadvantage of sep. 1. What is the main difference between String and StringBuilder? 2. What is the main difference between String and StringBuffer ? 3. Other than immutability and mutability is there any other difference between String and StringBuffer ? In String .equals() method meant for content comparison where as in StringBuffer meant for reference comparisi 4. What is the meaning of immutability and mutability? 5. Explain immutability and mutability with an example? 6. What is SCP? A specially designed memory area for the String literals/objects . 7. What is the advantage of SCP? Instead of creating a separate object for every requirement we can create only ‘one object and we can reuse same object for every requirement. This approach improves performance and memory utilization. 8. Whats the disadvantage of SCP? In SCP as several references pointing to the same object by using one reference if we are performing any changes the remaining references will be inflected. To prevent this compulsory String objects should be immutable. That is immutability is the disadvantage of SCP. 9. Why SCP like concept available only for the String but not for the StringBuffer? As String object is the most commonly used object sun people provided a specially designed memory area like SCP to improve memory utilization and performance. But StringBuffer object is not commonly used object hence specially designed memory area is not at all required. 10. Why String objects are immutable where as StringBuffer objects are mutable? In the case of String as several references pointing to the same object, by using one reference if we are allowed perform the change the remaining references will be impacted. To prevent this once we created a String object we can't perform any change in the existing object that is immutability is only due to SCP. But in the case of StringBuffer for every requirement we are creating a separate De | DURGASOFT, #202,2" Floor HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package object will be created by using one reference if we are performing any change in the object the remaining references won't be impacted hence immutability concept is not require for the StringBuffer. 11. Similar to String objects any other objects are immutable in java? In addition to String objects , all wrapper objects are immutable in java. 12. Is it possible to create our own mutable class? Yes. 13. Explain the process of creating our own immutable class with an example? 14, What is the difference between final and immutability? 15, What is interning of String objects? interning of String objects By using heap object reference, if we want to get corresponding SCP object , then we should go for intern() method. Example 1: class Stringdeno { public static void main(String!] args) ( String sl=new String("bhaskar") ; String s2=s1.intern() : Systen.out.printin(si=a2); //falee String #3="bhasieas" System. out. printin(s2—=s3) ://true If the corresponding object is not there in SCP then intern() method itself will create that object and returns it [e | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package Example 2: class StringDeno { public static void main(String{] args) rl String sinew String("bhaska") ; String s2=s1-concat("softwaze") ; String s3=s2.intern(); String s4="bhaskarsoftware"; System. out.printin (s3=s4) ;//ezue y } Diagram 2: Tees 1. String s=new String(); Creates an empty String Object. 2. String s=new String(String literals); To create an equivalent String object for the given String literal on the heap. 3. String snew String(StringBuffer sb); Creates an equivalent String object for the given StringBuffer. 4. String s=new String(char{] ch); 27 | BURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package creates an equivalent String object for the given chart ] array. Example: class StringDemo { public static void main(String{] args) ( char[] ch={'a',"b','c'} 7 String s=new String (ch) ; System.cut.printn(ch) ;//abe ) } 5. String s=new String(byte[] b); Create an equivalent String object for the given byte(] array. Example: class StringDeno { public static void main(String[] args) { byte[] b={100,101,102); String s-new String (b) ; System.cut.println(s) ;//def ) > Mcnsesen ee 1. public char charA((int index); Returns the character locat ig at specified index. Example: class Stringdemo ( public static void main(String{] args) ( Bering sstashok"; System. out .printin (s.chaxAt(3)) ://o System.out.printin(s.charAt(100));// RE : StringIndexcutofBoundsException d y // index is zero based 2. public String concat(String str); 3. Example: 4. class StringDemo { 5. public static void main(String!] args) { 6 i, 8 8 String ss"ashok"; s=5.concat ("software") ; //s2s+"'softwas //st=" software" ; 10. System. out-printIn(s) ;//ashoksoftware n. ) wz.) 2g | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package The overloaded "+" and "+=" operators also meant for concatenation purpose only. 13. public boolean equals(Object 0); For content comparison where case is important. Itis the overriding version of Object class .equals() method. 14, public boolean equalsIgnoreCase(String 5); For content comparison where case is not importam Example: class StringDemo { public static void main(String{] args) rl String s="java"; System.cut.printin (s equals ("JAVA")) ://false System out println (s equal signoreCase ("JAVA") ://true y y Note: We can validate username by using .equalsIgnoreCase() method where case is not important and we can validate password by using .equals() method where case is important. 15. public String substring(int begin); Return the substring from begin index to end of the string. Example: class StringDemo { public static void main(String{] args) { String s=vashoksoft™ system out-println (s substring (S)) ://eoft , y 16. public String substring(int begin, int end); Returns the substring from begin index to end-1 index. Example: class StringDemo { public static void main(string[] args) { String s=Vashoksoft"; System.out .printIn(s.substring(5)) ;//soft System.out .printIn(s.substring(3,7)) ;//okso y ) 17. public int length; 2g | DURGASOFT, #202,2" Floor HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package Returns the number of characters present in the string. Example: class StringDemo { public static void main(String!] args) { String s="jobs4tines"; System.out-printIn(s.length()) ;//10 //System.out.printin(s-length) ;//compile time error StringDemo.java:7: cannot find symbol symbol: variable length ecrtlons claen jmen-lang, sting Note: length is the variable applicable for arrays where as length( method is applicable for String object. 18. public String replace(char old, char new); To replace every old character with a new character. Example: class Stringdeno ( public static void main(String{] args) { String s="ababab"; System.out .printIn(s.replace('a', 'b') } ) 19. public String toLowerCase(); Converts the all characters of the st gto lowercase. Example: class StringDemo { public static void main(String{] args) { String e="ASHOR"; Systen.out printin(s y r -clowerCase()) ;//ashok 20. public String toUpperCase(; Converts the all characters of the string to uppercase. Example : class StringDemo { public static void main(String[] args) { String s="ashok"; 30 | DURGASOFT, #202,2" Floor HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package ‘System. out .printIn (s.toUpperCase ()) ;//ASHOK ) ) 24. public String trimQ; ‘We can use this method to remove blank spaces present at beginning and end of the string but not blank spaces present at middle of the String. Example: class StringDemo { public static void main(String[] args) { String s=" sai charan "; System.out.printIn(s.trim()) ;//sai charan ) ) 22. public int indexOf(char ch); It returns index of 1st occurrence of the specified character if the specified character is not available then return -1. Example: class StringDemo { public static void main(string[] args) { String s="saicharan"; System.out .printIn (s.indexo£('e")) ; System.out.printin(s.indexof('z")); // -1 y ) 23. public int lastIndexOf(Char ch); It returns index of last occurrence of the specified character if the specified character is not available then return -1. Example: class Stringdemo { public static void main(String[] args) { String s="arunkumar"; ‘System.out .printIn (s.lastIndexf ("a") ://7 Systam.out .printin(s.indexof ("2") ;//-1 } Note: ‘Because runtime operation if there is a change in content with those changes a new object will be created only on the heap but not in St If there is no change in content no new object will be created the same object will be reused. This rule is same whether object present on the Heap or SCP 31 | DURGASOFT, #202,2" Floor HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir java.iang package Example 1 class StringDeno public static void main(string{] args) ( String sl="bhaskar"; String s2=s1.toUppercase() String s3=81.toLowerCase () : System.out.printin (s1=s2) ;//£alse system out println (si==s3) ;//t=ue } » Diagram Hea s3 class StringDemo ( public static void main(String[] args) { String si="bhaskar"; String s2=s1.toString(); System.out .printIn(sl==s2) ;//true ) Hea scp <_< s2 class StringDeno { public static void main(string[] args) { String si=new String ("ashok"); String s2=21.tostring() String s3=s1.toUppercase() ; String s4=s1.totowercase (): String s5=s1.toUpperCase () ; String s6=33.totowerCase (); 32 | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com

You might also like