Wednesday, 29 April 2020

Convert CharSequence to String

Approach 1 : Using toString() method.
charSequence.toString()

Approach 2: Using String.valueOf()
String.valueOf(charSequence);

Approach 3: Using StringBuilder.
StringBuilder builder = new StringBuilder();
String result = builder.append(charSequence).toString();

Find the below working application.

App.java
package com.sample.app;

public class App {

 private static String getString_approach1(CharSequence charSequence) {
  if (charSequence == null) {
   return null;
  }
  return charSequence.toString();
 }

 private static String getString_approach2(CharSequence charSequence) {
  if (charSequence == null) {
   return null;
  }
  return String.valueOf(charSequence);
 }

 private static String getString_approach3(CharSequence charSequence) {

  if (charSequence == null) {
   return null;
  }

  StringBuilder builder = new StringBuilder();
  String result = builder.append(charSequence).toString();
  return result;
 }

 public static void main(String args[]) {
  CharSequence charSequence = "Hello World";

  String str1 = getString_approach1(charSequence);
  String str2 = getString_approach2(charSequence);
  String str3 = getString_approach3(charSequence);

  System.out.println("str1 : " + str1);
  System.out.println("str2 : " + str2);
  System.out.println("str3 : " + str3);
 }

}

Output
str1 : Hello World
str2 : Hello World
str3 : Hello World



You may like

No comments:

Post a Comment