Object to string conversion in java

Explicit and Automatic String Conversion in Java

Data with other data types can be converted to String using explicit and automatic ways in Java. Explicit String conversion ways include:

  • Use of the toString() method of an object, especially wrapper classes.
  • Use of the static overloaded method String.valueOf, passing in the other data type value.
  • Use of a String constructor to convert a byte array as a String.

Automatic String conversion of other data type values happen when objects are used in the context of a String like:

  • An object or primitive passed as an argument to a println().
  • An object or primitive written as the second operand of the “+ operator” when the first operand is a String.
Читайте также:  Bbcode to html java

Code for examples

We will use the below variable declarations for our examples inside a class StringCheck:

public class StringCheck

public static void main(String[] args)

int i=10;

char[] myCharArray = < 'a', 'b', 'c' >;

int[] myIntArray=;

byte myByteArray[] = «abcd».getBytes();

//Code for each case will go here.

>

>

Use of the toString() method

The toString() method is part of the Object class that should return a String representation of the object and hence inherited by all classes in Java. It is recommended that all subclasses override this method. Invoking toString() on a null reference will cause NullPointerException to be thrown.

System.out.println(new Integer(i).toString());

System.out.println(new StringCheck().toString());

System.out.println(myCharArray.toString());

System.out.println(myIntArray.toString());

System.out.println(myByteArray.toString());

The toString() method is part of the Object class and hence inherited by all classes in Java, but not primitives. The wrapper classes provide a mechanism to «wrap» primitive values in an object so that the primitives can be included in activities only for objects. Hence we need to wrap our primitive inside the corresponding wrapper class and then call the toString() method. Wrapper classes in Java (Integer, Long, Float etc) have overridden this method to return the String representation of the primitive it holds. Read more about wrapper classes at http://javajee.com/wrapper-classes-auto-boxing-and-auto-unboxing.

Since we have not overridden toString for our class StringCheck, it uses the inherited default implementation in the Object class. The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash code of the object.

In case of Arrays, toString prints a symbol [ followed by an alphabet like C, B etc. denoting the type, followed by the at-sign character ‘@’, and the unsigned hexadecimal representation of the hash code of the object. It prints something like [C@9664a1 for char[] and [B@addbf1 for byte[]. Now let us see in detail what [C@9664a1 mean for an array.

  • The [ means array.
  • The C means char.
  • The @ separates the type from the ID.
  • The hex digits are an object ID or hashcode.

Below is a list of possible values for most types.

  • B — byte
  • C — char
  • D — double
  • F — float
  • I — int
  • J — long
  • S — short
  • Z — boolean
  • [ — one [ for every dimension of the array

Use of String.valueOf

The static overloaded method String.valueOf returns the string representation of the argument data.

String.valueOf() is overloaded for all the primitive types, char array and for the type Object.

For the primitive types, valueOf() returns the string representation of the of the value it contains.

For objects including arrays, but excluding char[], if the argument is null, then a string equal to «null»; otherwise, the value of obj.toString() is returned.

For char array, if the argument is null, then a NullPointerException is thrown; otherwise it will print the contents of the char array.

System.out.println(String.valueOf(i));

System.out.println(String.valueOf(new StringCheck()));

System.out.println(String.valueOf(myCharArray));

System.out.println(String.valueOf(myIntArray));

System.out.println(String.valueOf(myByteArray));

This will produce the output:

You can see that except for character arrays, everything is printed as is for toString(); for char arrays, the contents are printed instead.

Converting a byte array to String using String constructor

Using the String.valueOf or the toString method of object will work for primitives and wrappers, but not for objects and arrays. For most objects, we need to override the toString. We also saw that a char array contents are converted with String.valueOf.

We can convert a byte array contents to String using a String constructor as:

Note that toString is overridden for the String class.

You can also specify the charset for conversion using another overloaded String constructor:

System.out.println(new String(myByteArray, «UTF-8»).toString());

This can throw an UnsupportedEncodingException. To know more about charsets and endocings, refer to javajee.com/charset-and-encodings.

Automatic string conversion inside println method

Java converts any object into its string representation inside a println() by calling one of the overloaded versions of the String.valueOf() method.

System.out.println(i);

System.out.println(new StringCheck());

System.out.println(myCharArray);

System.out.println(myIntArray);

System.out.println(myByteArray);

Note that the output is exactly same as that of String.valueOf.

Automatic String conversion when using String concatenation operator +

Java doesn’t allow operator overloading yet, + is overloaded for class String. When you add a non-string operand such as an integer or char to a String, the non-string operand is converted to a string and string concatenation happens. String conversion using concatenation operator for object references, which include all array types, is defined as follows: If the reference is null, it is converted to the string «null». Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string «null» is used instead. The string concatenation operator + makes use of toString directly whereas println makes use of String.valueOf and gives special treatment to char arrays. StringBuffer.append() also gives special treatement for char[] through overloading.

System.out.println(«»+i);

System.out.println(«»+new StringCheck());

System.out.println(«»+myCharArray);

System.out.println(«»+myIntArray);

System.out.println(«»+myByteArray);

Note that the output is exactly same as that of toString() invocation.

Источник

Convert Object to String in Java

Convert Object to String in Java

  1. Convert Object to String Using the valueOf() Method in Java
  2. Convert Object to String Using the + Operator in Java
  3. Convert Object to String Using the toString() Method in Java
  4. Convert Object to String Using the toString() Method in Java
  5. Convert Object to String Using toString() Method in Java
  6. Convert Object to String Using the join() Method in Java

This tutorial introduces how to convert an object to a string in Java.

Convert Object to String Using the valueOf() Method in Java

The valueOf() method of the String class can convert an object to a string. See the example below.

public class SimpleTesting  public static void main(String[] args)   Object obj = "DelftStack Portal";  System.out.println("Object value: "+obj);  String str = String.valueOf(obj);  System.out.println("String value: "+str);  > > 
Object value: DelftStack Portal String value: DelftStack Portal 

Convert Object to String Using the + Operator in Java

In Java, the plus operator + concatenates any type value with the string and returns a resultant string. We can use it to convert an object to a string too. See the below example.

public class SimpleTesting  public static void main(String[] args)   Object obj = "DelftStack Portal";  System.out.println("Object value: "+obj);  String str = ""+obj;  System.out.println("String value: "+str);  > > 
Object value: DelftStack Portal String value: DelftStack Portal 

Convert Object to String Using the toString() Method in Java

The toString() method of the Object class converts any object to the string. See the below example.

public class SimpleTesting  public static void main(String[] args)   Object obj = "DelftStack Portal";  System.out.println("Object value: "+obj);  String str = obj.toString();  System.out.println("String value: "+str);  > > 
Object value: DelftStack Portal String value: DelftStack Portal 

Convert Object to String Using the toString() Method in Java

An object can be of any type. For example, if we have an integer object and want to get its string object, use the toString() method. See the example below.

public class SimpleTesting  public static void main(String[] args)   Integer iVal = 123;  System.out.println("Integer Object value: "+iVal);  String str = iVal.toString();  System.out.println("String value: "+str);  > > 

Convert Object to String Using toString() Method in Java

This example explains how to convert a user-defined object to a string using the toString() method. See the example below.

class Employee  String fName;  String lName;   public Employee(String fName, String lName)   this.fName = fName;  this.lName = lName;  >   public String getfName()   return fName;  >  public void setfName(String fName)   this.fName = fName;  >  public String getlName()   return lName;  >  public void setlName(String lName)   this.lName = lName;  >   @Override  public String toString()   return "Employee [fName=" + fName + ", lName=" + lName + "]";  >   public String getString()   return toString();  > >  public class SimpleTesting  public static void main(String[] args)   Employee employee = new Employee("Rohan","Mosac");  System.out.println(employee.getString());   > > 
Employee [fName=Rohan, lName=Mosac] 

Convert Object to String Using the join() Method in Java

Here, we convert an ArrayList object to a string by using the join() method. The join() method of the String class returns a string after joining them into a single String object. See the example below.

import java.util.ArrayList; import java.util.List; public class SimpleTesting  public static void main(String[] args)   ListString> list = new ArrayList<>();  list.add("Sun");  list.add("Moon");  list.add("Earth");  System.out.println("List object: "+list);  // list object to string  String str = String.join(",", list);  System.out.println("String: "+str);  > > 
List object: [Sun, Moon, Earth] String: Sun,Moon,Earth 

Related Article — Java Object

Related Article — Java String

Источник

Object to string conversion in java

Java Object to String Example: Converting StringBuilder

Let’s see the simple code to convert StringBuilder object to String in java.

String is: hello Reverse String is: olleh

Now you can write the code to check the palindrome string.

So, you can convert any Object to String in java using toString() or String.valueOf(object) methods.

Youtube

For Videos Join Our Youtube Channel: Join Now

Feedback

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью