{"id":16355,"date":"2016-10-08T12:00:44","date_gmt":"2016-10-08T12:00:44","guid":{"rendered":"https:\/\/www.whizlabs.com\/?p=16355"},"modified":"2024-05-17T12:32:25","modified_gmt":"2024-05-17T07:02:25","slug":"ocajp-string-object","status":"publish","type":"post","link":"https:\/\/www.whizlabs.com\/blog\/ocajp-string-object\/","title":{"rendered":"OCAJP &#8211; Creating and Manipulating Strings"},"content":{"rendered":"<p>This post is about the OCAJP exam objective \u201cCreating and Manipulating Strings\u201d. <strong>You will be mainly tested in the exam about String Immutability behavior.<\/strong> You will also be tested in the exam about various methods and syntax related to the String class. Here we would explain about the String class and important methods. It is very important to understand the concepts of String and how it is being created and manipulated inside JVM to effectively answer the questions in the OCAJP exam.<\/p>\n<p>If you are preparing for the OCAJP exam, please try our <a href=\"https:\/\/www.whizlabs.com\/ocajp-scja\/ocajp8-free-test\/\">free OCAJP 8 mock exam questions<\/a>. Also send your feedback to <strong>feedback@whizlabs.com<\/strong>.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.whizlabs.com\/blog\/wp-content\/uploads\/2024\/05\/free_test.jpg\" alt=\"OCAJP 8 Free Test\" class=\" aligncenter\" \/><\/p>\n<p>Here is the some important points about the String class:<\/p>\n<ul>\n<li>String is a class present in java.lang package since Java 1.0 version.<\/li>\n<li>String is a final class and implemented three interfaces CharSequence, Comparable and Serializable .<\/li>\n<li>String class is Immutable which means once String object is created , its contents can\u2019t be changed.<\/li>\n<li>If you try to change string object with its methods, a new object will be created with modified content. But the original object remains same.<\/li>\n<li>String class is not thread safe.<\/li>\n<li>String(Ex: \u201cJava\u201d) is a object which contains sequence of characters in Java<\/li>\n<li>Whatever you write within double quotes (Ex: \u201cJava\u201d) is a String object in Java.<\/li>\n<\/ul>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_76 ez-toc-wrap-left counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #ea7e02;color:#ea7e02\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #ea7e02;color:#ea7e02\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.whizlabs.com\/blog\/ocajp-string-object\/#Creating_String_Objects\" >Creating String Objects<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.whizlabs.com\/blog\/ocajp-string-object\/#Garbage_Collection\" >Garbage Collection<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.whizlabs.com\/blog\/ocajp-string-object\/#String_Methods\" >String Methods<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.whizlabs.com\/blog\/ocajp-string-object\/#Concatenation\" >Concatenation<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.whizlabs.com\/blog\/ocajp-string-object\/#Conclusion\" >Conclusion<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.whizlabs.com\/blog\/ocajp-string-object\/#References\" >References<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"Creating_String_Objects\"><\/span>Creating String Objects<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p><strong>There are two ways of constructing String object.\/strong&gt;<\/strong><\/p>\n<p><strong>1)Without new operator<\/strong><\/p>\n<p>You can create String object without new object.<\/p>\n<p><span style=\"text-decoration: underline\"><strong>Example :<\/strong><\/span><\/p>\n<pre>public class StringCreation {\r\n    public static void main(String[] args) {\r\n\tString s1 = \"Java\"; \/\/Line 1\r\n\tString s2 = \"Java\"; \/\/Line 1\r\n        System.out.println(s1 == s2); \/\/prints true \r\n    }\r\n}\r\n<\/pre>\n<ul>\n<li>When a class is loaded, the JVM goes through the code for the class and looks for String literals. When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the String constant pool.<\/li>\n<li>Once a reference is made to that String object, any references to that String literal throughout your program are simply replaced with the reference to the object referenced from the String Constant Pool.<\/li>\n<li>So, in the example shown above, there would be only one entry in the String constant pool, which would refer to a String object that contained the word &#8220;Java&#8221;. Both of the local variables, s1 and s2 would be assigned a reference to that single String object.<\/li>\n<\/ul>\n<p><strong>Look at the below the diagram to understand better.<\/strong><\/p>\n<p><a href=\"https:\/\/www.whizlabs.com\/blog\/wp-content\/uploads\/2024\/05\/string-objects.png\"><img decoding=\"async\" src=\"https:\/\/www.whizlabs.com\/blog\/wp-content\/uploads\/2024\/05\/string-objects.png\" alt=\"String Objects - OCAJP\" width=\"674\" height=\"401\" class=\"aligncenter  wp-image-16358\" \/><\/a><\/p>\n<p><strong>2) With new operator<\/strong><br \/>\n<span lang=\"EN-US\"><\/span><\/p>\n<p>String class has 13 constructors. We will understand only the important constructors used in the String class.<\/p>\n<ul>\n<li>String()<\/li>\n<li>String(char[] value)<\/li>\n<li>String(String original)<\/li>\n<li>String(StringBuffer buffer)<\/li>\n<li>String(StringBuilder builder)<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example :<\/strong><\/span><\/p>\n<pre>public class StringCreation {\r\n    public static void main(String[] args) {\r\n\tchar[] ch = { 'O', 'A', 'J', 'P' };\r\n\tStringBuffer sb1 = new StringBuffer(\"OCAJP\");\r\n\tStringBuilder sb2 = new StringBuilder(\"OCAJP\");\r\n\tString s = \"OCAJP\";\r\n\tString s1= new String(ch); \/\/Line 1\r\n\tString s2= new String(sb1); \/\/Line 2\r\n\tString s3= new String(sb2);\/\/Line 3\r\n\tString s4= new String(s);\/\/Line 4\r\n\tString s5= new String(\"OCAJP\");\/\/Line 5\r\n\r\n\tSystem.out.println(\"String object from char array: \"+s1);\r\n\tSystem.out.println(\"String object from StringBuffer: \"+s2);\r\n\tSystem.out.println(\"String object from StringBuilder: \"+s3);\r\n\tSystem.out.println(\"String object from String: \"+s4);\r\n\tSystem.out.println(\"String object from String: \"+s5);\r\n   }\r\n}\r\n<\/pre>\n<p><strong>It outputs like:<\/strong><\/p>\n<pre>String object from char array: OAJP\r\nString object from StringBuffer: OCAJP\r\nString object from StringBuilder: OCAJP\r\nString object from String: OCAJP\r\nString object from String: OCAJP\r\n<\/pre>\n<ul>\n<li>Line1, Line 2 , Line 3 , Line 4,Line 5 shows the ways to create String object from character array, StringBuffer object, StringBuilder object, String object.<\/li>\n<li>You can check the remaining constructors details at Java Doc ( <a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/lang\/String.html\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/lang\/String.html<\/a>).<\/li>\n<\/ul>\n<p><strong>Difference between using new Operator and without new Operator object creation:<\/strong><\/p>\n<p><span style=\"text-decoration: underline\"><strong>Example:<\/strong><\/span><\/p>\n<pre>public class StringCreationCompare {\r\n    public static void main(String[] args) {\r\n\tString s1 = \"Java\";\/\/Line1\r\n\tString s2 = new String(\"Java\");\/\/Line2\r\n\tString s3 = new String(\"Java\").intern();\/\/Line3\r\n\tSystem.out.println((s1 == s2));\/\/prints false\r\n\tSystem.out.println((s1 == s3)); \/\/ prints true\r\n   }\r\n}\r\n<\/pre>\n<ul>\n<li>I hope you know == operator working. == operator compares objects references and it doesn\u2019t compare the contents. If two reference variables are referring to same object , it returns true otherwise false.<\/li>\n<li>When a class is loaded, the JVM goes through the code for the class and looks for String literals. When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the String constant pool. Once a reference is made to that String object, any references to that String literal throughout your program are simply replaced with the reference to the object referenced from the String Constant Pool.<\/li>\n<li>So, in the example shown above, there would be only one entry in the String constant pool, which would refer to a String object that contained the word &#8220;Java&#8221;. The local variable s1 would be assigned a reference to that single String object.<\/li>\n<li>At line 2, there is keyword &#8220;new,&#8221; the JVM is obliged to create a new String object at run-time, rather than using the one from the String constant pool and s2 is the reference for that new object.<\/li>\n<li>At Line 3 , there is intern() method which first checks string constant pool, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.<\/li>\n<li>String constant pool has already contained object with same content, so reference for that object will be returned.<\/li>\n<li>So s1,s3 are referring to the same object, s2 is referring to the another object.<\/li>\n<\/ul>\n<p>Look at the below diagram to get more clarity.<\/p>\n<p><a href=\"https:\/\/www.whizlabs.com\/blog\/wp-content\/uploads\/2024\/05\/string-ocajpexample.png\"><img decoding=\"async\" src=\"https:\/\/www.whizlabs.com\/blog\/wp-content\/uploads\/2024\/05\/string-ocajpexample.png\" alt=\"String Objects Example in OCAJP\" width=\"664\" height=\"417\" class=\"aligncenter size-full wp-image-16359\" \/><\/a><\/p>\n<h2><span class=\"ez-toc-section\" id=\"Garbage_Collection\"><\/span>Garbage Collection<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Let&#8217;s look at the below example program.<\/p>\n<pre>public class StringCreationCompare {\r\n    public static void main(String[] args) {\r\n\tString s1 = \"Java\";\/\/Line1\r\n\tString s2 = new String(\"Java\");\/\/Line2\r\n\tString s3 = new String(\"Java\").intern();\/\/Line3\r\n       \ts1=s2=s3=null;\r\n    }\r\n}\r\n<\/pre>\n<ul>\n<li>How many objects are eligible for garbage collection ? Did you say 1. Yes 1 object is eligible for garbage collection.<\/li>\n<li>Unlike most objects, String literals always have a reference to them from the String Constant Pool. That means that they always have a reference to them and are, therefore, not eligible for garbage collection.<\/li>\n<\/ul>\n<p>Look at the below diagram to get more clarity.<\/p>\n<p><a href=\"https:\/\/www.whizlabs.com\/blog\/wp-content\/uploads\/2024\/05\/garbagecollection-ocajp.png\"><img decoding=\"async\" src=\"https:\/\/www.whizlabs.com\/blog\/wp-content\/uploads\/2024\/05\/garbagecollection-ocajp.png\" alt=\"Garbage Collection in OCAJP\" width=\"607\" height=\"428\" class=\"aligncenter size-full wp-image-16360\" \/><\/a><\/p>\n<h2><span class=\"ez-toc-section\" id=\"String_Methods\"><\/span>String Methods<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In the subsequent sections, we would look at the various important String class&#8217;s methods and how to use them. These methds are very important for preparing OCAJP exam, in the exam you will be tested to answer the questions that are related to operations using the String methods.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Concatenation\"><\/span>Concatenation<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Generally Concatenation means adding two things together. In Java, concatenation means adding two String objects together. We can achieve String objects concatenation using \u2018+\u2019 operator and concat method. When you concat two string objects, a new String object will be created.But original object doesn\u2019t get changed.<\/p>\n<p><strong>concat():<\/strong><br \/>\n<strong>public String concat(String str)<\/strong><\/p>\n<ul>\n<li>This method adds the specified string to the end of this string and returns a new String object . But the original object doesn\u2019t get changed. This concept is \u201cImmutability\u201d.<\/li>\n<li>If the length of the argument string is 0, then reference to same object will be returned. Otherwise, a new String object is returned that represents a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string. But the original object doesn\u2019t get changed<\/li>\n<li>Keep this point in mind. Because most of the questions will test in this concept ( Immutability).<\/li>\n<li>Look at the below example to understand the Immutability concept practically.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example :<\/strong><\/span><\/p>\n<pre>public class StringConcat {\r\n\tpublic static void main(String[] args) {\r\n\t\tString s1 = \"OCA\"; \/\/Line 1\r\n\t\tString s2 = s1.concat(\"JP8\");\/\/Line 2\r\n\t\tString s3 = s1 +\"JP8\"; \/\/Line 3\r\n\t\tSystem.out.println(\"s1 content : \"+s1);\r\n\t\tSystem.out.println(\"s2 content : \"+s2);\r\n\t\tSystem.out.println(\"s3 content : \"+s3);\r\n\t\tSystem.out.println(\"s1==s2 : \"+(s1==s2));\r\n\t\tSystem.out.println(\"s1==s3 : \"+(s1==s3));\r\n\t\tSystem.out.println(\"s2==s3 : \"+(s2==s3));\t\t\r\n\t}\r\n}\r\n<\/pre>\n<p><strong>It outputs like:<\/strong><\/p>\n<pre>s1 content : OCA\r\ns2 content : OCAJP8\r\ns3 content : OCAJP8\r\ns1==s2 : false\r\ns1==s3 : false\r\ns2==s3 : false\r\n<\/pre>\n<ul>\n<li>At Line 1 String object is created with content OCA and s1 is the reference for that object.<\/li>\n<li>At Line 2 , concat method adds JP8 to the s1 object and creates new object with content OCAJP8 and s2 is the reference for that object.<\/li>\n<li>At Line 3 you are adding s1 with object \u201cJP8\u201d using + operator, new object will be created with content OCAJP8 and s3 is the reference for that object.<\/li>\n<li>s1,s2 are referencing to the different objects, so s1==s2 gives false<\/li>\n<li>s1,s3 are referencing to the different objects, so s1==s3 gives false.<\/li>\n<li>S2,s3 are referencing to the different objects, so s2==s3 gives false.<\/li>\n<\/ul>\n<p><strong>length(),isEmpty()<\/strong><\/p>\n<ul>\n<li>public int length() : This method returns the number of characters present in the String object.<\/li>\n<li>public boolean isEmpty() : This method returns true if string doesn\u2019t contain any characters(zero characters) otherwise returns false.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example :<\/strong><\/span><\/p>\n<pre>public class StringLength {\r\n   public static void main(String[] a) {\r\n\tString s = \"OCAJP8\";\r\n\tString s1=\"\";\r\n\tSystem.out.println(\"Length of s: \"+s.length());\/\/prints 6 \r\n        System.out.println(\"s is Empty or not: \"+s.isEmpty());\/\/prints false\r\n        System.out.println(\"s1 is Empty or not: \"+s1.isEmpty());\/\/prints true\r\n    }\r\n}\r\n<\/pre>\n<ul>\n<li>Here s.length() returns 6 because object contains 6 characters.<\/li>\n<li>s.isEmpty() returns false because object contains characters.<\/li>\n<li>s1.isEmpty() returns true because object doesn\u2019t contain characters.<\/li>\n<\/ul>\n<p><strong>charAt(),toCharArray()<\/strong><br \/>\n<strong>public char charAt(int index)<\/strong><\/p>\n<ul>\n<li>Returns the char value at the specified index. An index ranges from 0 to length() &#8211; 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.<\/li>\n<li>It throws IndexOutOfBoundsException, but it practically throws String IndexOutOfBoundsException.<\/li>\n<\/ul>\n<p><strong>public char[] toCharArray()<\/strong><\/p>\n<p>This method converts string object into char array.<\/p>\n<p><span style=\"text-decoration: underline\"><strong>Example:<\/strong><\/span><\/p>\n<pre>import java.util.Arrays;\r\npublic class StringLength {\r\n\tpublic static void main(String[] a) {\r\n\t\tString s = \"OCAJP8\";\r\n\t\tSystem.out.println(\"char At 2 : \" + s.charAt(2));\r\n\t\tchar[] ch = s.toCharArray();\r\n\t\tSystem.out.println(\"char array from string object : \"\r\n\t\t\t\t+ Arrays.toString(ch));\r\n\t}\r\n}\r\n<\/pre>\n<p><strong>It outputs like<\/strong><\/p>\n<pre>char At 2 : A\r\nchar array from string object : [O, C, A, J, P, 8]\r\n<\/pre>\n<p><strong>trim(),toString(),toUpperCase,toLowerCase,valueOf(),toCharArry()<\/strong><\/p>\n<ul>\n<li>public String toLowerCase() : This method converts string objects characters into lower case and returns new String object.<\/li>\n<li>public String toUpperCase() : This method converts string objects characters into upper case and returns new String object.<\/li>\n<li>public String trim() : It removes any leading and trailing whitespace in string object and returns new String object. It means, It will removes spaces at the starting and ending of character sequence in the string object.<\/li>\n<li>public String toString() : It returns the string object with the same content as the original content.<\/li>\n<li>public String ValueOf : This method is overloaded.valueOf method takes either boolean value or char value or double value or float value or int value or long value or char array or Object (you can pass any object) as argument and returns new String object with the particular content.<\/li>\n<li>public char[] toCharArray() : This method converts the string to a new character array and returns that character array.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example:<\/strong><\/span><\/p>\n<pre>class Test{\r\n\tString name;\r\n\tTest(String name){\r\n\t\tthis.name=name;\r\n\t}\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn \"[name=\" + name + \"]\";\r\n\t}\r\n\t\r\n}\r\npublic class StringOperations {\r\n\tpublic static void main(String[] a) {\r\n\t\tString s1 = \"OCAJP8\";\r\n\t\tString s2 = \"  OCA  \";\r\n\t\tchar [] c = s1.toCharArray(); \r\n\t\tSystem.out.println(\"Without Spaces : \"+s2.trim());\r\n\t\tSystem.out.println(\"s1 toString : \"+s1.toString());\r\n\t\tSystem.out.println(\"s1 to lower case : \"+s1.toLowerCase());\r\n\t\tSystem.out.println(\"s1 to upper case : \"+s1.toUpperCase());\r\n                System.out.println(\"s1 to char array : \"+Arrays.toString(c));\r\n\t     int i=10;\r\n\t     char[] ch = {'O','C','A'};\r\n\t     Test t = new Test(\"OCA\");\r\n\t     System.out.println(\"int to String : \"+String.valueOf(i));\r\n\t     System.out.println(\"char to String : \"+String.valueOf(ch));\r\n\t     System.out.println(\"Test to String : \"+String.valueOf(t));\r\n\t}\r\n}\r\n<\/pre>\n<p><strong>It outputs like<\/strong><\/p>\n<pre>Without Spaces : OCA\r\ns1 toString : OCAJP8\r\ns1 to lower case : ocajp8\r\ns1 to upper case : OCAJP8\r\ns1 to char array : [O, C, A, J, P, 8]\r\nint to String : 10\r\nchar to String : OCA\r\nTest to String : [name=OCA]\r\n<\/pre>\n<p><strong>equals(),equalsIgnoreCase()<\/strong><\/p>\n<ul>\n<li>public boolean equals(Object anObject) : This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object other wise false. It is case sensitive.<\/li>\n<li>public boolean equalsIgnoreCase(String anotherString) : This method compares this String to another String, ignoring case considerations. It returns true if two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case otherwise false.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example:<\/strong><\/span><\/p>\n<pre>public class StringEquals {\r\n\tpublic static void main(String[] args) {\r\n\t\tString s1 = \"OCA\";\r\n\t\tString s2 = \"OCA\";\r\n\t\tString s3 = \"oca\";\r\n\t\tSystem.out.println(s1.equals(s2));\/\/Line 1\r\n\t\tSystem.out.println(s1.equals(s3));\/\/Line 2\r\n                System.out.println(s1.equalsIgnoreCase(s3));\/\/Line 3\r\n     }\r\n}\r\n<\/pre>\n<p><strong>It outputs like:<\/strong><\/p>\n<pre>true\r\nfalse\r\ntrue\r\n<\/pre>\n<ul>\n<li>Line 1 prints true because s1, s2 contains same character sequence and letters case is also matched.<\/li>\n<li>Line 2 prints false because s1, s3 contains same character sequence but the letters case is not matched.Since equals method is case sensitive , it returns false.<\/li>\n<li>Line 3 prints true because s1, s3 contains same character sequence. So equalsIgnoreCase returns true, because it is not case sensitive.<\/li>\n<\/ul>\n<p><strong>contains(),replace()<\/strong><\/p>\n<p>contains() : public boolean contains(CharSequence s)<\/p>\n<ul>\n<li>This method returns true if and only if this string contains the specified sequence of char values otherwise false.<\/li>\n<li>You can pass string object or StringBuilder or StringBuffer as arguments to this method.<\/li>\n<li>This method is case sensitive.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example:<\/strong><\/span><\/p>\n<pre>public class StringEquals {\r\n\tpublic static void main(String[] args) {\r\n\t\tString s1 = \"OCAJP8\";\r\n\t\tString s2 = \"OCA\";\r\n\t\tStringBuilder sb1 = new StringBuilder(\"OCA\");\r\n\t\tStringBuffer sb2 = new StringBuffer(\"jp8\");\r\n\t\tStringBuffer sb3 = new StringBuffer(\"JP8\");\r\n\t\tSystem.out.println(s1.contains(s2));\/\/Line1\r\n\t\tSystem.out.println(s1.contains(sb1));\/\/Line2\r\n\t\tSystem.out.println(s1.contains(sb2));\/\/Line3\r\n\t\tSystem.out.println(s1.contains(sb3));\/\/Line4\r\n\r\n\t}\r\n\r\n}\r\n<\/pre>\n<p><strong>It outputs like:<\/strong><\/p>\n<pre>true\r\ntrue\r\nfalse\r\ntrue\r\n<\/pre>\n<ul>\n<li>Line 1 prints true because s1 contains s2 character sequence<\/li>\n<li>Line 2 prints true because s1 contains sb1 character sequence.<\/li>\n<li>Line 3 prints false because s1 contains sb2 character sequence.But the letters case is not matched.<\/li>\n<li>Line 4 prints true because s1 contains sb2 character sequence.Here,the letters case is matched.<\/li>\n<\/ul>\n<p><strong>replace()<\/strong><\/p>\n<ul>\n<li>replace method is overloaded.<\/li>\n<li>It is also case sensitive.<\/li>\n<li>public String replace(char oldChar, char newChar)<\/li>\n<li>This method replaces all occurrences of oldChar in this string with newChar and returns new String object with modified content.<\/li>\n<li>If oldChar is not occurred in this String object, a reference to the original object will be returned.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example:<\/strong><\/span><\/p>\n<pre>public class StringReplace {\r\n\tpublic static void main(String[] args) {\r\n\t\tString s1 = \"OCAJP8\";\r\n\t\tString s2 = s1.replace('A', 'a');\r\n\t\tString s3 = s1.replace('Z', 'a');\r\n                String s4 = s1.replace('a', 'x');\r\n\r\n\t\tSystem.out.println(s1);\r\n\t\tSystem.out.println(s2);\r\n\t\tSystem.out.println(s1 == s2);\r\n\t\tSystem.out.println(s3);\r\n\t\tSystem.out.println(s1 == s3);\r\n        System.out.println(s4);\r\n       System.out.println(s1 == s4);\r\n\t}\r\n}\r\n<\/pre>\n<p><strong>It outputs like<\/strong><\/p>\n<pre>OCAJP8\r\nOCaJP8\r\nfalse\r\nOCAJP8\r\ntrue\r\nOCAJP8\r\ntrue\r\n<\/pre>\n<p><strong>public String replace(CharSequence target, CharSequence replacement)<\/strong><\/p>\n<ul>\n<li>This method replaces all occurrences of target character sequence in this string with replacement character sequence and returns new String object with modified content.<\/li>\n<li>If target character sequence is not occurred in this String object, a reference to the original object will be returned<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example:<\/strong><\/span><\/p>\n<pre>public class StringReplace {\r\n    public static void main(String[] args) {\r\n\tString s1 = \"OCAJP8\";\r\n\tString s = \"a\";\r\n\tStringBuilder sb1 = new StringBuilder(\"A\");\r\n\tStringBuilder sb2 = new StringBuilder(\"a\");\r\n\tStringBuffer sb3 = new StringBuffer(\"Z\");\r\n\tString s2 = s1.replace(sb1, s);\r\n\tString s3 = s1.replace(sb2, s);\r\n\tString s4 = s1.replace(sb3, s);\r\n\r\n\tSystem.out.println(s1);\r\n\tSystem.out.println(s2);\r\n\tSystem.out.println(s1 == s2);\r\n\tSystem.out.println(s3);\r\n\tSystem.out.println(s1 == s3);\r\n\tSystem.out.println(s4);\r\n\tSystem.out.println(s1 == s4);\r\n   }\r\n}\r\n<\/pre>\n<p><strong>It outputs like<\/strong><\/p>\n<pre>OCAJP8\r\nOCaJP8\r\nfalse\r\nOCAJP8\r\ntrue\r\nOCAJP8\r\ntrue\r\n<\/pre>\n<p><strong>startsWith(), endsWith()<\/strong><br \/>\n<strong>startsWith()<\/strong><\/p>\n<ul>\n<li>public boolean startsWith(String prefix) : This method returns true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise. Note also that true will be returned if the argument is an empty string or is equal to this String object.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example:<\/strong><\/span><\/p>\n<pre>public class StringStarts {\r\n    public static void main(String[] args) {\r\n\tString s1 = \"OCAJP8\";\r\n\tboolean b1 = s1.startsWith(\"OC\");\r\n\tboolean b2 = s1.startsWith(\"\");\r\n\tboolean b3 = s1.startsWith(\"OCAJP8\");\r\n\tboolean b4 = s1.startsWith(\"OCP\");\r\n\t\t\r\n\tSystem.out.println(b1);\r\n\tSystem.out.println(b2);\r\n\tSystem.out.println(b3);\r\n\tSystem.out.println(b4);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>It outputs like:<\/strong><\/p>\n<pre>true\r\ntrue\r\ntrue\r\nFalse\r\n<\/pre>\n<ul>\n<li>public boolean endsWith(String suffix) : This method returns true if the character sequence represented by the argument is a suffix of the character sequence represented by this object; false otherwise. Note that the result will be true if the argument is the empty string or is equal to this String object.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example:<\/strong><\/span><\/p>\n<pre>public class StringEnds {\r\n     public static void main(String[] args) {\r\n\tString s1 = \"OCAJP8\";\r\n\tboolean b1 = s1.endsWith(\"JP8\");\r\n\tboolean b2 = s1.endsWith(\"\");\r\n\tboolean b3 = s1.endsWith(\"OCAJP8\");\r\n\tboolean b4 = s1.endsWith(\"OC\");\r\n\tSystem.out.println(b1);\r\n\tSystem.out.println(b2);\r\n\tSystem.out.println(b3);\r\n\tSystem.out.println(b4);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>It outputs like:<\/strong><\/p>\n<pre>true\r\ntrue\r\ntrue\r\nfalse\r\n<\/pre>\n<p><strong>substring()<\/strong><\/p>\n<ul>\n<li>This method is overloaded.<\/li>\n<\/ul>\n<p><strong>public String substring(int beginIndex)<\/strong><\/p>\n<ul>\n<li>This method returns a new string object that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.<\/li>\n<li>If beginIndex is invalid(negative number or greater than string length), it throws IndexOutOfBoundsException.But practically it throws StringIndexOutOfBoundsException.<\/li>\n<\/ul>\n<p><strong>public String substring(int beginIndex, int endIndex)<\/strong><\/p>\n<ul>\n<li>This method returns a new string object that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex &#8211; 1 .<\/li>\n<li>If beginIndex or endIndex or both invalid(if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex) , it throws IndexOutOfBoundsException.But practically it throws StringIndexOutOfBoundsException.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example:<\/strong><\/span><\/p>\n<pre>public class StringSub {\r\n    public static void main(String[] args) {\r\n\tString s1 = \"OCAJP8\";\r\n\tString s2 =\ts1.substring(3);\r\n\tString s3 =\ts1.substring(1,5);\r\n\tSystem.out.println(s2);\/\/prints JP8\r\n\tSystem.out.println(s3);\/\/prints CAJP\r\n    }\r\n}\r\n<\/pre>\n<p><strong>indexOf(),lastIndexOf()<\/strong><\/p>\n<ul>\n<li><strong>indexOf() :<\/strong> It is overloaded method.<\/li>\n<li><strong>public int indexOf(int ch) :<\/strong> This method returns the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.Pay attention to the method signature , it takes int parameter. But you need to pass char value. Because char can be converted into int.<\/li>\n<li><strong>public int indexOf(int ch, int fromIndex) :<\/strong> This method returns the index of the first occurrence of the character in the character sequence represented by this object and search start from fromIndex. It returns -1 if the character does not occur.Pay attention to the method signature , it takes int parameter. But you need to pass char value. Because char can be converted into int<\/li>\n<li><strong>public int indexOf(String str) :<\/strong> This method returns the index of the first occurrence of the specified substring, or -1 if there is no such occurrence.<\/li>\n<li>public int indexOf(String str, int fromIndex) : This method returns the index of the first occurrence of the specified substring, starting at the specified index, or -1 if there is no such occurrence.<\/li>\n<li><strong>public int lastIndexOf(int ch) :<\/strong> This method returns the index of the last occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.<\/li>\n<li><strong>public int lastIndexOf(int ch,int fromIndex) :<\/strong> This method returns the index of the last occurrence of the character in the character sequence represented by this object that is less than or equal to fromIndex, or -1 if the character does not occur before that point.<\/li>\n<li><strong>int lastIndexOf(String str) :<\/strong> This method returns the index of the last occurrence of the specified substring, or -1 if there is no such occurrence.The last occurrence of the empty string &#8220;&#8221; is considered to occur at the index value this.length().<\/li>\n<li><strong>public int lastIndexOf(String str, int fromIndex) :<\/strong> This method returns the index of the last occurrence of the specified substring, searching backward from the specified index, or -1 if there is no such occurrence.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example:<\/strong><\/span><\/p>\n<pre>public class StringSearch {\r\n    public static void main(String[] args) {\r\n\tString s1 = \"OCAJP8OCPJP8OCAJP8OCPJP8\";\r\n\tint i1 = s1.indexOf('A');\r\n\tint i2 = s1.indexOf('P', 3);\r\n\tint i3 = s1.indexOf(\"OCP\");\r\n\tint i4 = s1.indexOf(\"JP8\", 4);\r\n\tSystem.out.println(i1);\/\/prints 2\r\n\tSystem.out.println(i2);\/\/prints 4\r\n\tSystem.out.println(i3);\/\/prints 6\r\n\tSystem.out.println(i4);\/\/prints 9\r\n\tint i5 = s1.lastIndexOf('A');\r\n\tint i6 = s1.lastIndexOf('P', 6);\r\n\tint i7 = s1.lastIndexOf(\"OCP\");\r\n\tint i8 = s1.lastIndexOf(\"JP8\", 4);\r\n\tSystem.out.println(i5);\/\/prints 14\r\n\tSystem.out.println(i6);\/\/prints 4\r\n\tSystem.out.println(i7);\/\/prints 18\r\n\tSystem.out.println(i8);\/\/prints 3\r\n   }\r\n}\r\n<\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>For the OCAJP, Make sure you have clear understanding about String immutability concept. Remember the important String class methods declarations and their functionality. Be able to identify the correct output when multiple methods are chaining. Important methods for OCAJP is concat(), charAt(), length(), indexOf, lastIndexOf, substring(), trim(),\u00a0equals(), equalsIgnoreCase(), toUpperCase(), toLowerCase(), startsWith(), endsWith(), contains(),replace().<\/p>\n<h2><span class=\"ez-toc-section\" id=\"References\"><\/span>References<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>We have published few useful articles for preparing OCAJP Exams. Please read the below articles for effective preparation.<\/p>\n<ul>\n<li><a href=\"https:\/\/www.whizlabs.com\/blog\/how-to-prepare-for-ocajp-8-certification\/\" title=\"How to prepare for OCAJP 8 Certification\">How to prepare for OCAJP Exam?<\/a><\/li>\n<li><a href=\"https:\/\/www.whizlabs.com\/blog\/ocajp-8-books\/\" title=\"What are the good books for preparing OCAJP 8 exam?\">What are the good books for OCAJP 8 Certification Exam?<\/a><\/li>\n<li><a href=\"https:\/\/www.whizlabs.com\/blog\/ocajp-7-books\/\" title=\"What are the best books for preparing OCAJP 7 exam?\">What are the good books for OCAJP 7 Certification Exam?<\/a><\/li>\n<\/ul>\n<p><img decoding=\"async\" src=\"https:\/\/www.whizlabs.com\/blog\/wp-content\/uploads\/2024\/05\/Practice-Tests.jpg\" alt=\"Practice Tests\" class=\" aligncenter\" \/><\/p>\n<p><strong>If you are looking for any support for Java certification preparation or purchasing our <a href=\"https:\/\/www.whizlabs.com\/ocajp-scja\/\">OCAJP Certification Kit<\/a>, please send us a mail or call to our support.<\/strong><\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This post is about the OCAJP exam objective \u201cCreating and Manipulating Strings\u201d. You will be mainly tested in the exam about String Immutability behavior. You will also be tested in the exam about various methods and syntax related to the String class. Here we would explain about the String class and important methods. It is very important to understand the concepts of String and how it is being created and manipulated inside JVM to effectively answer the questions in the OCAJP exam. If you are preparing for the OCAJP exam, please try our free OCAJP 8 mock exam questions. Also [&hellip;]<\/p>\n","protected":false},"author":220,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"default","adv-header-id-meta":"","stick-header-meta":"default","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"set","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[13],"tags":[1143],"class_list":["post-16355","post","type-post","status-publish","format-standard","hentry","category-java","tag-ocajp-examples"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false,"profile_24":false,"profile_48":false,"profile_96":false,"profile_150":false,"profile_300":false,"tptn_thumbnail":false,"web-stories-poster-portrait":false,"web-stories-publisher-logo":false,"web-stories-thumbnail":false},"uagb_author_info":{"display_name":"Aditi Malhotra","author_link":"https:\/\/www.whizlabs.com\/blog\/author\/aditi\/"},"uagb_comment_info":2,"uagb_excerpt":"This post is about the OCAJP exam objective \u201cCreating and Manipulating Strings\u201d. You will be mainly tested in the exam about String Immutability behavior. You will also be tested in the exam about various methods and syntax related to the String class. Here we would explain about the String class and important methods. It is&hellip;","_links":{"self":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts\/16355","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/users\/220"}],"replies":[{"embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/comments?post=16355"}],"version-history":[{"count":5,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts\/16355\/revisions"}],"predecessor-version":[{"id":95956,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts\/16355\/revisions\/95956"}],"wp:attachment":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/media?parent=16355"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/categories?post=16355"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/tags?post=16355"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}