Title: Java String Class (with video) - Examples Java Code Geeks - 2026
Open Graph Title: Java String Class (with video) - Examples Java Code Geeks - 2026
Description: Check out our detailed example on Java String Class! We are going to analyze the java string methods with detailed examples.
Open Graph Description: Check out our detailed example on Java String Class! We are going to analyze the java string methods with detailed examples.
Mail addresses
support@javacodegeeks.com
Opengraph URL: https://examples.javacodegeeks.com/java-string-class-example/
Generator: WordPress 6.9.4
Domain: examples.javacodegeeks.com
{"@context":"https://schema.org","@graph":[{"@type":"Article","@id":"https://examples.javacodegeeks.com/java-string-class-example/#article","isPartOf":{"@id":"https://examples.javacodegeeks.com/java-string-class-example/"},"author":{"name":"Prateek Sharma","@id":"https://examples.javacodegeeks.com/#/schema/person/561cddc206f1d8d280f27bfe1377fc03"},"headline":"Java String Class Example (with video)","datePublished":"2014-03-05T21:52:20+00:00","dateModified":"2022-07-05T20:23:46+00:00","mainEntityOfPage":{"@id":"https://examples.javacodegeeks.com/java-string-class-example/"},"wordCount":2334,"commentCount":1,"publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"image":{"@id":"https://examples.javacodegeeks.com/java-string-class-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","articleSection":["String"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https://examples.javacodegeeks.com/java-string-class-example/#respond"]}]},{"@type":"WebPage","@id":"https://examples.javacodegeeks.com/java-string-class-example/","url":"https://examples.javacodegeeks.com/java-string-class-example/","name":"Java String Class (with video) - Examples Java Code Geeks - 2026","isPartOf":{"@id":"https://examples.javacodegeeks.com/#website"},"primaryImageOfPage":{"@id":"https://examples.javacodegeeks.com/java-string-class-example/#primaryimage"},"image":{"@id":"https://examples.javacodegeeks.com/java-string-class-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","datePublished":"2014-03-05T21:52:20+00:00","dateModified":"2022-07-05T20:23:46+00:00","description":"Check out our detailed example on Java String Class! We are going to analyze the java string methods with detailed examples.","breadcrumb":{"@id":"https://examples.javacodegeeks.com/java-string-class-example/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https://examples.javacodegeeks.com/java-string-class-example/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/java-string-class-example/#primaryimage","url":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https://examples.javacodegeeks.com/java-string-class-example/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://examples.javacodegeeks.com/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https://examples.javacodegeeks.com/category/java-development/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https://examples.javacodegeeks.com/category/java-development/core-java/"},{"@type":"ListItem","position":4,"name":"lang","item":"https://examples.javacodegeeks.com/category/java-development/core-java/lang/"},{"@type":"ListItem","position":5,"name":"String","item":"https://examples.javacodegeeks.com/category/java-development/core-java/lang/string/"},{"@type":"ListItem","position":6,"name":"Java String Class Example (with video)"}]},{"@type":"WebSite","@id":"https://examples.javacodegeeks.com/#website","url":"https://examples.javacodegeeks.com/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://examples.javacodegeeks.com/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https://examples.javacodegeeks.com/#organization","name":"Exelixis Media P.C.","url":"https://examples.javacodegeeks.com/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/logo/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https://examples.javacodegeeks.com/#/schema/logo/image/"},"sameAs":["https://www.facebook.com/javacodegeeks","https://x.com/javacodegeeks"]},{"@type":"Person","@id":"https://examples.javacodegeeks.com/#/schema/person/561cddc206f1d8d280f27bfe1377fc03","name":"Prateek Sharma","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/person/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2019/08/prateek-.sharma-96x96.png","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2019/08/prateek-.sharma-96x96.png","caption":"Prateek Sharma"},"description":"Prateek has graduated in Computer Engineering from Thapar University (Patiala, India). He also holds a Master degree in Software Systems from Birla Institute of Technology & Science (Pilani, India). Currently he is working as a Full Stack Software Engineer in telecommunications sector where he is involved in multiple flavors of project ranging from development in J2EE,Groovy, JPA, Hibernate, Web Service (SOAP/REST) to DevOps tools like Jenkins, SonarQube, SonarLint, EclEmma etc. He also has experience in message queues like RabbitMQ and Kafka.","sameAs":["https://www.linkedin.com/in/prateek-sharma-189434149/"],"url":"https://examples.javacodegeeks.com/author/prateek-sharma/"}]}
{"@context":"http:\/\/schema.org","@type":"BreadcrumbList","@id":"#Breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"item":{"name":"Home","@id":"https:\/\/examples.javacodegeeks.com\/"}},{"@type":"ListItem","position":2,"item":{"name":"Java Development","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"}},{"@type":"ListItem","position":3,"item":{"name":"Core Java","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"}},{"@type":"ListItem","position":4,"item":{"name":"lang","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/lang\/"}},{"@type":"ListItem","position":5,"item":{"name":"String","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/lang\/string\/"}}]}
{"@context":"http:\/\/schema.org","@type":"Article","dateCreated":"2014-03-05T23:52:20+02:00","datePublished":"2014-03-05T23:52:20+02:00","dateModified":"2022-07-05T23:23:46+03:00","headline":"Java String Class Example (with video)","name":"Java String Class Example (with video)","keywords":[],"url":"https:\/\/examples.javacodegeeks.com\/java-string-class-example\/","description":"This article talks about one of the widely used String library in Java which does no less than magic. It goes through some of the common Java String methods available previous to Java 8. Then it speci","copyrightYear":"2014","articleSection":"String","articleBody":"\nThis article talks about one of the widely used String library in Java which does no less than magic. It goes through some of the common Java String methods available previous to Java 8. Then it specifies some of the important String methods introduced in and after Java 8.\n\n\n\n You can also check this tutorial in the following video: \n\n\n\nJava String Class Example - Video\n\n\n\n\nTable Of Contents\n\n1. Introduction\n2. Java String Class basic methods\n\n\n2.1 Java String Equal Methods\n\n\n2.2 Java String Case Methods\n\n\n2.3 Java String Index Methods\n\n\n2.4 Java String Substring Methods\n\n\n2.5 Java String Replace Methods\n\n\n2.6 Java String Compare Methods\n\n\n2.7 Java String Split Methods\n\n\n2.8 Java String Other Common Methods\n\n\n2.9 Java 8 String Methods\n\n\n2.10 Java 9 String Methods\n\n\n2.11 Java 11 String Methods\n\n\n2.12 Java 12 String Methods\n\n\n3. Other characteristics of String objects\n4. More articles\n5. Download the Eclipse Project\n\n\n\n\n\n1. Introduction\n\n\n\n\n\n\n\nIn this example, we are going to discuss the basic characteristics of Java String Class. String is probably one of the most used types in Java programs. That's why Java provides a number of API methods that make String manipulation easy and efficient, straight out of the box. Strings are so important that even in the latest Java releases (including 7 and 8), several changes have been made to its class methods and its internal representation, improving it even further in terms of performance and security.\n\n\n\n2. Java String Class basic methods\n\n\n\nA String is simply a sequence of characters. As a matter of fact, a String Object is backed by a char array. Consequently, it is not null terminated, like in C\/C++.\n\n\n\nHere is how you can create a String\n\n\n\n\n\n\n\n\n\n1\n\n\n\nString str= \"Hello World\";\n\n\n\n\n\n\n\n\n\n\n\"Hello World\" is called a String literal. In a Java program, everything between two double quotes is a String literal. Literals are implemented as instances of String class. As you can see, you can conveniently initialize a String Object like a primitive type, e.g int i = 0;.\n\n\n\nThere is no need to do:\n\n\n\n\n\n\n\n\n\n1\n\n\n\nString str = new String(\"Hello World\");\n\n\n\n\n\n\n\n\n\n\nThere is a difference between these two initialization methods, although the result is the same : A String with value \"Hello World\". But more on that in just a bit.\n\n\n\nFor now, here is a simple main with the most important String API methods:\n\n\n\nStringClassExample.java\n\n\n\n\n\n\n\n\n\n001\n002\n003\n004\n005\n006\n007\n008\n009\n010\n011\n012\n013\n014\n015\n016\n017\n018\n019\n020\n021\n022\n023\n024\n025\n026\n027\n028\n029\n030\n031\n032\n033\n034\n035\n036\n037\n038\n039\n040\n041\n042\n043\n044\n045\n046\n047\n048\n049\n050\n051\n052\n053\n054\n055\n056\n057\n058\n059\n060\n061\n062\n063\n064\n065\n066\n067\n068\n069\n070\n071\n072\n073\n074\n075\n076\n077\n078\n079\n080\n081\n082\n083\n084\n085\n086\n087\n088\n089\n090\n091\n092\n093\n094\n095\n096\n097\n098\n099\n100\n101\n102\n103\n104\n105\n106\n\n\n\npackage com.javacodegeeks.core.lang.string;\n \npublic class StringClassExample {\n \n public static void main(String[]args){\n \/\/Initialization with literal\n String str1 = \"Hello World\";\n System.out.println(\"str1:\"+str1);\n \n \/\/Initialization with char array\n char arr[] = {'H','e','l','l','o'};\n String str2 = new String(arr);\n System.out.println(\"str2:\"+str2);\n \n \/\/Concatenation using + operator\n String str3 = \"World\";\n str3 = str2 + \" \" + str3;\n System.out.println(\"str3:\"+str3);\n \n \/\/find out the length of a string\n System.out.println(str3.length());\n \n \/\/You can even apply that to literals, as with all String API methods\n \/\/As we said. literals are implemented as String instances\n System.out.println(\"Length: \"+\"abcdefg\".length());\n \n \/\/Substring from position 2 to position 10\n String c = str1.substring(2,10);\n System.out.println(\"Substring :\"+c);\n \n \/\/Substring from position 1 to position 4\n System.out.println(\"Literal Substring :\"+\"abcdefghigklm\".substring(1,4));\n \n \/\/ Get the charcter array of the string.\n char[] chars = c.toCharArray();\n System.out.println(\"Char array : [\"+chars[0]+\",\"+chars[1]+\",\"+chars[2]+\"]\");\n \n \/\/find the first index of a char inside a string\n int i = str1.indexOf('W');\n System.out.println(\"Index of 'W':\"+i);\n \n \/\/find the first index of a string inside another string after a certain position\n i = str1.indexOf(\"orld\",5);\n System.out.println(\"Index of 'orld':\"+i);\n \n \/\/find the last index of a string inside another string\n i = str1.lastIndexOf(\"l\");\n System.out.println(\"LAST Index of 'l':\"+i);\n \n \/\/find the last index of a string inside another string after a certain position\n \/\/ - like scanning the string backwards\n i = str1.lastIndexOf(\"l\",7);\n System.out.println(\"LAST Index of 'l':\"+i);\n \n \/\/find a character in a certain position\n char cr = str1.charAt(5);\n System.out.println(\"Character at position 5:\"+cr);\n \n \/\/Lower case\n System.out.println(\"ABCEFAFA\".toLowerCase());\n \n \/\/Upper case\n System.out.println(\"abcasipasc\".toUpperCase());\n \n \/\/replace occurrences of a character\n str1 = str1.replace('o','0');\n System.out.println(str1);\n \n \/\/Trim white spaces from the end and the beginning\n String str4 = \" Java\";\n System.out.println(str4);\n System.out.println(str4.trim());\n \n \/\/Split !!!\n String str5= \"Java is great\";\n String[] strArray = str5.split(\" \");\n \n System.out.println(strArray[0]+\",\"+strArray[1]+\",\"+strArray[2]);\n \n str5= \"Java-is-great\";\n strArray = str5.split(\"-\");\n System.out.println(strArray[0]+\",\"+strArray[1]+\",\"+strArray[2]);\n \n str5= \"Java is great\";\n strArray = str5.split(\"\/*\");\n System.out.println(strArray[0]+\",\"+strArray[1]+\",\"+strArray[2]+\",\"+strArray[3]+\",\"+strArray[4]+\n \",\"+strArray[5]+\",\"+strArray[6]+\",\"+strArray[7]+\",\"+strArray[8]);\n \n \/\/contains and equals\n System.out.println(\"Contains :\" + \"qwerty\".contains(\"ert\")); \n System.out.println (\"Equals :\"+str5.equals(\"java is great\"));\n System.out.println (\"Equals ignore case:\"+str5.equalsIgnoreCase(\"java is great\"));\n \n \/\/ Compare lexicographically two strings\n System.out.println (\"Compare:\"+str5.compareTo(\"abc\"));\n \n \/\/comparison attempts\n String s1 = \"abc\"; \n String s3 = new String(\"abc\");\n \n System.out.println(s1==s3);\n System.out.println(s1.equalsIgnoreCase(s3));\n \n }\n \n}\n\n\n\n\n\n\n\n\n\n\nThis is the output of the above program:\n\n\n\nstr1:Hello World\nstr2:Hello\nstr3:Hello World\n11\nLength: 7\nSubstring :llo Worl\nLiteral Substring :bcd\nChar array : [l,l,o]\nIndex of 'W':6\nIndex of 'orld':7\nLAST Index of 'l':9\nLAST Index of 'l':3\nCharacter at position 5: \nabcefafa\nABCASIPASC\nHell0 W0rld\n Java\nJava\nJava,is,great\nJava,is,great\n,J,a,v,a, ,i,s, \nContains :true\nEquals :false\nEquals ignore case:true\nCompare:-23\nfalse\ntrue\n\n\n\n\nFrom the above program is clear that Java designers decided to treat Strings somewhat differently from other Objects. For example you can initialize them like a primitive, e.g String a=\"abc\" and you can concatenate two strings using + operator, like you would add two ints (looks like overloading + operator in C++).\n\n\n\nThe comparison attempts section of the code might seem a little fuzzy, but it will get clear in the next section. What you should take away from it now, is that you SHOULD NEVER try to compare the contents of Strings using == operator. You are only comparing reference equality, not content equality. You MUST use equals or equalsIgnoreCase.\n\n\n\n2.1 Java String Equal Methods\n\n\n\nThe following method returns true if the content of both the strings are equal, otherwise returns false. It also takes into account the case of the contents.\n\n\n\nequals(String str)\n\n\n\npublic class EqualsExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n\n String s2 = \"Java Code Geeks\";\n\n String s3 = \"java code geeks\";\n\n System.out.println(s1.equals(s2)); \/\/prints true\n\n System.out.println(s1.equals(s3)); \/\/prints false\n\n }\n\n}\n\n\n\n\nThe following method returns true if the content of both the strings are equal, otherwise returns false. It does not take into account the case of the contents.\n\n\n\nequalsIgnoreCase(String str)\n\n\n\npublic class EqualsIgnoreCaseExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n\n String s2 = \"Java Code Geeks\";\n\n String s3 = \"java code geeks\";\n\n System.out.println(s1.equalsIgnoreCase(s2)); \/\/prints true\n\n System.out.println(s1.equalsIgnoreCase(s3)); \/\/prints true\n\n }\n\n}\n\n\n\n\nThe following method takes as parameter either a String or a StringBuffer object and compares the contents. Returns true if content is same considering the case as well.\n\n\n\ncontentEquals(StringBuffer str)\n\n\n\npublic class ContentEqualsExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n\n StringBuffer s2 = new StringBuffer(\"Java Code Geeks\");\n\n System.out.println(s1.contentEquals(s2)); \/\/prints true \n\n }\n\n}\n\n\n\n\n2.2 Java String Case Methods\n\n\n\nThe following method converts the contents of the string to lowercase.\n\n\n\ntoLowerCase()\n\n\n\npublic class ToLowerCaseExample{\n\n public static void main(String[] args){\n\n String s1 = \"JAVA CODE GEEKS\";\n \n System.out.println(s1.toLowerCase()); \/\/prints java code geeks \n\n }\n\n}\n\n\n\n\nThe following method converts the contents of the string to uppercase.\n\n\n\ntoUpperCase()\n\n\n\npublic class ToUpperCaseExample{\n\n public static void main(String[] args){\n\n String s1 = \"java code geeks\";\n \n System.out.println(s1.toUpperCase()); \/\/prints JAVA CODE GEEKS \n\n }\n\n}\n\n\n\n\n2.3 Java String Index Methods \n\n\n\nThe following method returns the index of the first occurrence of the character ch. Returns -1 if there is no occurrence.\n\n\n\nindexOf(char ch)\n\n\n\npublic class IndexOfCharExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n \n System.out.println(s1.indexOf('a')); \/\/prints 1\n\n System.out.println(s1.indexOf('z')); \/\/prints -1 \n\n }\n\n}\n\n\n\n\nThe following method returns the index of the first occurrence of the substring str. Returns -1 if there is no occurrence.\n\n\n\nindexOf(String str)\n\n\n\npublic class IndexOfStringExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n \n System.out.println(s1.indexOf(\"Code\")); \/\/prints 5\n\n System.out.println(s1.indexOf(\"Test\")); \/\/prints -1 \n\n }\n\n}\n\n\n\n\nThe following method returns the index of the first occurrence of the character ch after the fromIndex. It begins the search after the fromIndex in the String. Returns -1 if there is no occurrence after the fromIndex.\n\n\n\nindexOf(char ch, int fromIndex)\n\n\n\npublic class IndexOfCharFromIndexExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n \n System.out.println(s1.indexOf('a',2)); \/\/prints 3\n\n System.out.println(s1.indexOf('a',5)); \/\/prints -1 \n\n }\n\n}\n\n\n\n\nThe following method returns the index of the first occurrence of the substring str after the fromIndex. It begins the search after the fromIndex in the String. Returns -1 if there is no occurrence after the fromIndex.\n\n\n\nindexOf(String str, int fromIndex)\n\n\n\npublic class IndexOfStringFromIndexExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Java\";\n \n System.out.println(s1.indexOf(\"Java\",4)); \/\/prints 10\n\n System.out.println(s1.indexOf(\"Code\",10)); \/\/prints -1 \n\n }\n\n}\n\n\n\n\nThe following method returns the index of the last occurrence of the character ch. Returns -1 if there is no occurrence.\n\n\n\nlastIndexOf(char ch)\n\n\n\npublic class LastIndexOfCharExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n \n System.out.println(s1.lastIndexOf('a')); \/\/prints 3\n\n System.out.println(s1.lastIndexOf('z')); \/\/prints -1 \n\n }\n\n}\n\n\n\n\nThe following method returns the index of the last occurrence of the substring str. Returns -1 if there is no occurrence.\n\n\n\nlastIndexOf(String str)\n\n\n\npublic class LastIndexOfStringExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code ode\";\n \n System.out.println(s1.lastIndexOf(\"ode\")); \/\/prints 10\n\n System.out.println(s1.indexOf(\"Test\")); \/\/prints -1 \n\n }\n\n}\n\n\n\n\nThe following method returns the index of the last occurrence of the character ch searching backwards beginning from the fromIndex. Returns -1 if there is no occurrence after the fromIndex.\n\n\n\nlastIndexOf(char ch, int fromIndex)\n\n\n\npublic class LastIndexOfCharFromIndexExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n \n System.out.println(s1.lastIndexOf('e',9)); \/\/prints 8\n\n System.out.println(s1.lastIndexOf('G',4)); \/\/prints -1 \n\n }\n\n}\n\n\n\n\nThe following method returns the index of the last occurrence of the substring str searching backwards beginning from the fromIndex. Returns -1 if there is no occurrence after the fromIndex.\n\n\n\nlastIndexOf(String str, int fromIndex)\n\n\n\npublic class LastIndexOfStringFromIndexExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Java\";\n \n System.out.println(s1.lastIndexOf(\"Java\",13)); \/\/prints 10\n\n System.out.println(s1.lastIndexOf(\"Code\",4)); \/\/prints -1 \n\n }\n\n}\n\n\n\n\n2.4 Java String Substring Methods\n\n\n\nThe following method returns the substring of the string which starts from the index beginIndex and extends till endIndex-1. The beginIndex is inclusive and endIndex is exclusive.\n\n\n\nsubstring(int beginIndex int endIndex)\n\n\n\npublic class SubstringExample1{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n\n String s2 = s1.substring(0,9);\n \n System.out.println(s2); \/\/prints Java Code \n\n }\n\n}\n\n\n\n\nThe following method returns the substring of the string which starts from the index beginIndex and extends till the end of the string.\n\n\n\nsubstring(int beginIndex)\n\n\n\npublic class SubstringExample2{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n\n String s2 = s1.substring(5);\n \n System.out.println(s2); \/\/prints Code Geeks \n\n }\n\n}\n\n\n\n\nThe following method behaves exactly the same way as substring(int beginIndex, int endIndex). The only difference is subSequence returns a CharSequence.\n\n\n\nsubSequence(int beginIndex, int endIndex)\n\n\n\npublic class SubSequenceExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n\n CharSequence s2 = s1.subSequence(0,4);\n \n System.out.println(s2); \/\/prints Java \n\n }\n\n}\n\n\n\n\nYou can also check this Substring Java Example for further knowledge.\n\n\n\n2.5 Java String Replace Methods\n\n\n\nThe following method replaces all the occurrences of oldChar with the newChar in the string.\n\n\n\nreplace(char oldChar, char newChar)\n\n\n\npublic class ReplaceExample1{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n\n String s2 = s1.replace('e','i');\n \n System.out.println(s2); \/\/prints Java Codi Giiks \n\n }\n\n}\n\n\n\n\nThe following method replaces all the occurrences of string target with the string replacement.\n\n\n\nreplace(CharSequence target, CharSequence replacement)\n\n\n\npublic class ReplaceExample2{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n\n String s2 = s1.replace(\"Geeks\",\"Experts\");\n \n System.out.println(s2); \/\/prints Java Code Experts \n\n }\n\n}\n\n\n\n\nThe following method replaces all the occurrences of substring which matches the regular expression regex with the string replacement.\n\n\n\nreplaceAll(String regex, String replacement)\n\n\n\npublic class ReplaceAllExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n\n String s2 = s1.replaceAll(\"Geeks\",\"Experts\"); \n \n \/\/The below line removes all white spaces\n String s3 = s1.replaceAll(\"\\\\s\", \"\");\n\n System.out.println(s2); \/\/prints Java Code Experts \n\n System.out.println(s3); \/\/prints JavaCodeGeeks \n\n }\n\n}\n\n\n\n\nThe following method replaces only the first occurrence of substring which matches the regular expression regex with the string replacement.\n\n\n\nreplaceFirst(String regex, String replacement)\n\n\n\npublic class ReplaceFirstExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks helps to learn Java\";\n\n String s2 = s1.replaceFirst(\"Java\",\"JAVA\"); \n \n String s3 = s1.replaceFirst(\"[a]\", \"A\");\n\n System.out.println(s2); \/\/prints JAVA Code Geeks helps to learn Java \n\n System.out.println(s3); \/\/prints JAva Code Geeks helps to learn Java \n\n }\n\n}\n\n\n\n\n2.6 Java String Compare Methods\n\n\n\nThe following method compares two string lexicographically i.e. Unicode value of each character in the strings. It returns a positive number (character value difference) if the first string is lexicographically greater than the second string, returns a negative number if first string is lexicographically lower than the second string and returns 0 if two strings are lexicographically equal. This method is case sensitive.\n\n\n\ncompareTo(String str)\n\n\n\npublic class CompareToExample1{\n\n public static void main(String[] args){\n\n String s1 = \"Code\";\n\n String s2 = \"Node\";\n\n String s3 = \"Code\";\n\n String s4 = \"code\"; \n\n System.out.println(s2.compareTo(s1)); \/\/prints 11 as 'N' is 11 characters ahead of 'C'\n\n System.out.println(s1.compareTo(s3)); \/\/prints 0 \n\n System.out.println(s1.compareTo(s4)); \/\/prints -32 as 'C' is 32 characters behind 'c' \n\n }\n\n}\n\n\n\n\nThe following method compares two string lexicographically i.e. Unicode value of each character in the strings. It returns a positive number (character value difference) if the first string is lexicographically greater than the second string, returns a negative number if first string is lexicographically lower than the second string and returns 0 if two strings are lexicographically equal. This method is not case sensitive.\n\n\n\ncompareToIgnoreCase(String str)\n\n\n\npublic class CompareToExample2{\n\n public static void main(String[] args){\n\n String s1 = \"Code\";\n\n String s2 = \"code\"; \n\n System.out.println(s2.compareToIgnoreCase(s1)); \/\/prints 0 \n\n }\n\n}\n\n\n\n\n2.7 Java String Split Methods\n\n\n\nThe following method splits the string on the matches of the regular expression regex and returns a String array containing all the elements after the split.\n\n\n\nsplit(String regex)\n\n\n\npublic class SplitExample1{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n\n String[] s2 = s1.split(\" \"); \/\/Splits s1 on white spaces and stores the elements in array s2 as {\"Java\",\"Code\",\"Geeks\"} \n\n System.out.println(s2.length); \/\/prints 3 \n\n }\n\n}\n\n\n\n\nThe following method splits the string on the matches of the regular expression regex and returns a String array containing all the elements after the split. The number of elements in the array will not be more than the parameter limit.\n\n\n\nsplit(String regex, int limit)\n\n\n\npublic class SplitExample2{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\";\n\n String[] s2 = s1.split(\" \",2); \/\/Splits s1 on white spaces and stores only 2 elements in array s2 as {\"Java\",\"Code\"} \n\n System.out.println(s2.length); \/\/prints 2 \n\n }\n\n}\n\n\n\n\n2.8 Java String Other Common Methods\n\n\n\nThe following method returns the length of the string.\n\n\n\nlength()\n\n\n\npublic class LengthExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\"; \n\n System.out.println(s1.length()); \/\/prints 15 \n\n }\n\n}\n\n\n\n\nThe following method returns a character Array containing all the chars of the String.\n\n\n\ntoCharArray()\n\n\n\npublic class ToCharArrayExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\"; \n\n char[] s2 = s1.toCharArray();\n\n System.out.println(\"[\"+s2[0]+\",\"+s2[1]+\",\"+s2[2]+\"]\"); \/\/prints [J,a,v]\n\n }\n\n}\n\n\n\n\nThe following method removes the trailing and leading white spaces from the String.\n\n\n\ntrim()\n\n\n\npublic class TrimExample{\n\n public static void main(String[] args){\n\n String s1 = \" Java Code Geeks \"; \n\n System.out.println(s1.trim()); \/\/prints Java Code Geeks\n\n }\n\n}\n\n\n\n\nThe following method returns the character present at the index specified.\n\n\n\ncharAt(int index)\n\n\n\npublic class CharAtExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\"; \n\n char ch = s1.charAt(5);\n\n System.out.println(ch); \/\/prints C\n\n }\n\n}\n\n\n\n\nThe following method returns true if the String contains the substring represented by sequence, otherwise returns false.\n\n\n\ncontains(CharSequence sequence)\n\n\n\npublic class ContainsExample{\n\n public static void main(String[] args){\n\n String s1 = \"Java Code Geeks\"; \n\n System.out.println(s1.contains(\"Code\")); \/\/prints true\n\n System.out.println(s1.contains(\"Node\")); \/\/prints false\n\n }\n\n}\n\n\n\n\n2.9 Java 8 String Methods\n\n\n\nThe following method takes input as various Strings in var-args format and joins them separated the by the argument delimiter.\n\n\n\njoin(CharSequence delimiter, CharSequence... elements)\n\n\n\npublic class JoinExample1{\n\n public static void main(String[] args){ \n\n String joinedString = String.join(\"-\",\"Java\",\"Code\",\"Geeks\"); \n\n System.out.println(joinedString); \/\/prints Java-Code-Geeks \n\n }\n\n}\n\n\n\n\nThe following method takes input either a list of Strings or an String Array and joins the items in the list or array separated the by the argument delimiter.\n\n\n\njoin(CharSequence delimiter, Iterable elements)\n\n\n\npublic class JoinExample2{\n\n public static void main(String[] args){ \n\n List strList = Arrays.asList(\"Java\",\"Code\",\"Geeks\"); \n\n String joinedString = String.join(\"-\",strList);\n\n System.out.println(joinedString); \/\/prints Java-Code-Geeks \n\n }\n\n}\n\n\n\n\n2.10 Java 9 String Methods\n\n\n\nThe following method converts the String into char values and returns the char values as stream of int.\n\n\n\nchars()\n\n\n\npublic class CharsExample{\n\n public static void main(String[] args){ \n\n String str = \"Java Code Geeks\";\n\n IntStream stream = str.chars();\n \n stream.forEach(x -> System.out.printf(\"-%s\", (char)x)); \/\/prints -J-a-v-a- -C-o-d-e- -G-e-e-k-s \n\n }\n\n}\n\n\n\n\nThe following method converts the String into a stream of code point values.\n\n\n\ncodePoints()\n\n\n\npublic class CodePointsExample{\n\n public static void main(String[] args){ \n\n String str = \"Java Code Geeks\";\n\n IntStream stream = str.codePoints();\n \n stream.forEach(x -> System.out.print(\n new StringBuilder().appendCodePoint(Character.toChars(x)[0]).toString())); \/\/prints Java Code Geeks\n\n }\n\n}\n\n\n\n\n2.11 Java 11 String Methods\n\n\n\nThe following method removes the trailing and leading whitespaces from the String.\n\n\n\nstrip()\n\n\n\npublic class StripExample{\n\n public static void main(String[] args){ \n\n String str = \" Java Code Geeks \";\n\n System.out.println(str.strip()); \/\/prints Java Code Geeks\n\n }\n\n}\n\n\n\n\nOutput\nJava Code Geeks\n\n\n\n\nstrip() is different from already existing method trim() in the way that trim() removes only those whitespaces whose codepoint is less than or equal to 'U+0020' (the space character) whereas strip() removes all whitespaces.\n\n\n\nThe following method removes all leading whitespaces from the String.\n\n\n\nstripLeading()\n\n\n\npublic class StripLeadingExample{\n\n public static void main(String[] args){ \n\n String str = \" Java Code Geeks\";\n\n System.out.println(str.stripLeading()); \/\/prints Java Code Geeks\n\n }\n\n}\n\n\n\n\nOutput\nJava Code Geeks\n\n\n\n\nThe following method removes all trailing whitespaces from the String.\n\n\n\nstripTrailing()\n\n\n\npublic class StripTrailingExample{\n\n public static void main(String[] args){ \n\n String str = \"Java Code Geeks \";\n\n System.out.println(str.stripTrailing()); \/\/prints Java Code Geeks\n\n }\n\n}\n\n\n\n\nOutput\nJava Code Geeks\n\n\n\n\nThe following method returns true if the String is blank, otherwise false.\n\n\n\nisBlank()\n\n\n\npublic class IsBlankExample{\n\n public static void main(String[] args){ \n\n String str = \" \";\n\n System.out.println(str.isBlank()); \/\/prints true\n\n }\n\n}\n\n\n\n\nOutput\ntrue\n\n\n\n\nisBlank() is different from isEmpty() in the way that isBlank() also detects U+2005 whitespaces.\n\n\n\nThe following method splits a String into Stream of separate lines and separated by line terminators which could be \"\\n\", \"\\r\" and \"\\r\\n\".\n\n\n\nlines()\n\n\n\npublic class LinesExample{\n\n public static void main(String[] args){ \n\n String str = \"Java Code Geeks hosts a lot of examples in Java.\\nThis is an example of lines() method.\";\n\n str.lines().forEach(System.out::println);\n\n }\n\n}\n\n\n\n\nOutput\nJava Code Geeks hosts a lot of examples in Java.\nThis is an example of lines() method.\n\n\n\n\nThe following method concatenates the String with itself 'n' number of times. 'n' cannot be negative. If 'n' is 0 then it will return an empty String.\n\n\n\nrepeat(int n)\n\n\n\npublic class RepeatExample{\n\n public static void main(String[] args){ \n\n String str = \"Java Code Geeks\";\n\n System.out.println(str.repeat(2)); \/\/prints Java Code GeeksJava Code Geeks\n\n System.out.println(str.repeat(0)); \/\/prints an empty String\n\n }\n\n}\n\n\n\n\nOutput\nJava Code GeeksJava Code Geeks\n\n\n\n\n\n2.12 Java 12 String Methods\n\n\n\nThe following method indents each line of the String with 'n' number of whitespaces. The method first breaks the String into separate lines wherever it finds \\n and then inserts 'n' number of whitespaces before each line. If n is greater than 0 then it appends n whitespaces before each line. If n is smaller than 0 then it removes n whitespaces or all whitespaces if n is greater than the number of whitespaces. If n is equal to 0 then it remains unchanged.\n\n\n\nindent(int n)\n\n\n\npublic class IndentExample{\n\n public static void main(String[] args){ \n\n String str = \"Java Code Geeks.\\nLearn Java\";\n\n String str1 = \" Java Code Geeks.\\n Learn Java\";\n\n String indentStr = str.indent(5);\n\n String indentStr1 = str1.indent(-3);\n\n System.out.println(str); \n\n System.out.println(indentStr); \n\n System.out.println(str1);\n\n System.out.println(indentStr1);\n\n }\n\n}\n\n\n\n\nOutput\nJava Code Geeks.\nLearn Java\n Java Code Geeks.\n Learn Java\n Java Code Geeks.\n Learn Java\nJava Code Geeks.\n Learn Java\n\n\n\n\nThe following method executes the function f by taking the String as input and returns output from the function.\n\n\n\ntransform(Function f)\n\n\n\npublic class TransformExample{\n\n public static void main(String[] args){ \n\n String str = \"Java Code Geeks\";\n\n var output = str.transform(input -> input.concat(\" Learn Java\")).transform(String::toUpperCase);\n\n System.out.println(output.toString()); \/\/prints JAVA CODE GEEKS LEARN JAVA\n\n }\n\n}\n\n\n\n\nOutput\nJAVA CODE GEEKS LEARN JAVA\n\n\n\n\n3. Other characteristics of String objects\n\n\n\nString objects are immutable. This means that once a String is created, its contents cannot be changed. In the above example, every time we attempt to change its contents, e.g when concatenating, a new String object is created representing the result. Additionally, String class is final, so you cannot override its behavior.\n\n\n\nImmutability was mostly chosen for security reasons and for performance. It also means that two different thread can share the same String and manipulate it as they want, not having to synchronize anything, because every time they make a change in the original string, a new one is created, while the old one remains untouched.\n\n\n\nNow let's see this :\n\n\n\n\n\n\n\n\n\n1\n2\n3\n4\n5\n6\n7\n\n\n\nString s1 = \"abc\";\nString s2= \"abc\";\n \nString s3 = new String(\"abc\");\n \nSystem.out.println(s1==s2);\nSystem.out.println(s1==s3);\n\n\n\n\n\n\n\n\n\n\nThis outputs:\n\n\n\ntrue\nfalse\n\n\n\nLiterals are stored in a special place in memory, called a String pool, of course in the form of String Objects. In that pool, a String object with value \"abc\" is only created and stored once. Any other String that gets the value \"abc\" (statically - hard coded) will reference the same String object. So, every time you create a String using a literal, the system will search that pool and checks if the value of the literal exists in an object of the pool. If it does, it sends back the reference to that matching object, if not it creates a new Object and stores it in the pool. So, String references, initialized with the same literals, will point to the same String object. This technique was used to save precious memory, as it shares as much common data as possible.\n\n\n\nNow, you can also see another reason why Strings are immutable. Imagine thread A creating a local string \"abc\" and then a second thread B creating his own local string \"abc\". These two threads will share the same String object... If String was mutable, then if A changed the string, the change would affect thread B, but in a meaningless (put catastrophic) way.\n\n\n\nWhen creating a String using new, you explicitly create a brand new object in the heap. This is also the case for non hard coded String initialization, for example, if you are reading input Strings from a source. These String Objects will not be stored in the pool. Imagine that you create an application that has to hold addresses for users living in Greece. There are four million people living in Athens, so consider the massive waste of space should you store four million String objects with value \"Athens\". In order to pool those non hard coded Strings, there is an API method called intern, and can be used like so:\n\n\n\n\n\n\n\n\n\n01\n02\n03\n04\n05\n06\n07\n08\n09\n10\n\n\n\nString s1 = \"abc\";\nString s2= \"abc\";\n \nString s3 = new String(\"abc\");\n \nSystem.out.println(s1==s2);\nSystem.out.println(s1==s3);\n \ns3 = s3.intern();\nSystem.out.println(s1==s3);\n\n\n\n\n\n\n\n\n\n\nThis will now output:\n\n\n\ntrue false true\n\n\n\nWhen calling intern, the system follows the same procedure as if we did s3 = \"abc\", but without using literals.\n\n\n\nBut be careful. Before Java 7, this pool was located in a special place in the Java Heap, called PermGen. PermGen is of fixed size, and can only hold a limited amount of string literals. So, interning should be used with ease. From Java 7 onward, the pool will be stored in the normal heap, like any other object (making them eligible for garbage collection), in a form of a hashmap and you can adjust its size using -XX:StringTableSize option. You could create your own String pool for that matter, but don't bother.\n\n\n\nThis is only one of the aspects that Java creators changed in the String class. Even more radical changes were made, including the internal String representation (it now has two less static fields).\n\n\n\n4. More articles\n\n\n\nString to Int Java ExampleConvert int to string Java ExampleString CompareTo Java Example\n\n\n\n5. Download the Eclipse Project\n\n\n\nThis was an example of Java String Class.\nDownload\nYou can download the full source code of this example here: Java String Class Example\n\n\n\nLast updated on May 13th, 2021\n","publisher":{"@id":"#Publisher","@type":"Organization","name":"Examples Java Code Geeks","logo":{"@type":"ImageObject","url":"\/wp-content\/uploads\/2013\/05\/JavaCodeGeeks-logo.png"},"sameAs":["https:\/\/feeds.feedburner.com\/examplesjavacodegeeks","https:\/\/www.facebook.com\/javacodegeeks","https:\/\/twitter.com\/javacodegeeks","https:\/\/www.linkedin.com\/groups\/3810709\/","https:\/\/www.youtube.com\/channel\/UCxoUc7Rar2q90Gu0nT2ffuQ","https:\/\/github.com\/javacodegeeks\/"]},"sourceOrganization":{"@id":"#Publisher"},"copyrightHolder":{"@id":"#Publisher"},"mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-string-class-example\/","breadcrumb":{"@id":"#Breadcrumb"}},"author":{"@type":"Person","name":"Prateek Sharma","url":"https:\/\/examples.javacodegeeks.com\/author\/prateek-sharma\/"},"image":{"@type":"ImageObject","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":1200,"height":150}}
| og:locale | en_US |
| og:type | article |
| og:site_name | Examples Java Code Geeks |
| article:publisher | https://www.facebook.com/javacodegeeks |
| article:published_time | 2014-03-05T21:52:20+00:00 |
| article:modified_time | 2022-07-05T20:23:46+00:00 |
| og:image | https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg |
| og:image:width | 150 |
| og:image:height | 150 |
| og:image:type | image/jpeg |
| author | Prateek Sharma |
| twitter:card | summary_large_image |
| twitter:creator | @javacodegeeks |
| twitter:label1 | Written by |
| twitter:data1 | Prateek Sharma |
| twitter:label2 | Est. reading time |
| twitter:data2 | 19 minutes |
| None | IE=edge |
| msapplication-TileImage | https://examples.javacodegeeks.com/wp-content/uploads/2013/05/JavaCodeGeeks-favIcon.png |
Links:
Viewport: width=device-width, initial-scale=1.0
Robots: index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1