Loading...

Follow KnpCode on Feedspot

Continue with Google
Continue with Facebook
or

Valid

If you want to get specific character of the String by index you can use charAt() method of the String class in Java.

charAt() method
  • char charAt(int index)– Returns the char value at the specified index. For a String of length n the passed index should be with in the range 0 to n-1. Method throws IndexOutOfBoundsException if the index argument is negative or not less than the length of this string.
Java String charAt() method examples

1. Using charAt() to get the first and last characters of the String.

public class StringCase {

	public static void main(String[] args) {
		String str = "Hello World";
		// getting first character
		char firstChar = str.charAt(0);
		// getting last character
		char lastChar = str.charAt(str.length()-1);
		System.out.println("First character- " + firstChar);
		System.out.println("Last character- " + lastChar);
	}
}

Output

First character- H
Last character- d

Since index starts at 0 so first character is retrieved using the index 0. For getting the last character of the String, length() method of the String class is used to get the length of the String.

2. Getting all the characters of the String by iterating the String and retrieving each character using charAt() method.

public class StringCase {

	public static void main(String[] args) {
		String str = "Hello World";
		for(int i = 0; i < str.length(); i++) {
			System.out.println(str.charAt(i));
		}
	}
}

Output

H
e
l
l
o
 
W
o
r
l
d

3. If any index outside the range of the String is used that results in IndexOutOfBoundsException.

public class StringCase {

	public static void main(String[] args) {
		String str = "Hello World";
		System.out.println(str.charAt(20));
	}
}

Output

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 20
	at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:44)
	at java.base/java.lang.String.charAt(String.java:692)
	at com.knpcode.proj.Programs.String.StringCase.main(StringCase.java:7)

That’s all for the topic Java String charAt() Method. If something is missing or you have something to share about the topic please write a comment.

You may also like

The post Java String charAt() Method appeared first on KnpCode.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this post you’ll learn how to change case of the String in Java using toLowerCase() and toUpperCase() methods.

toLowerCase() method in Java String
  • String toLowerCase()– Used to convert all of the characters in this String to lower case. If no argument is passed then rules of the default locale is used, making it equivalent to calling toLowerCase(Locale.getDefault()). Note that this method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently.
  • String toLowerCase(Locale locale)– Converts all of the characters in this String to lower case using the rules of the given Locale.

public class StringCase {

	public static void main(String[] args) {
		String str = "TEST String";
		System.out.println("String converted in all lower case- " + str.toLowerCase());
	}
}

Output

String converted in all lower case- test string

Note that the modified string is a new String object which has to be assigned to a String object if you intend to store the modified String. This is because String is immutable in Java.

public class StringCase {

	public static void main(String[] args) {
		String str = "TEST String";
		System.out.println("String converted in all lower case- " + str.toLowerCase());
		System.out.println("Original String- " + str);
		// assigning modified string
		str = str.toLowerCase();
		System.out.println("Modified String- " + str);
	}
}

Output

String converted in all lower case- test string
Original String- TEST String
Modified String- test string

Here you can see initially original string remains intact even though toLowerCase() method is called on it. Once str is assigned the modified string then only it changes.

toUpperCase() method in Java String
  • String toUpperCase()– Used to convert all of the characters in this String to upper case. If no argument is passed then rules of the default locale is used, making it equivalent to calling toUpperCase(Locale.getDefault()). Note that this method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently.
  • String toUpperCase(Locale locale)– Converts all of the characters in this String to upper case using the rules of the given Locale.

public class StringCase {

	public static void main(String[] args) {
		String str = "Test String";
		System.out.println("String converted in all upper case- " + str.toUpperCase());
	}
}

Output

String converted in all upper case- TEST STRING

That’s all for the topic Java String toLowerCase() And toUpperCase() Methods. If something is missing or you have something to share about the topic please write a comment.

You may also like

The post Java String toLowerCase() And toUpperCase() Methods appeared first on KnpCode.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this post you’ll learn how to remove spaces from a String in Java, the spaces may be leading spaces, trailing spaces or spaces in between the words. String class provides following options for removing String spaces in Java.

    • If you want to remove spaces at the beginning (leading) and spaces at the end (trailing) best way to do it is to use trim() method of the Java String class. As per trim() method space is defined as any character whose codepoint is less than or equal to ‘U+0020’ (the space character).
    • Java 11 onward there is also strip() method in Java String class for removing leading and trailing white spaces. This method internally uses the Character.isWhitespace() to check for whitepsaces. There are two more methods for removing either leading spaces or trailing spaces.
      If you want to remove only trailing white spaces then you can use-
      • stripLeading()– to remove all leading white spaces. Available Java 11 onward.

      If you want to remove only leading white spaces then you can use-

      • stripTrailing()– to remove all trailing white spaces. Available Java 11 onward.
    • Another option is to use replaceAll() method of the Java String class, passing regex ‘\\s+’ as an argument for removing spaces. This option removes spaces in between the words too apart from leading and trailing spaces.

One thing to remember here is that whenever string is modified in anyway a new String is created as String is immutable in Java, so you need to assign the modified string to a String reference.

Removing spaces using trim() method Java example
  • trim()– Returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose codepoint is less than or equal to ‘U+0020’ (the space character).

public class StringSpaces {
	public static void main(String[] args) {	
		String str = "  Hello    World		";
		str = str.trim();
		System.out.println("String- " + str);
	}
}

Output

String- Hello    World

As you can see leading and trailing spaces are removed though not the spaces in between the words.

Removing spaces using strip() method Java example

Java 11 onward there is also a strip() method in Java to remove leading and trailing spaces from a String.

Strip() method internally uses Character.isWhitespace() to check for white spaces which provides a much wider definition of whitespaces than trim(). In trim() space is defined as any character whose codepoint is less than or equal to ‘U+0020’ (the space character).

Let’s try to clarify it with an example where a unicode character ‘\u2002’ is used which is not recognized by trim() method.

public class StringSpaces {
	public static void main(String[] args) {
		String str = '\u2002'+"Hello World!"+ '\u2002';
		System.out.println("String-" + str);
		str = str.trim();
		System.out.println("String-" + str);
	}
}

Output

String- Hello World!
String- Hello World!

You can see that the leading and trailing spaces are not removed by the trim() method as unicode character greater than ‘\u0020’ is used. Using strip() method you can remove these spaces.

public class StringSpaces {
	public static void main(String[] args) {
		String str = '\u2002'+"Hello World!"+ '\u2002';
		System.out.println("String-" + str);
		str = str.strip();
		System.out.println("String-" + str);
	}
}

Output

String- Hello World!
String-Hello World!

Removing spaces using replaceAll() method Java example

If you have to remove spaces in between the words too apart from leading and trailing spaces then replaceAll() method can be used.

  • replaceAll(String regex, String replacement)– Replaces each substring of this string that matches the given regular expression with the given replacement.

By passing “\\s+” as regex which matches one or many whitespaces and “” as replacement for those whitespaces you can remove all whitespaces from a String.

public class StringSpaces {
	public static void main(String[] args) {	
		String str = "  Hello    World		";
		str = str.replaceAll("\\s+", "");
		System.out.println("String- " + str);
	}
}

Output

String- Hello World!
String- HelloWorld

That’s all for the topic Remove Spaces From a String in Java – trim(), strip() Methods. If something is missing or you have something to share about the topic please write a comment.

You may also like

The post Remove Spaces From a String in Java – trim(), strip() appeared first on KnpCode.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

If you have to get a part of the original String i.e. substring in Java then you can use substring() method of the Java String class.

Java substring() method

There are two variants of the substring() method-

  • String substring(int beginIndex)– Returns a substring of this string where the substring begins with the character at the beginIndex and goes till the end of this string. Method throws IndexOutOfBoundsException if beginIndex is negative or larger than the length of this String object.
  • String substring(int beginIndex, int endIndex)– Returns a string that is a substring of this string. The substring begins at the specified beginIndex and ends at index endIndex – 1. IndexOutOfBoundsException is thrown if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
    For this variant of substring() method remember that-
    • beginIndex – the beginning index, inclusive.
    • endIndex – the ending index, exclusive.
Java substring() method example

1. Using substring(int beginIndex) method to get a substring from the specified index.

public class SubStringExp {

	public static void main(String[] args) {
		String str = "This is a test String";
		String substr = str.substring(10);
		System.out.println("Substring is- " + substr);
	}
}

Output

Substring is- test String

Here extraction of substring starts from index 10 of the original string and extends till end of the String.

2- Using substring(int beginIndex, int endIndex) method to get a substring with in the given index range.

public class SubStringExp {

	public static void main(String[] args) {
		String str = "This is a test String";
		String substr = str.substring(10, 14);
		System.out.println("Substring is- " + substr);
	}
}

Output

Substring is- test

In the substring method, begin index is passed as 10 so extraction starts from that index. End index is 14 so extraction ends at index endIndex -1 = 13.

3- Using substring method along with other String class methods.

You can use substring method with other String class methods where start and end indices can be calculated using those methods. For example you have date in format dd-mm-yyyy and you want the year part then you can use lastIndexOf() method to get the start index for the substring() method to get the desired substring.

public class SubStringExp {

	public static void main(String[] args) {
		String str = "11-07-2019";
		String substr = str.substring(str.lastIndexOf('-') + 1);
		System.out.println("Substring is- " + substr);
	}
}

Output

Substring is- 2019

If you want to get the month part then you can use both indexOf() and lastIndexOf() methods to get the start index and end index respectively.

public class SubStringExp {

	public static void main(String[] args) {
		String str = "11-07-2019";
		String substr = str.substring(str.indexOf('-')+1, str.lastIndexOf('-'));
		System.out.println("Substring is- " + substr);
	}
}

Output

Substring is- 07

That’s all for the topic Java String – substring() Method Example. If something is missing or you have something to share about the topic please write a comment.

You may also like

The post Java String – substring() Method Example appeared first on KnpCode.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

If you want to check if given string is present in another string then in Java you have following options-

  1. Use indexOf() method to find the first occurrence of the specified character or substring. See example.
  2. Use lastIndexOf() method to get index within this string of the last occurrence of the specified character or substring. See example.
  3. Using contains() method in Java you can check if this string contains the specified substring or not. Returns true if substring is found false otherwise. See example.

Note that all of these methods do a case sensitive search so you may need to convert String and substring to similar case (lower or upper case) if you don’t want case to be a factor while searching.

Searching String using indexOf() method in Java

indexOf() method of the Java String class has 4 variants, two are used to search specified character and two are used to search specified substring.

  • int indexOf(int ch)– If found returns the index within this string of the first occurrence of the specified character, otherwise returns -1.
  • int indexOf(int ch, int fromIndex)– If found returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. Returns -1 if character is not found.
  • int indexOf(String str)– If found returns the index within this string of the first occurrence of the specified substring, otherwise returns -1.
  • int indexOf(String str, int fromIndex)– If found returns the index within this string of the first occurrence of the specified substring, starting at the specified index. Returns -1 if substring is not found.

Searching for character in a string using indexOf() example

public class StringSearch {

	public static void main(String[] args) {
		String str = "This is a test String";
		// Search for first occurrence
		int index = str.indexOf('s');
		System.out.println("First occurrence of character 's' found at index " + index);
		// Search for first occurrence after specified index
		index = str.indexOf('s', 11);
		System.out.println("First occurrence of character 's' after index 11 found at index " + index);
	}
}

Output

First occurrence of character 's' found at index 3
First occurrence of character 's' after index 11 found at index 12

Searching for substring in a string using indexOf() Java example

public class StringSearch {

	public static void main(String[] args) {
		String str = "This is a test String";
		// Search for first occurrence
		int index = str.indexOf("test");
		if(index != -1) {
			System.out.println("First occurrence of substring test found at index " + index);
		}else {
			System.out.println("Substring not found ");
		}
		
		// Search for first occurrence after specified index
		index = str.indexOf("test", 6);
		System.out.println("First occurrence of substring test after index 6 found at index " + index);
	}
}

Output

First occurrence of substring test found at index 10
First occurrence of substring test after index 6 found at index 10

Searching String using lastIndexOf() method in Java

lastIndexOf() method of the Java String class has 4 variants, two are used to search specified character and two are used to search specified substring.

  • int lastIndexOf(int ch)– If found returns the index within this string of the last occurrence of the specified character, otherwise returns -1.
  • int lastIndexOf(int ch, int fromIndex)– If found returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. Returns -1 if character is not found.
  • int lastIndexOf(String str)– If found returns the index within this string of the last occurrence of the specified substring, otherwise returns -1.
  • int lastIndexOf(String str, int fromIndex)– If found returns the index within this string of the last occurrence of the specified substring, searching backward at the specified index. Returns -1 if substring is not found.

Searching for character in a string using lastIndexOf() example

public class StringSearch {

	public static void main(String[] args) {
		String str = "This is a test String";
		// Search for last occurrence
		int index = str.lastIndexOf('s');
		System.out.println("Last occurrence of character 's' found at index " + index);
		// Search for last occurrence after specified index
		index = str.lastIndexOf('s', 11);
		System.out.println("Last occurrence of character 's' moving backward from index 11 found at index " + index);
	}
}

Output

Last occurrence of character 's' found at index 12
Last occurrence of character 's' moving backward from index 11 found at index 6

Searching for substring in a string using lastIndexOf() example

public class StringSearch {

	public static void main(String[] args) {
		String str = "test String to test";
		// Search for last occurrence
		int index = str.lastIndexOf("test");
		if(index != -1) {
			System.out.println("Last occurrence of substring test found at index " + index);
		}else {
			System.out.println("Substring not found ");
		}
		
		// Search for last occurrence after specified index
		index = str.lastIndexOf("test", 6);
		System.out.println("Last occurrence of substring test moving backward from index 6 found at index " + index);
	}
}

Output

Last occurrence of substring test found at index 15
Last occurrence of substring test moving backward from index 6 found at index 0

Searching String using contains() method in Java
  • boolean contains(CharSequence s)– Returns true if and only if this string contains the specified sequence of char values, false otherwise.

CharSequence is an interface which is implemented by String, StringBuffer and StringBuilder so objects of these classes can be passed with contains() method.

public class StringSearch {

	public static void main(String[] args) {
		String str = "This is a test String";
		String str1= "test";
		if(str.contains(str1)) {
			System.out.println(str1 + " found in String");
		}else {
			System.out.println(str1 + "is not found in String");
		}
	}
}

Output

test found in String

If you do a search for “Test” false is returned as the search is case sensitive.

public class StringSearch {

	public static void main(String[] args) {
		String str = "This is a test String";
		String str1= "Test";
		if(str.contains(str1)) {
			System.out.println(str1 + " found in String");
		}else {
			System.out.println(str1 + " is not found in String");
		}
	}
}

Output

Test is not found in String

That’s all for the topic Search String in Another String in Java – indexOf, lastIndexOf, contains methods. If something is missing or you have something to share about the topic please write a comment.

You may also like

The post Search String in Another String in Java – indexOf, lastIndexOf, contains methods appeared first on KnpCode.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In a multi-threaded environment shared object can be modified by any of the thread, in some scenarios you may want to ensure that the original object shared among the threads remain unchanged. That can be done by making that object immutable. Since String in Java is immutable by design so it is also thread safe thus a string object can be shared safely among many threads.

Java String immutability and thread safety

One important point to note is that even if String is immutable thus thread safe, reference to the String object is not thread safe.
If String object is passed to a thread and it is modified with in the thread then a new String is created and the reference is changed but the original String remains unchanged. We’ll clear this point with an example.

In the example string object is shared among three threads. While executing these threads, shared string object is modified by appending content to it. When all the threads are finished string object is printed again in the main thread to verify that it remains unchanged.

public class StringThreadSafeExp implements Runnable {
	private String str;
    public StringThreadSafeExp(String str){
        this.str = str;
    }
    @Override
    public void run() {
        System.out.println("Executing Thread- " + Thread.currentThread().getName());        
        // Adding to String  
        str = str + " World";
        System.out.println("Modified String " + str);
    }

	public static void main(String[] args) {
        String str = "Hello";

        Thread t1 = new Thread(new StringThreadSafeExp(str));
        Thread t2 = new Thread(new StringThreadSafeExp(str));
        Thread t3 = new Thread(new StringThreadSafeExp(str));
        t1.start();
        t2.start();
        t3.start();
        // Wait for all threads to terminate
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {    
            e.printStackTrace();
        }
        System.out.println("Original String is " + str);
    }
}

Output

Executing Thread- Thread-2
Executing Thread- Thread-1
Executing Thread- Thread-0
Modified String Hello World
Modified String Hello World
Modified String Hello World
Original String is Hello

As you can see each of thread, when it modifies the passed String gets reference to a new String object pointing to modified content, leaving the original string unchanged.

Immutability of Java String ensures that String once assigned a value can’t be modified. By using a StringBuffer object which is mutable you can verify what happens when a mutable object is shared among threads and modified.

public class StringThreadSafeExp implements Runnable {
	private StringBuffer sb;
    public StringThreadSafeExp(StringBuffer sb){
        this.sb = sb;
    }
    @Override
    public void run() {
        System.out.println("Executing Thread- " + Thread.currentThread().getName());        
        // Adding to String  
        sb.append(" World");
        System.out.println("Modified String " + sb);
    }

	public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");

        Thread t1 = new Thread(new StringThreadSafeExp(sb));
        Thread t2 = new Thread(new StringThreadSafeExp(sb));
        Thread t3 = new Thread(new StringThreadSafeExp(sb));
        t1.start();
        t2.start();
        t3.start();
        // Wait for all threads to terminate
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {    
            e.printStackTrace();
        }
        System.out.println("Original String is " + sb);
    }
}

Output

Executing Thread- Thread-0
Executing Thread- Thread-2
Executing Thread- Thread-1
Modified String Hello World World
Modified String Hello World
Modified String Hello World World World
Original String is Hello World World World

As you can see now the original StringBuffer object itself is modified as it is mutable.

That’s all for the topic Is Java String Thread Safe. If something is missing or you have something to share about the topic please write a comment.

You may also like

The post Is Java String Thread Safe appeared first on KnpCode.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

If you have to compare two Strings in Java or the portion of two Strings on the basis of the content of those Strings then you can do it using one of the following methods-

  1. equals() method or equalsIgnoreCase() if you don’t want to consider case. See example.
  2. compareTo() method or compareToIgnoreCase() if you don’t want to consider case. See example.
  3. For comparing portion of the String you can use startsWith() and endsWith() methods. See example.
  4. To compare region of one String with the specified region of another String you can use regionMatches() method. See example.
Compare Strings using equals() and equalsIgnoreCase() methods
  • boolean equals(Object anObject)– Compares this string to the specified object. This method returns true if the passed argument is not null and is a String object having the same sequence of characters as this String.
  • boolean equalsIgnoreCase(String anotherString)– Compares this String to another String, ignoring case considerations. Two strings are considered equal (ignoring case) if they are of the same length and corresponding characters in the two strings are equal.

Java example using equals() method

public class StringComapre {

	public static void main(String[] args) {
		String str1 = "Hello";
		String str2 = "Hello";
		String str3 = "hello";
		//returns true
		System.out.println("str1.equals(str2)-" + str1.equals(str2));
		//returns false as case is different
		System.out.println("str1.equals(str3)-" + str1.equals(str3));
	}
}

Output

str1.equals(str2)-true
str1.equals(str3)-false

Java example using equalsIgnoreCase() method

public class StringComapre {

	public static void main(String[] args) {
		String str1 = "Hello";
		String str2 = "Hello";
		String str3 = "hello";
		//returns true
		System.out.println("str1.equals(str2)-" + str1.equals(str2));
		//returns true as case is ignored
		System.out.println("str1.equalsIgnoreCase(str3)-" + str1.equalsIgnoreCase(str3));
	}
}

Output

str1.equals(str2)-true
str1.equalsIgnoreCase(str3)-true

Compare Strings using compareTo() and compareToIgnoreCase() methods
  • int compareTo(String anotherString)– Compares two strings lexicographically. Returns positive integer if this String is greater than the argument, returns negative integer if this String is less than the argument, returns zero if this string is equal to the argument.
  • int compareToIgnoreCase(String str)– Compares two strings lexicographically, ignoring case differences. Returns positive integer if this String is greater than the argument, returns negative integer if this String is less than the argument, returns zero if this string is equal to the argument, ignoring case considerations.

Java example using compareTo() method

public class StringComapre {

	public static void main(String[] args) {
		String str1 = "Hello";
		String str2 = "Hello";
		String str3 = "Halo";
		// returns 0
		System.out.println("str1.compareTo(str2): " + str1.compareTo(str2));
		// returns positive integer
		System.out.println("str1.compareTo(str3): " + str1.compareTo(str3));
		// returns negative integer
		System.out.println("str3.compareTo(str1): " + str3.compareTo(str1));
	}
}

Output

str1.compareTo(str2): 0
str1.compareTo(str3): 4
str3.compareTo(str1): -4

Java example using compareToIgnoreCase() method

public class StringComapre {

	public static void main(String[] args) {
		String str1 = "Hello";
		String str2 = "hello";
		String str3 = "cello";
		// returns 0
		System.out.println("str1.compareTo(str2): " + str1.compareToIgnoreCase(str2));
		// returns positive integer
		System.out.println("str1.compareTo(str3): " + str1.compareTo(str3));
		// returns negative integer
		System.out.println("str3.compareTo(str1): " + str3.compareTo(str1));
	}
}

Output

str1.compareTo(str2): 0
str1.compareTo(str3): -27
str3.compareTo(str1): 27

Compare String portions using startsWith() and endsWith() methods
  • boolean startsWith(String str)– Tests if this string starts with the passed argument. Returns true if substring matches at the start, false otherwise.
  • boolean startsWith(String str, int toffset)– Tests if the substring of this string beginning at the specified index starts with the passed argument. Returns true if substring matches at the start, false otherwise.
  • boolean endsWith(String str)– Tests if this string ends with the passed argument. Returns true if substring matches at the end, false otherwise.

Java example using startsWith() and endsWith()

public class StringComapre {

	public static void main(String[] args) {
		String str = "Compare this String";

		// returns true
		System.out.println("str.startsWith(\"Compare\"): " + str.startsWith("Compare"));
		// returns false
		System.out.println("str.startsWith(\"Comparison\"): " + str.startsWith("Comparison"));
		// returns true- Comparison starts from index 8
		System.out.println("str.startsWith(\"this\"): " + str.startsWith("this", 8));
		
		// returns true
		System.out.println("str.endsWith(\"String\"): " + str.endsWith("String"));
		// returns false
		System.out.println("str.endsWith(\"Sting\"): " + str.endsWith("Sting"));
	}
}

Output

str.startsWith("Compare"): true
str.startsWith("Comparison"): false
str.startsWith("this"): true
str.endsWith("String"): true
str.endsWith("Sting"): false

Compare String portions using regionMatches method
  • boolean regionMatches(int toffset, String other, int ooffset, int len)– Tests if two string regions are equal. A substring of the first string is compared to the substring of the second string. Index from which the substring of the first string starts is specified using toffset. Index from which the substring of the second string starts is specified using ooffset. Length of the substring which is to be compared is specfied using len.
  • boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)– If ignoreCase is passed as true, ignore case when comparing characters.

public class StringComapre {

	public static void main(String[] args) {
		String str1 = "Compare this string";
		String str2 = "Compare with this String";
		
		// Comparing "this" portion of both Strings- true
		System.out.println("str1.regionMatches(8, str2, 13, 4): " + str1.regionMatches(8, str2, 13, 4));
		// Comparing "String" portion of both Strings- false when case is considered
		System.out.println("str1.regionMatches(13, str2, 18, 6): " + str1.regionMatches(13, str2, 18, 6));
		// Comparing "String" portion of both Strings- true when case is ignored
		System.out.println("str1.regionMatches(true, 13, str2, 18, 6): " + str1.regionMatches(true, 13, str2, 18, 6));
	}
}

Output

str1.regionMatches(8, str2, 13, 4): true
str1.regionMatches(13, str2, 18, 6): false
str1.regionMatches(true, 13, str2, 18, 6): true

That’s all for the topic Compare Two Strings in Java – equals, compareTo() methods . If something is missing or you have something to share about the topic please write a comment.

You may also like

  • Java String length() Method With Examples
  • Finally Block in Java
  • Java Program to Find The Maximum Element in Each Row of a Matrix
  • Different Ways to Iterate a HashMap in Java
  • ArrayBlockingQueue in Java
  • What is HDFS Federation in Hadoop
  • The post Compare Two Strings in Java – equals, compareTo() methods appeared first on KnpCode.

    • Show original
    • .
    • Share
    • .
    • Favorite
    • .
    • Email
    • .
    • Add Tags 

    To find length of a String you can use length() method of the Java String class. This method returns the count of characters in the String object including spaces.

    Java String length() method examples

    1. In the examples there are two strings and length of those String is calculated using length() method.

    public class StringLength {
    
    	public static void main(String[] args) {
    		String str1 = "String length method";
    		//separated by 4 spaces
    		String str2 = "Hello    World";
    		System.out.println("Length of str1- " + str1.length());
    		System.out.println("Length of str2- " + str2.length());
    	}
    }

    Output

    Length of str1- 20
    Length of str2- 14

    2- Printing each character by iterating a String, using String’s length() method to limit the iteration.

    public class StringLength {
    
    	public static void main(String[] args) {
    		String str = "Hello";
    		for(int i = 0; i < str.length(); i++) {
    			System.out.println(str.charAt(i));
    		}
    	}
    }

    Output

    H
    e
    l
    l
    o

    That’s all for the topic Java String length() Method With Examples. If something is missing or you have something to share about the topic please write a comment.

    You may also like

  • Compact Strings in Java 9
  • Java Multithreading Interview Questions And Answers
  • Spliterator in Java With Examples
  • Difference Between sleep() And wait() Methods in Java
  • How to Convert File to Byte Array in Java
  • How to Read And Write Avro Files in Hadoop
  • The post Java String length() Method With Examples appeared first on KnpCode.

    • Show original
    • .
    • Share
    • .
    • Favorite
    • .
    • Email
    • .
    • Add Tags 

    One of the enhancement in Java 9 is Compact String with the goal to make String class and related classes more space efficient while maintaining performance in most scenarios.

    Motivation for introducing Compact String in Java

    Till Java 8 String was stored internally as a character array with each character taking 2 bytes of space where UTF16 was used for character encoding.

    Data gathered from many different applications indicates that strings are a major component of heap usage, moreover most String objects contain only Latin-1 also called ISO-8859-1 characters. Latin-1 is a 8-bit character set meaning it needs 1 byte of space i.e. 1 byte less than UTF16 for each character. If strings can be stored using Latin-1 character encoding that will bring substantial reduction in memory usage by String objects. That is the motivation behind compact Strings in Java.

    Java 9 compact Strings

    Java 9 onwards this space efficiency optimization is brought to String class in Java using a new feature called compact Strings.

    Instead of char array Java 9 onward String is stored internally as a byte array plus an encoding-flag field.

    This new String class stores characters encoded as ISO-8859-1/Latin-1 (1 byte per character) if all the characters of the String can be stored using 1 byte each.

    In case any character of the String needs 2 bytes (in case of special characters) all the characters of the String are stored as UTF-16 (2 bytes per character).

    How to determine whether UTF16 or Latin-1 character encoding has to be used is done using the encoding-flag field known as coder.

    So in Java 8 String class there was this code for String storage-

    /** The value is used for character storage. */
        private final char value[];

    Which is changed Java 9 onward to use byte[]-

    @Stable
        private final byte[] value;

    A flag (field named coder) to identify the encoding is also added-

    /**
         * The identifier of the encoding used to encode the bytes in
         * {@code value}. The supported values in this implementation are
         *
         * LATIN1
         * UTF16
         *
         * @implNote This field is trusted by the VM, and is a subject to
         * constant folding if String instance is constant. Overwriting this
         * field after construction will cause problems.
         */
        private final byte coder;

    Which can have either of the following two values.

    @Native static final byte LATIN1 = 0;
        @Native static final byte UTF16  = 1;

    Changes in String methods for compact Strings

    Methods in String class are also changed to check if String is stored as Latin-1 character or UTF-16 character and appropriate implementation is used. For example substring() method of the String class with Compact String changes-

    public String substring(int beginIndex) {
            if (beginIndex < 0) {
                throw new StringIndexOutOfBoundsException(beginIndex);
            }
            int subLen = length() - beginIndex;
            if (subLen < 0) {
                throw new StringIndexOutOfBoundsException(subLen);
            }
            if (beginIndex == 0) {
                return this;
            }
            return isLatin1() ? StringLatin1.newString(value, beginIndex, subLen)
                              : StringUTF16.newString(value, beginIndex, subLen);
        }
    
        private boolean isLatin1() {
            return COMPACT_STRINGS && coder == LATIN1;
        }

    Using XX:-CompactStrings option

    By default Compact String option is enabled which can be disabled by using -XX:-CompactStrings VM option. You may want to disable it, if mainly UTF-16 Strings are used in your application.

    That’s all for the topic Compact Strings in Java 9. If something is missing or you have something to share about the topic please write a comment.

    You may also like
  • Java StringBuilder With Method Examples
  • Finally Block in Java
  • How to Sort HashSet in Java
  • ReentrantLock in Java With Examples
  • Radix Sort Java Program
  • OutputCommitter in Hadoop MapReduce
  • The post Compact Strings in Java 9 appeared first on KnpCode.

    • Show original
    • .
    • Share
    • .
    • Favorite
    • .
    • Email
    • .
    • Add Tags 

    StringBuilder in Java is a mutable sequence of characters. The API provided by StringBuilder class is compatible with StringBuffer with one noticeable difference, with StringBuilder there is no guarantee of synchronization.

    When string buffer is being used by a single thread it is recommended that StringBuilder be used instead of StringBuffer as it will be faster as there is no synchronization overhead.

    Why is StringBuilder class required

    You may be wondering why is StringBuilder or StringBuffer class required when String class is already there with an extensive API.

    In the post String in Java we have already seen that String objects are immutable and their values cannot be changed after they are created. Because of this immutability property when you use a String modification method like concatenation what actually happens is that a new String is created and returned that contains the result of the operation. That may lead to creation of lots of intermediate String objects if String is modified several times which in turn means more memory being used for these intermediate objects.

    Using StringBuilder or StringBuffer you can avoid this problem of creating several objects as these classes are mutable.

    Important points about Java StringBuilder

    Some of the important points about StringBuilder class.

    1. StringBuilder in Java provides much of the functionality of String class with one prominent deviation that StringBuilder is mutable.
    2. StringBuilder has an API compatible with StringBuffer except one design difference StringBuilder is not synchronized so it is not thread safe like StrinBuffer.
    3. Every StringBuilder is created with a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.
    Java StringBuilder Constructors

    There are four constructors in StringBuilder class.

    1. StringBuilder()– Constructs an empty string builder and an initial capacity of 16 characters.
      StringBuilder sb = new StringBuilder();
    2. StringBuilder(int capacity)– Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.
      StringBuilder sb = new StringBuilder(30);
    3. StringBuilder(CharSequence seq)– Constructs a string builder that contains the same characters as the specified CharSequence.
      Here CharSequence is an interface which is implemented by CharBuffer, Segment, String, StringBuffer, StringBuilder.
    4. StringBuilder(String str)– Constructs a string builder initialized to the contents of the specified string.
      StringBuilder sb = new StringBuilder("Hello");
    Java StringBuilder method examples

    append method

    append method in StringBuilder class is overloaded so as to accept data of any type. This method appends the string representation of the given data type to existing buffer. The append method always adds these characters at the end of the buffer.

    public class StringLiteral  {
    	public static void main(String[] args) {
    		StringBuilder sb = new StringBuilder("Hello");
    		sb.append(" ");
    		//chaining several appends
    		sb.append("World").append(" ").append(123);
    		System.out.println("Apended String- " + sb.toString());
    	}
    }

    Output

    Apended String- Hello World 123

    As you can see from the example append is used with both String and int as argument as it is overloaded for these data types. You can also chain several append methods as done in the example.

    insert method

    insert method is also overloaded in StringBuilder class so as to accept data of any type. This method is used to insert the string representation of the given data type to existing buffer. The insert method adds the characters at a specified point.

    insert method takes two arguments first an integer indicating the position where characters are to be inserted in the buffer and second argument is the text to be inserted.

    public class StringLiteral  {
    	public static void main(String[] args) {
    		StringBuffer sb = new StringBuffer("Hello");
    		sb.insert(5, " World");
    		System.out.println("String after insert- " + sb);
    	}
    }

    Output

    String after insert- Hello World

    length and capacity methods

    • capacity()– Returns the current capacity of the StringBuilder.
    • length()– Returns the number of characters in this sequence.

    public class StringLiteral  {
    	public static void main(String[] args) {
    		StringBuilder sb = new StringBuilder(30);
    		sb.append("Hello");
    		System.out.println("Capacity of StringBuilder- " + sb.capacity());
    		System.out.println("Length of StringBuilder- " + sb.length());
    	}
    }

    Output

    Capacity of StringBuilder- 30
    Length of StringBuilder- 5

    Here you can see that StringBuilder is created with the capacity as 30 so the capacity is displayed as 30 where as number of characters in the buffer is 5 so the length is displayed as 5.

    reverse method

    • reverse()– Reverses the existing StringBuilder.

    public class StringLiteral  {
    	public static void main(String[] args) {
    		StringBuilder sb = new StringBuilder("Hello");
    		System.out.println("Reversed- " + sb.reverse());
    	}
    }

    Output

    Reversed- olleH

    replace method

    • replace(int start, int end, String str)– Replaces the characters in a substring of this sequence (start to end-1) with characters in the specified String.

    public class StringLiteral  {
    	public static void main(String[] args) {
    		StringBuilder sb = new StringBuilder("Hello");
    		sb.replace(3, 5, "ena");
    		System.out.println("String- " + sb);
    	}
    }

    Output

    String- Helena

    delete and deleteCharAt methods

    • delete(int start, int end)– Removes the characters in a substring of this sequence. start which indicates the beginning index is inclusive where as end which indicates the ending index is exclusive.
    • deleteCharAt(int index)– Removes the char at the specified position in this sequence.

    public class StringLiteral  {
    	public static void main(String[] args) {
    		StringBuilder sb = new StringBuilder("Hello");
    		sb.delete(1, 3);
    		System.out.println("After deletion- " + sb);
    		System.out.println("Length of StringBuilder- " + sb.length());
    	}
    }

    Output

    After deletion- Hlo
    Length of StringBuilder- 3

    public class StringLiteral  {
    	public static void main(String[] args) {
    		StringBuilder sb = new StringBuilder("Hello");
    		sb.deleteCharAt(4);
    		System.out.println("After deletion- " + sb);
    		System.out.println("Length of StringBuilder- " + sb.length());
    	}
    }

    Output

    After deletion- Hell
    Length of StringBuilder- 4

    Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/StringBuilder.html

    That’s all for the topic Java StringBuilder With Method Examples. If something is missing or you have something to share about the topic please write a comment.

    You may also like

    The post Java StringBuilder With Method Examples appeared first on KnpCode.

    Read for later

    Articles marked as Favorite are saved for later viewing.
    close
    • Show original
    • .
    • Share
    • .
    • Favorite
    • .
    • Email
    • .
    • Add Tags 

    Separate tags by commas
    To access this feature, please upgrade your account.
    Start your free month
    Free Preview