Java Basics:String Methods-5

 

Java String isEmpty()

The Java String isEmpty() method checks whether the string is empty or not.

The syntax of the string isEmpty() method is:

string.isEmpty()

Here, string is an object of the String class.


isEmpty() Parameters

The isEmpty() method does not take any parameters.


isEmpty() Return Value

  • returns true if the string is empty (length is 0)
  • returns false if the string is not empty

Example: Java String isEmpty()

class Main {
  public static void main(String[] args) {

    String str1 = "Java Programming";
    String str2 = "";

    System.out.println(str1.isEmpty()); // false
    System.out.println(str2.isEmpty()); // true

  }
}

Note: A non-initialized string is not an empty string. If you use isEmpty() on a string that is not initialized, you will get an error.

Java String intern()

The Java String intern() method returns a canonical representation of the string object.

The syntax of the string intern() method is:

string.intern()

Here, string is an object of the String class.


intern() Parameters

The intern() method does not take any parameters.


intern() Return Value

  • returns a canonical representation of the string

What is Java String Interning?

The String interning ensures that all strings having the same contents use the same memory.

Suppose, we these two strings:

String str1 = "xyz";
String str2 = "xyz";

Since both str1 and str2 have the same contents, both these strings will share the same memory. Java automatically interns the string literals.

However, if you create strings with using the new keyword, these strings won't share the same memory. For example,

class Main {
  public static void main(String[] args) {

    String str1 = new String("xyz");
    String str2 = new String("xyz");


    System.out.println(str1 == str2); // false

  }
}

As you can see from this example, both str1 and str2 have the same content. However, they are not equal because they don't share the same memory.

In this case, you can manually use the intern() method so that the same memory is used for strings having the same content.


Example: Java String intern()

class Main {
  public static void main(String[] args) {

    String str1 = new String("xyz");
    String str2 = new String("xyz");

    // str1 and str2 doesn't share the same memory pool
    System.out.println(str1 == str2); // false

    // using the intern() method
    // now both str1 and str2 share the same memory pool
    str1 = str1.intern();
    str2 = str2.intern();

    System.out.println(str1 == str2); // true
  }
}

As you can see, both str1 and str2 have the same content, but they are not equal initially.

We then use the intern() method so that str1 and str2 use the same memory pool. After we use intern()str1 and str2 are equal.


______________________

Java String getBytes()

The Java String getBytes() method encodes the string into a sequence of bytes and stores it in a byte array.

The syntax of the String getBytes() method are:

string.getBytes()
string.getBytes(Charset charset)
string.getBytes(String charsetName)

Here, string is an object of the String class.

The getBytes() method returns a byte array.


1. getBytes() Without Any Parameters

If you do not pass any parameters, getBytes() encodes the string using the platform's default charset.

Example: getBytes() Without Any Parameters

import java.util.Arrays;

class Main {
  public static void main(String[] args) {

    String str = "Java";
    byte[] byteArray;

    // convert the string to a byte array
    // using platform's default charset
    byteArray = str.getBytes();
    System.out.println(Arrays.toString(byteArray));
  }
}

Output

[74, 97, 118, 97]

Note: We have used the Arrays class in the above example to print the byte array in a readable form. It has nothing to do with getBytes().


2. getBytes() With CharSet Parameter

Here are different CharSet available in java:

  • UTF-8 - Eight-bit UCS Transformation Format
  • UTF-16 - Sixteen-bit UCS Transformation Format
  • UTF-16BE - Sixteen-bit UCS Transformation Format, big-endian byte order
  • UTF-16LE - Sixteen-bit UCS Transformation Format, little-endian byte order
  • US-ASCII - Seven-bit ASCII
  • ISO-8859-1 - ISO Latin Alphabet No. 1

Example: getBytes() With CharSet Parameter

import java.util.Arrays;
import java.nio.charset.Charset;

class Main {
  public static void main(String[] args) {

    String str = "Java";
    byte[] byteArray;

    // using UTF-8 for encoding
    byteArray = str.getBytes(Charset.forName("UTF-8"));
    System.out.println(Arrays.toString(byteArray));

    // using UTF-16 for encoding
    byteArray = str.getBytes(Charset.forName("UTF-16"));
    System.out.println(Arrays.toString(byteArray));
  }
}

Output

[74, 97, 118, 97]
[-2, -1, 0, 74, 0, 97, 0, 118, 0, 97]

Note: In the above program, we have imported java.nio.charset.Charset to use CharSet. And, we have imported the Arrays class to print the byte array in a readable form.


3. getBytes() With String Parameter

You can also specify the encoding type to getBytes() using strings. When you use getBytes() in this way, you must wrap the code inside try...catch block.

Example: getBytes() With String Parameter

import java.util.Arrays;

class Main {
  public static void main(String[] args) {

    String str = "Java";
    byte[] byteArray;

    try {
      byteArray = str.getBytes("UTF-8");
      System.out.println(Arrays.toString(byteArray));

      byteArray = str.getBytes("UTF-16");
      System.out.println(Arrays.toString(byteArray));

      // wrong encoding
      // throws an exception
      byteArray = str.getBytes("UTF-34");
      System.out.println(Arrays.toString(byteArray));

    } catch (Exception e) {
      System.out.println(e + " encoding is wrong");
    }

  }
}

Output

[74, 97, 118, 97]
[-2, -1, 0, 74, 0, 97, 0, 118, 0, 97]
java.io.UnsupportedEncodingException: UTF-34 encoding is wrong

Note: We have imported java.util.Arrays to print the byte array in a readable form. It has nothing to do with getBytes().

Java String contentEquals()

The Java String contentEquals() method checks whether the contents of the String is equal to the specified charSequence/StringBuffer or not.The syntax of the string contentEquals() method is:

string.contentEquals(StringBuffer sb)
string.contentEquals(charSequence cs)

Here, string is an object of the String class.


contentEquals() Parameters

The contentEquals() method takes a single parameter.

  • either StringBuffer or charSequence

Note: You can pass any class that implements charSequence to the contentEquals() method. For example: StringStringBufferCharBuffer etc.


contentEquals() Return Value

  • Returns true if the string contains the same sequence of characters as the specified parameter. If not, returns false.

Example: Java String contentEquals()

class Main {
  public static void main(String[] args) {
    String str = "Java";

    String str1 = "Java";
    StringBuffer sb1 = new StringBuffer("Java");
    CharSequence cs1 = "Java";

    String str2 = "JavA";
    StringBuffer sb2 = new StringBuffer("JavA");
    CharSequence cs2 = "JavA";

    System.out.println(str.contentEquals(str1)); // true
    System.out.println(str.contentEquals(sb1)); // true
    System.out.println(str.contentEquals(cs1)); // true

    System.out.println(str.contentEquals(str2)); // false
    System.out.println(str.contentEquals(sb2)); // false
    System.out.println(str.contentEquals(cs2)); // false
  }
}

Java String equals() Vs contentEquals()

The Java String equals() method not only compares the content, but also checks if the other object is an instance of String. However, contentEquals() only compares the content. For example,

class Main {
  public static void main(String[] args) {
    String str1 = "Java";
    StringBuffer sb1 = new StringBuffer("Java");

    System.out.println(str1.equals(sb1)); // false
    System.out.println(str1.contentEquals(sb1)); // true
  }
}

Here, both str1 and sb1 have the same content but they are instance of different objects. Hence, str1.equals(sb1) returns false and str1.contentEquals(sb1) returns true.


Comments

Popular posts from this blog

Java OOPS:OOPS Concepts Overview

Selenium-Java Contents

Java OOPS:Constructors in Java – A complete study!!