{"id":1189,"date":"2022-02-24T20:17:55","date_gmt":"2022-02-24T20:17:55","guid":{"rendered":"https:\/\/mdr.foobrdigital.com\/?p=1189"},"modified":"2022-02-24T20:17:55","modified_gmt":"2022-02-24T20:17:55","slug":"java-strings","status":"publish","type":"post","link":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/2022\/02\/24\/java-strings\/","title":{"rendered":"Java Strings"},"content":{"rendered":"\n<p>In this tutorial, we will learn about Java strings, how to create them, and various methods of the String class with the help of examples.<\/p>\n\n\n\n<p id=\"introduction\">In Java, a string is a sequence of characters. For example,&nbsp;<var>&#8220;hello&#8221;<\/var>&nbsp;is a string containing a sequence of characters&nbsp;<var>&#8216;h&#8217;<\/var>,&nbsp;<var>&#8216;e&#8217;<\/var>,&nbsp;<var>&#8216;l&#8217;<\/var>,&nbsp;<var>&#8216;l&#8217;<\/var>, and&nbsp;<var>&#8216;o&#8217;<\/var>.<\/p>\n\n\n\n<p>We use&nbsp;<strong>double quotes<\/strong>&nbsp;to represent a string in Java. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ create a string\nString type = \"Java programming\";<\/code><\/pre>\n\n\n\n<p>Here, we have created a string variable named&nbsp;<var>type<\/var>. The variable is initialized with the string&nbsp;<code>Java Programming<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"example\">Example: Create a String in Java<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n  public static void main(String&#91;] args) {\n    \n    \/\/ create strings\n    String first = \"Java\";\n    String second = \"Python\";\n    String third = \"JavaScript\";\n\n    \/\/ print strings\n    System.out.println(first);   \/\/ print Java\n    System.out.println(second);  \/\/ print Python\n    System.out.println(third);   \/\/ print JavaScript\n  }\n}<\/code><\/pre>\n\n\n\n<p>In the above example, we have created three strings named&nbsp;<var>first<\/var>,&nbsp;<var>second<\/var>, and&nbsp;<var>third<\/var>. Here, we are directly creating strings like primitive types.<\/p>\n\n\n\n<p>However, there is another way of creating Java strings (using the&nbsp;<code>new<\/code>&nbsp;keyword). We will learn about that later in this tutorial.<\/p>\n\n\n\n<p><strong>Note<\/strong>: Strings in Java are not primitive types (like&nbsp;<code>int<\/code>,&nbsp;<code>char<\/code>, etc). Instead, all strings are objects of a predefined class named&nbsp;<code>String<\/code>.<\/p>\n\n\n\n<p>And, all string variables are instances of the&nbsp;<code>String<\/code>&nbsp;class.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Java String Operations<\/h2>\n\n\n\n<p>Java String provides various methods to perform different operations on strings. We will look into some of the commonly used string operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"string-length\">1. Get length of a String<\/h3>\n\n\n\n<p>To find the length of a string, we use the&nbsp;<code>length()<\/code>&nbsp;method of the String. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n  public static void main(String&#91;] args) {\n\n    \/\/ create a string\n    String greet = \"Hello! World\";\n    System.out.println(\"String: \" + greet);\n\n    \/\/ get the length of greet\n    int length = greet.length();\n    System.out.println(\"Length: \" + length);\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>String: Hello! World\nLength: 12<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, the\u00a0<code>length()<\/code>\u00a0method calculates the total number of characters in the string and returns it.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"join-strings\">2. Join Two Java Strings<\/h3>\n\n\n\n<p>We can join two strings in Java using the&nbsp;<code>concat()<\/code>&nbsp;method. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n  public static void main(String&#91;] args) {\n\n    \/\/ create first string\n    String first = \"Java \";\n    System.out.println(\"First String: \" + first);\n\n    \/\/ create second\n    String second = \"Programming\";\n    System.out.println(\"Second String: \" + second);\n\n    \/\/ join two strings\n    String joinedString = first.concat(second);\n    System.out.println(\"Joined String: \" + joinedString);\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>First String: Java \nSecond String: Programming     \nJoined String: Java Programming<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have created two strings named&nbsp;<var>first<\/var>&nbsp;and&nbsp;<var>second<\/var>. Notice the statement,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>String joinedString = first.concat(second);<\/code><\/pre>\n\n\n\n<p>Here, the&nbsp;<code>concat()<\/code>&nbsp;method joins the&nbsp;<var>second<\/var>&nbsp;string to the&nbsp;<var>first<\/var>&nbsp;string and assigns it to the&nbsp;<var>joinedString<\/var>&nbsp;variable.<\/p>\n\n\n\n<p>We can also join two strings using the\u00a0<code>+<\/code>\u00a0operator in Java. <\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"compare-strings\">3. Compare two Strings<\/h3>\n\n\n\n<p>In Java, we can make comparisons between two strings using the&nbsp;<code>equals()<\/code>&nbsp;method. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n  public static void main(String&#91;] args) {\n\n    \/\/ create 3 strings\n    String first = \"java programming\";\n    String second = \"java programming\";\n    String third = \"python programming\";\n\n    \/\/ compare first and second strings\n    boolean result1 = first.equals(second);\n    System.out.println(\"Strings first and second are equal: \" + result1);\n\n    \/\/ compare first and third strings\n    boolean result2 = first.equals(third);\n    System.out.println(\"Strings first and third are equal: \" + result2);\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Strings first and second are equal: true\nStrings first and third are equal: false<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have created 3 strings named&nbsp;<var>first<\/var>,&nbsp;<var>second<\/var>, and&nbsp;<var>third<\/var>. Here, we are using the&nbsp;<code>equal()<\/code>&nbsp;method to check if one string is equal to another.<\/p>\n\n\n\n<p>The\u00a0<code>equals()<\/code>\u00a0method checks the content of strings while comparing them.<\/p>\n\n\n\n<p><strong>Note<\/strong>: We can also compare two strings using the\u00a0<code>==<\/code>\u00a0operator in Java. However, this approach is different than the\u00a0<code>equals()<\/code>\u00a0method. To learn more, visit\u00a0Java String == vs equals().<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"escape-character\">Escape character in Java Strings<\/h2>\n\n\n\n<p>The escape character is used to escape some of the characters present inside a string.<\/p>\n\n\n\n<p>Suppose we need to include double quotes inside a string.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ include double quote \nString example = \"This is the \"String\" class\";<\/code><\/pre>\n\n\n\n<p>Since strings are represented by&nbsp;<strong>double quotes<\/strong>, the compiler will treat&nbsp;<var>&#8220;This is the &#8220;<\/var>&nbsp;as the string. Hence, the above code will cause an error.<\/p>\n\n\n\n<p>To solve this issue, we use the escape character&nbsp;<code>\\<\/code>&nbsp;in Java. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ use the escape character\nString example = \"This is the \\\"String\\\" class.\";<\/code><\/pre>\n\n\n\n<p>Now escape characters tell the compiler to escape&nbsp;<strong>double quotes<\/strong>&nbsp;and read the whole text.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"immutable-string\">Java Strings are Immutable<\/h2>\n\n\n\n<p>In Java, strings are&nbsp;<strong>immutable<\/strong>. This means, once we create a string, we cannot change that string.<\/p>\n\n\n\n<p>To understand it more deeply, consider an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ create a string\nString example = \"Hello! \";<\/code><\/pre>\n\n\n\n<p>Here, we have created a string variable named&nbsp;<var>example<\/var>. The variable holds the string&nbsp;<var>&#8220;Hello! &#8220;<\/var>.<\/p>\n\n\n\n<p>Now suppose we want to change the string.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ add another string \"World\"\n\/\/ to the previous tring example\nexample = example.concat(\" World\");<\/code><\/pre>\n\n\n\n<p>Here, we are using the&nbsp;<code>concat()<\/code>&nbsp;method to add another string&nbsp;<var>World<\/var>&nbsp;to the previous string.<\/p>\n\n\n\n<p>It looks like we are able to change the value of the previous string. However, this is not&nbsp;<code>true<\/code>.<\/p>\n\n\n\n<p>Let&#8217;s see what has happened here,<\/p>\n\n\n\n<ol><li>JVM takes the first string&nbsp;<var>&#8220;Hello! &#8220;<\/var><\/li><li>creates a new string by adding&nbsp;<var>&#8220;World&#8221;<\/var>&nbsp;to the first string<\/li><li>assign the new string&nbsp;<var>&#8220;Hello! World&#8221;<\/var>&nbsp;to the&nbsp;<var>example<\/var>&nbsp;variable<\/li><li>the first string&nbsp;<var>&#8220;Hello! &#8220;<\/var>&nbsp;remains unchanged<\/li><\/ol>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"new-keyword\">Creating strings using the new keyword<\/h2>\n\n\n\n<p>So far we have created strings like primitive types in Java.<\/p>\n\n\n\n<p>Since strings in Java are objects, we can create strings using the&nbsp;<code>new<\/code>&nbsp;keyword as well. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ create a string using the new keyword\nString name = new String(\"Java String\");<\/code><\/pre>\n\n\n\n<p>In the above example, we have created a string&nbsp;<var>name<\/var>&nbsp;using the&nbsp;<code>new<\/code>&nbsp;keyword.<\/p>\n\n\n\n<p>Here, when we create a string object, the\u00a0<code>String()<\/code>\u00a0constructor is invoked. <\/p>\n\n\n\n<p><strong>Note<\/strong>: The\u00a0<code>String<\/code>\u00a0class provides various other constructors to create strings. To learn more, visit\u00a0Java String (official Java documentation).<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Create Java Strings using the new keyword<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n  public static void main(String&#91;] args) {\n\n    \/\/ create a string using new\n    String name = new String(\"Java String\");\n\n    System.out.println(name);  \/\/ print Java String\n  }\n}<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"string-literal-vs-new\">Create String using literals vs new keyword<\/h3>\n\n\n\n<p>Now that we know how strings are created using string literals and the&nbsp;<code>new<\/code>&nbsp;keyword, let&#8217;s see what is the major difference between them.<\/p>\n\n\n\n<p>In Java, the JVM maintains a&nbsp;<strong>string pool<\/strong>&nbsp;to store all of its strings inside the memory. The string pool helps in reusing the strings.<\/p>\n\n\n\n<p>1. While creating strings using string literals,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>String example = \"Java\";<\/code><\/pre>\n\n\n\n<p>Here, we are directly providing the value of the string (<code>Java<\/code>). Hence, the compiler first checks the string pool to see if the string already exists.<\/p>\n\n\n\n<ul><li><strong>If the string already exists<\/strong>, the new string is not created. Instead, the new reference,&nbsp;<var>example<\/var>&nbsp;points to the already existed string (<code>Java<\/code>).<\/li><li><strong>If the string doesn&#8217;t exist<\/strong>, the new string (<code>Java<\/code>&nbsp;is created.<\/li><\/ul>\n\n\n\n<p>2. While creating strings using the new keyword,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>String example = new String(\"Java\");<\/code><\/pre>\n\n\n\n<p>Here, the value of the string is not directly provided. Hence, a new&nbsp;<code>\"Java\"<\/code>&nbsp;string is created even though&nbsp;<code>\"Java\"<\/code>&nbsp;is already present inside the memory pool.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"string-methods\">Methods of Java String<\/h2>\n\n\n\n<p>Besides those mentioned above, there are various\u00a0string methods\u00a0present in Java. Here are some of those methods:<\/p>\n\n\n\n<figure class=\"wp-block-table is-style-regular\"><table><tbody><tr><th>Methods<\/th><th>Description<\/th><\/tr><tr><td>contains()<\/td><td>checks whether the string contains a substring<\/td><\/tr><tr><td>substring()<\/td><td>returns the substring of the string<\/td><\/tr><tr><td>join()<\/td><td>join the given strings using the delimiter<\/td><\/tr><tr><td>replace()<\/td><td>replaces the specified old character with the specified new character<\/td><\/tr><tr><td>replaceAll()<\/td><td>replaces all substrings matching the regex pattern<\/td><\/tr><tr><td>replaceFirst()<\/td><td>replace the first matching substring<\/td><\/tr><tr><td>charAt()<\/td><td>returns the character present in the specified location<\/td><\/tr><tr><td>getBytes()<\/td><td>converts the string to an array of bytes<\/td><\/tr><tr><td>indexOf()<\/td><td>returns the position of the specified character in the string<\/td><\/tr><tr><td>compareTo()<\/td><td>compares two strings in the dictionary order<\/td><\/tr><tr><td>compareToIgnoreCase()<\/td><td>compares two strings ignoring case differences<\/td><\/tr><tr><td>trim()<\/td><td>removes any leading and trailing whitespaces<\/td><\/tr><tr><td>format()<\/td><td>returns a formatted string<\/td><\/tr><tr><td>split()<\/td><td>breaks the string into an array of strings<\/td><\/tr><tr><td>toLowerCase()<\/td><td>converts the string to lowercase<\/td><\/tr><tr><td>toUpperCase()<\/td><td>converts the string to uppercase<\/td><\/tr><tr><td>valueOf()<\/td><td>returns the string representation of the specified argument<\/td><\/tr><tr><td>toCharArray()<\/td><td>converts the string to a <code>char<\/code> array<\/td><\/tr><tr><td>matches()<\/td><td>checks whether the string matches the given regex<\/td><\/tr><tr><td>startsWith()<\/td><td>checks if the string begins with the given string<\/td><\/tr><tr><td>endsWith()<\/td><td>checks if the string ends with the given string<\/td><\/tr><tr><td>isEmpty()<\/td><td>checks whether a string is empty of not<\/td><\/tr><tr><td>intern()<\/td><td>returns the canonical representation of the string<\/td><\/tr><tr><td>contentEquals()<\/td><td>checks whether the string is equal to charSequence<\/td><\/tr><tr><td>hashCode()<\/td><td>returns a hash code for the string<\/td><\/tr><tr><td>subSequence()<\/td><td>returns a subsequence from the string<\/td><\/tr><\/tbody><\/table><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we will learn about Java strings, how to create them, and various methods of the String class with the help of examples. In Java, a string is a sequence of characters. For example,&nbsp;&#8220;hello&#8221;&nbsp;is a string containing a sequence of characters&nbsp;&#8216;h&#8217;,&nbsp;&#8216;e&#8217;,&nbsp;&#8216;l&#8217;,&nbsp;&#8216;l&#8217;, and&nbsp;&#8216;o&#8217;. We use&nbsp;double quotes&nbsp;to represent a string in Java. For example, Here, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[484],"tags":[],"_links":{"self":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1189"}],"collection":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/comments?post=1189"}],"version-history":[{"count":0,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1189\/revisions"}],"wp:attachment":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/media?parent=1189"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/categories?post=1189"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/tags?post=1189"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}