Home Java Java-conversion Convert Object To String
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Convert Object To String

Advertisement
In this section, you will learn to convert an object to a string.

Convert Object To String

     

In this section, you will learn to convert an object to a string. Object is a class of java.lang package.

Code Description:

This program helps you in converting an object type data into a string type data. The toString() method returns a string representation of the object. So, we get the an object type data is 10 and this program converts into a string type data as a '10'. 

Here is the code of this program:

import java.io.*;
import java.lang.*;

public class ObjectToString{
  public static void main(String[] args) {
  Object obj = 10;
  String s = obj.toString();
  System.out.println("String value is: = " + s);
  }
}

 Download of this program:

Output of this program given below.

C:\corejava>java ObjectToString
String value is:=10
C:\corejava>
_
Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 5, 2007

Ask Questions?    Discuss: Convert Object To String   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
lalarargh
April 17, 2012
help

I'v done this with a program recently in hope that I could convert an Object into a String and then compare 2 String type variables in an if statement, but for whatever reason the variable that was originally an Object (but now a String) is not being picked up eg cpuChoice = objectChoice.toString(); if((playerChoice.equalsIgnoreCase("Rock")&&(cpuChoice.equals("Rock"))){ System.out.println("the game is a tie"); } etc etc however if I force cpuChoice to "Rock" then the if statement works perfectly, any ideas?
Dan
December 4, 2012
This didn't work for me.

String str=o.toString(); System.out.println(str+" is found at index "+search(arr, o)+".");} My "o" is "hello". The search method will return "2". My output is: [Ljava.lang.String;@19189e1 is found at index 2.
DMCA.com