Java String is one of the most widely used class. Java String class is defined in java.lang package. Show
Java String
Let’s go ahead and learn more about Java String class. Different Ways to Create StringThere are many ways to create a string object in java, some of the popular ones are given below.
Java String compareString class provides equals() and equalsIgnoreCase() methods to compare two strings. These methods compare the value of string to check if two strings are equal or not. It returns true if two strings are equal and false if not. package com.journaldev.string.examples; /** * Java String Example * * @author pankaj * */ public class StringEqualExample { public static void main(String[] args) { //creating two string object String s1 = "abc"; String s2 = "abc"; String s3 = "def"; String s4 = "ABC"; System.out.println(s1.equals(s2));//true System.out.println(s2.equals(s3));//false System.out.println(s1.equals(s4));//false; System.out.println(s1.equalsIgnoreCase(s4));//true } }Output of above program is: true false false trueString class implements Comparable interface, which provides compareTo() and compareToIgnoreCase() methods and it compares two strings lexicographically. Both strings are converted into Unicode value for comparison and return an integer value which can be greater than, less than or equal to zero. If strings are equal then it returns zero or else it returns either greater or less than zero. package com.journaldev.examples; /** * Java String compareTo Example * * @author pankaj * */ public class StringCompareToExample { public static void main(String[] args) { String a1 = "abc"; String a2 = "abc"; String a3 = "def"; String a4 = "ABC"; System.out.println(a1.compareTo(a2));//0 System.out.println(a2.compareTo(a3));//less than 0 System.out.println(a1.compareTo(a4));//greater than 0 System.out.println(a1.compareToIgnoreCase(a4));//0 } }Output of above program is: 0 -3 32 0Please read this in more detail at String compareTo example. Java String MethodsLet’s have a look at some of the popular String class methods with an example program.
String ConcatenationString concatenation is very basic operation in java. String can be concatenated by using “+” operator or by using concat() method. package com.journaldev.examples; /** * Java String concatenation * * @author pankaj * */ public class StringConcatExample { public static void main(String[] args) { String s1 = "Hello"; String s2 = "World"; String s3 = s1 + s2; //using + operator System.out.println("Using + operator: "); System.out.println(s3); //using concat method System.out.println("Using concat method: "); System.out.println(s1.concat(s2)); } }Output of above program is: Using + operator: HelloWorld Using concat method: HelloWorldCheck this post for more information about String Concatenation in Java. Java String PoolMemory management is the most important aspect of any programming language. Memory management in case of string in Java is a little bit different than any other class. To make Java more memory efficient, JVM introduced a special memory area for the string called String Constant Pool. When we create a string literal it checks if there is identical string already exist in string pool or not. If it is there then it will return the reference of the existing string of string pool. Let’s have a look at the below example program. package com.journaldev.examples; /** * Java String Pool Example * */ public class StringPoolExample { public static void main(String[] args) { String a = "abc"; String b = "abc"; String c = "def"; //same reference if (a==b) { System.out.println("Both string refer to the same object"); } //different reference if (a==c) { System.out.println("Both strings refer to the same object"); }else { System.out.println("Both strings refer to the different object"); } } }The output of above program is: Both string refer to the same object Both strings refer to the different objectCheck this post for more about Java String Pool. String intern() MethodWhen we create a string using string literal, it will be created in string pool but what if we create a string using new keyword with the same value that exists in string pool? Can we move the String from heap memory to string pool? For this intern() method is used and it returns a canonical representation of string object. When we call intern() method on string object that is created using the new keyword, it checks if there is already a String with the same value in the pool? If yes, then it returns the reference of that String object from the pool. If not, then it creates a new String with the same content in the pool and returns the reference. package com.journaldev.examples; /** * Java String intern * * @author pankaj * */ public class StringInternExample { public static void main(String[] args) { String s1 = "pankaj"; String s2 = "pankaj"; String s3 = new String("pankaj"); System.out.println(s1==s2);//true System.out.println(s2==s3);//false String s4 = s3.intern(); System.out.println(s1==s4);//true } }Check this post to learn more about Java String intern method. String Immutability BenefitsSome of the benefits of String being immutable class are:
Check this post for more about Sting Immutablity Benefits. Java 8 String join()A new static method join() has been added in String class in Java 8. This method returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter. Let’s look at an example to understand it easily. List<String> words = Arrays.asList(new String[]{"Hello", "World", "2019"}); String msg = String.join(" ", words); System.out.println(msg);Output: Hello World 2019 Java 9 String MethodsThere are two methods added in String class in Java 9 release. They are - codePoints() and chars(). Both of these methods return IntStream object on which we can perform some operations. Let’s have a quick look at these methods. String s = "abc"; s.codePoints().forEach(x -> System.out.println(x)); s.chars().forEach(x -> System.out.println(x));Output: 97 98 99 97 98 99Java 11 String Class New MethodsThere are many new methods added in String class in Java 11 release.
Let’s look at an example program for these methods. package com.journaldev.strings; import java.util.List; import java.util.stream.Collectors; /** * JDK 11 New Functions in String class * * @author pankaj * */ public class JDK11StringFunctions { public static void main(String[] args) { // isBlank() String s = "abc"; System.out.println(s.isBlank()); s = ""; System.out.println(s.isBlank()); // lines() String s1 = "Hi\nHello\rHowdy"; System.out.println(s1); List lines = s1.lines().collect(Collectors.toList()); System.out.println(lines); // strip(), stripLeading(), stripTrailing() String s2 = " Java, \tPython\t "; System.out.println("#" + s2 + "#"); System.out.println("#" + s2.strip() + "#"); System.out.println("#" + s2.stripLeading() + "#"); System.out.println("#" + s2.stripTrailing() + "#"); // repeat() String s3 = "Hello\n"; System.out.println(s3.repeat(3)); s3 = "Co"; System.out.println(s3.repeat(2)); } }Output: false true Hi Hello Howdy [Hi, Hello, Howdy] # Java, Python # #Java, Python# #Java, Python # # Java, Python# Hello Hello Hello CoCoThat’s all about Java String class, it’s method and String manipulation examples. You can checkout more String examples from our GitHub Repository. Reference: API Doc Which of these method of class string is used to extract more than one character at a time?Which of these method of class String is used to extract more than one character at a time a String object? Explanation: None. 2. Which of these methods is an alternative to getChars() that stores the characters in an array of bytes?
Which methods are used to extract the characters from string?Below are various ways to do so:. Using String. charAt() method: Get the string and the index. ... . Using String. toCharArray() method: Get the string and the index. ... . Using Java 8 Streams: Get the string and the index. Convert String into IntStream using String. ... . Using String. codePointAt() method: ... . Using String. getChars() method:. Which method is used to extract a single character at an index?Use the charAt method to get a character at a particular index.
Which of these method of class string is used to extract a substring from a string object?The substring(int start) method of StringBuffer class is the inbuilt method used to return a substring start from index start and extends to end of this sequence. The string returned by this method contains all character from index start to end of the old sequence.
|