toString 1 « toString « Java Class Q&A

Java Class Q&A
1.abstract class
2.Base class
3.class hierarchy
4.class name
5.class version
14.equal method
15.extend Class
19.inner class
21.main class
26.object reference
28.parent class
31.Private Field
35.Static Class
39.Wrapper Class
Java Class Q&A » toString » toString 1 

1. Why can't I call toString() on a Java primitive?

I want to convert a primitive to a string, and I tried:

This fails with the error:
int cannot be dereferenced
Now, I get that primitives are not reference types (ie, not an Object) ...

2. How to convert string result of enum with overridden toString() back to enum?

Given the following java enum:

public enum AgeRange {

   A18TO23 {
     public String toString() {        

3. Explicit vs implicit call of toString

I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception. For ...

4. Automatic .toString() when calling a method?

I got the code of a former employee. There are many calls to methods like:

void foo(String s,...) {
and val is an int. Of course, I get an error. As a ...

5. (String) or .toString()?

Actually, this question has no big meaning, I guess. The situation is: I have a method with an "Object o" parameter. In this method, I exactly know there is a string in "o" ...

6. Stacktrace to string in Java

Easiest way to convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace?

7. toString() in Java

A lead developer on my project has taken to referring to the project's toString() implementations as "pure cruft" and is looking to remove them from the code base. I've said that doing ...

8. Do any Java libraries use annotations for code generation?

Is anyone aware of a library that uses the the techniques (annotations and classworking) described in this article for automatically generating the standard Object methods toString(), equals() and hashcode() ...

9. C++ equivalent of java.toString?

I'd like to control what is written to a stream, i.e. cout, for an object of a custom class. Is that possible in C++? In Java you could overwride the toString() ...

10. how to use the toString() method for multiple enum members in same class in Java

I am trying to add more user friendly descriptions for multiple enum members in the same class. Right now I just have each enum returned in lowercase:

public enum Part {

11. unboxing or toString() is used in sysout in java

We know that when we use objects in sysout(System.out.Println) statement internally it's toString method is called. and with primitive it directly prints. but when we use any Wrapper class type of ...

12. In Java, how do I get the value of an enum inside the enum itself?

I want to override toString() for my enum, Color. However, I can't figure out how to get the value of an instance of Color inside the Color enum. Is there a ...

13. when to use toString() method

This may sound very basic... can someone please explain the use of the toString() method and when to effectively use this? Have done a search on google but could not find any ...

14. Java - How to convert a Color.toString() into a Color?

In order to save Color attributes of a graphical object in my application, I saved the string representation of this Color in a data file. For instance, for red I save: ...

15. Auto-generating toString Method

Is it good or bad practice auto-generating toString methods for some simple classes? I was thinking of generating something like bellow where it takes the variable names and produces a toString method ...

16. toString() Method question

I've been working on this assignemnt here's code:

public class Student
 private String fname;
 private String lname;
 private String studentId;
 private double gpa;

 public Student(String studentFname,String studentLname,String stuId,double studentGpa)

18. why toString method does not work here?

Hi this is my whole class ,I have added number 2 to the doubly linked list and then I want it to be be print in the concole but it will show ...

19. Java Language Design with toString

We did they make the decision to not implement a toString method for int[] but instead let it inherent the toString method from Object?

20. Integer.toString()

Why does the Integer.toString() method is implemented using String.valueOf(int i) instead of using directly static method Integer.toString(int i) which is called back by String.valueOf(int i) ? Update: I am working with a ...

21. Integer.toString(int i) vs String.valueOf(int i)

I am wondering why the method String.valueOf(int i) exists ? I am using this method to convert int into String and just discovered the Integer.toString(int i) method. After looking the implementation of ...

22. (string) and .toString and other typecasting why is it needed?

may i know why is there .toString() when you can use (String) instead? and vice versa and also for numbers can use the wrapper class's so why do we need to ...

23. How do I use System.getProperty("line.separator").toString()?

I have a Tab-delimited String (representing a table) that is passed to my method. When I print it to the command line, it appears like a table with rows: The ...

24. Provide Programmatic Access to All Data Available in String Form: toString()

Bloch said: Provide Programmatic Access to All Data Available in String Form. I am wondering if he means to override toString() which should involve 'all data available'? I think the 'in string form' ...

25. Why is myEnum.ONE not equal to myEnum.ONE.toString()?

I've got the following enum:

public enum myEnum {
    ONE("ONE"), TWO("TWO");

    private String name;

    private myEnum(String name) {

26. How to use the toString method in Java?

Can anybody explain to me the concept of the toString() method? How is it used, and what is its purpose?

27. Add an empty string vs toString - why is it bad?

According to the tool PMD, the following is a bad practice:

String s = "" + 123; // bad 
String t = Integer.toString(456); // ok 

This is an inefficient way to convert ...

28. Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

I would like an efficient utility to generate Unique sequences of bytes. UUID is a good candidate but UUID.randomUUID().toString() generates stuff like 44e128a5-ac7a-4c9a-be4c-224b6bf81b20 which is good as long as you don't ...

29. Java int to String - Integer.toString(i) vs new Integer(i).toString()

Sometimes java puzzles me... I have a huge amount of "int" initializations to make. What's the "real" difference?

  1. Integer.toString(i)
  2. new Integer(i).toString()

30. Im working on this code and expecting a matrix but thats what came up...Matrix@2c78bc3b Matrix@2a8ddc4c

public class Matrix

    public static int rows;
    public static int colms;//columns
    public static int[][] numbers;

    public Matrix(int[][] numbers)

31. Java: Is the method Interger.toString() better than adding empty string to interger type value?

Possible Duplicate:
Is conversion to String using (“” + <int value>) bad practice?
Hi there, I am testing some Java codes with PMD rules. One of the ...

32. Where is Short.toString(short s, int radix)?

Short.parseShort(String s, int radix) exists, as does Integer.parseInt(String s, int radix) and Long.parseLong(String s, int radix). Integer.toString(int i, int radix) and Long.toString(long l, int radix) exist. Short.toString(short s), Integer.toString(int i) and Long.toString(long l) ...

33. What time zone does Date.toString() display?

By default, what time zone does method java.util.Date.toString() display? Since a Java Date stores a given date in UTC and doesn't contain any explicit ...

34. Simple if statement problem

I am trying to return a toString if something is true. I have this code:

    public void printoutsailings() {
    for (Sailing s:sailings) {

35. JVMTI _jclass toString

How to get the name of the JVM TI _jclass? I want to display names of classes loaded in the JVMTI agent, however it is not obvious to me how to get ...

36. What is the nicest toString builder class you have used or seen ? What made it nice

Lets face it writing nice toString messages is a boring messy chore that needs to be done as it can really be helpful for insepection in a debugger or logging. What features ...

37. Equivilent of Java's toString() for Clojure functions

some Java code I'm using invokes toString() on my Clojure function objects, which return something like #<ns$something something.something$something@7ce1eae7>>- I want to return something else...presumably there's a way to include some metadata ...

38. Having trouble with a toString() method

I am making a program that keeps up with hot dog stands and sells hotdogs. This program is composed of two files, the first one I got to work fine ...

39. toString method

I want to add a toString method in the Item class that returns the title of the item in there. I have need make sure that the toString method in the ...

40. toString method

Possible Duplicate:
toString method
I have been asked to change the print method into a toString method that displays the exact same information when called. I'm ...

41. Java - toString to Colour

I have been trying to work this out all day. Basically I have made a for loop which adds entries into an arraylist. One of the entries is a "Colour" varible. I ...

42. toString method in Java

Why the time is shown not in normal (readable) way? Method toString is missing?

import java.util.Calendar;

abstract class Calender {

    abstract void showTime();

    void time() {

43. Java numbers with radix > Character.MAX_RADIX

I have a five-character String and I want to use those five characters as an ASCII-encoded (printable) number. The simplest way to achieve this is to use

Long.toString(number, Character.MAX_RADIX);
This will give me ...

44. Returning a toString from a StringBuffer

This is my class:

    public String toString(){
    status = status1.getStat();
    item = status1.getItem();
    boolean checked;
    checked ...

45. BST toString in linear time

how can i write a linear-time toString() method for BST that uses StringBuilder? i just want to know how to start atleast

46. How is Set.toString() implemented?

The toString method is not overridden in Set or its hierarchy, so how are the elements printed?

import java.lang.Math;
import java.util.HashSet;
class Hello{

public String name= ""; 

Hello(String name){ = name; ...

47. how does Float.toString() and Integer.toString() works?

How can i implement an algorithm to convert float or int to string? I found one link but i cant understand the algorithm given there

48. How to get system (BlueJ) to allocate unique number sequentially

/**File class */

public class File {
   // The File name.       
   private String name;
   // The date file ...

49. How to call a super method (ie: toString()) from outside a derived class

existantial question if i have a class hierarchy like:

public class TestSuper {
    public static class A {

50. Java negative BigInteger toString

It seems I have a two's complement issue with Java's BigInteger. I have a 64-bit integer where only the msb and the second msb are set to 1, the rest is ...

51. why is toString() returning a "/" to my String path?

I have a toString() method that is returning a "/" at the beginning of the String, which is a filepath. this is seriously screwing up my program because it's not able ...

52. Cannot make a static reference to the non-static method tostring() from the type Box

This is my

public class Box{ 
  private int height, width, length;

  public void setLength(int il) {
    length = il;
  public void setWidth(int iw) {

53. Detect if javascript is compressed with YIU compressor in Javascript

edit: IMPORTANT: I'LL GIVE UP,USE ANOTHER METHOD TO CHECK COMPRESSION * THIS TOPIC IS CLOSED *I have made a construction to defer loading javascript to speed up page loading. To deploy ...

54. why does toString method in java doesn't seem to work?

I want to convert a character array to a string object using the toString() method in java. following is the snippet of the test code I used

import java.util.Arrays;
class toString{

55. Why does sysout(upper class) invoke toString of lower class after assigning lower class to upper class?

I have two classes A and B while B is a subtype of A:

public class A {
    private String stringVar;

    public A()  {

56. Difference between Long.toString(i) vs i + ""

we often come across a scenario where in we need to pass a String representation of a primitive and More often then not we use

  WrapperClass.toString() ;
and sometimes we usually ...

57. Write toString() once and for all?

I want to have all of my classes implement toString() the same way using Java reflection. There are two ways I came up with.

  1. Create a base class such as MyObject overriding ...

58. Which toString technique is more efficient?

I have a class called Zebra (not her actual name). Zebra overrides the toString method to provide her own convoluted obfuscated stringification. Which is more efficient to stringify an instance of Zebra? ...

59. changing the toString Method

I was recently asked to rewrite a class that used inheritance, to a class that used composition instead. I ran into a problem when I was rewriting the toString() method; the ...

60. java toString() returning this

In String toString() method returns this and when i pass it System.out.println() it prints the content of the String. It is confusing for me how is that happening. can comeone explain ...

61. toString() method for FORMULA class

Hi all, In my current project there is a class defined as: public class APPLIEDRATES { .... ... public static final class FORMULA extends LinkedHashMap> { private static final long serialVersionUID = -4754565974505570612L; private FORMULA () {super(10);} } -- -- public static final class LHSRATE{} public static final class RHSRATE{} } Please help me write toString() method for FORMULA class. ...

62. char[].toString() VS new String(char[])

I think this falls into the "Oh, that would be cute!" category. If char[] overrode toString() to return "new String(this)," it would be the only array class to do so. Every other array class simply uses the version of toString() inherited from Object. It would be cute, indeed, but the way it's done now is actually more consistent.

63. Difference between String casting and toString () method

If you warranty that the Object is a String, then I prefer to do the cast rather than calling toString() method. The reason is that if the object is null, then casting the object to String would give null as well, but trying to call the toString() method on a null String will throw a NullpointerException

64. Interesting Anomaly with toString() vs. Memory Address

It seems I heard about this whole object and toString() business when I learned Java, but this is over my head. I am testing this code: import java.util.*; public class DateTest { public static void main(String[] args) { System.out.println("Date = " + new Date()); } } Seems straight forward enough. When I first found this, I compiled and ran from my ...

65. toString() function

Actually toString() resides in the Object class and thus is accessible to all other classes that extend Object. toString() is an object's way of saying this is my human readable string format (in most cases). You can override the toString() function to give your object a meaningful representation when you try to print it to a console or elsewhere. System.out.println() uses ...

67. about toString method

package pack; import java.util.*; import*; public class Samp { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(; int n = 0; try { System.out.print("Enter the Number of records :"); n = Integer.parseInt(br.readLine()); ArrayList al = new ArrayList(); Employee e = null; for (int i = 0; i < n; i++) { System.out.print("Enter the Name:"); ...

68. toString problem

well i wrote this code public static void displayResults(JTextArea area,Room[] rooms,int length) { JFrame bigTextArea = new JFrame("College Rooms"); bigTextArea.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); bigTextArea.setSize(240,400); bigTextArea.getContentPane().add(area, BorderLayout.WEST); area.setEditable(false); area.append("Rooms Unsorted"+"\n"+"\n"); for ( int i = 0; i < length; i++ ) { area.append(rooms[i]+"\n"); } selectionSort(rooms,length) ;// Sorting the rooms JTextArea area2 = new JTextArea(); bigTextArea.getContentPane().add(area2, BorderLayout.EAST); area2.setEditable(false); area2.append("Rooms sorted"+"\n"+"\n"); for ( int j = 0; ...

69. how to add tostring

I don't know how to use tostring in my program import cs1.Keyboard; public class MoveCat { private int width; private int length; private int height; public int getwidth () { System.out.print("Enter the cat width: "); //determine the distance will travel in length width = Keyboard.readInt(); while ((width <= -10) | | (width >= 10)) { System.out.print("Not right try again ...

70. Integer.toString.......

Hi folks, just look at the following code and help me out in getting the right output for the program. I am a newbie and learning. I am not able to get the input number as output.... Thanks Ram // import*; public class Largest { public static void main( String args[] ) throws IOException { int count = 0, ...

71. Can't Get This toString Method Overridden. Why?

I'm trying to get the default toString method overridden by my version. However, it's not even getting called by main. Why? Do all overridding methods have to be public? I can't make it public since the driving class containing main (is in the same file) and must be public. Any help would be deeply appreciated. Here's the code: import java.util.Vector; class ...

72. Using toString() Method

This is a homework question and I am almost done with it. but I am a little Stuck. This is what we had to do: Develop a class that represents a data set. Use a Vector inside the class to hold the Integers. Provide the folling public methods addData() clearData() count() sum() toString() Create a driver program to test your DataSet ...

73. Converting int to string W/OUT toString, etc.

Ok. Here is the idea. We are to make a main method that calls upon a method (that accepts an int and returns a string). The method cannot use simple methods such as toString or the such-- we have to do the conversion 'manually'. Well, I had it 'semi-working'. The program would take the int, return the ASCII code equivalent ('0' ...

74. How to overrule the toString method.

Hi, For debugging purpose, I want to display the references of objects. However, some of this objects have overload the toString method. As a result I get : "Value : 1 Date : 12/02/02" instead of "Toto@1323b930". I know it is possible to get the references of the object but I can't remember how. Any help would be appreciate. W.

75. toString question

76. toString() Method vs. Casting

77. List interface and toString( ) method

The List interface does not specify a toString( ) method, and neither does the Collection interface (the only other interface that List implements). Yet I am able to call this method on an object declared as a List. For example: List myList; ... (assigns some object to myList) String s = myList.toString(); Of course I know that Object implements toString, and ...

78. using toString()

79. problem with toString() in Sun ONE Studio 4, update 1

The original BookOrder class did not have any methods, or variables, to handle dates(I'm working out of Murach's "Beginning Java 2"). The assignment was to add these things, including the "Date: " + date + "\n\n" line to the toString() method. The resulting code is almost exactly like the example given in the book, yet when the main class calls toString(), ...

80. Class toString

81. StringBuffer toString method

Hi all, I am working through the Java Tutorial third edition and one of the exercises is to write a program that computes your initials from your full name and displays them. I set the app up to accept the full name from the command line. My thought was to first append the first letter of the string to a StringBuffer ...

82. about "toString"

The 'toString' method is inherited by all classes, and is originally defined in the Object class (the super parent of all objects/classes). The toString() method needs to be over-ridden (this means to replace the super-classes method definition with your own - just like when you write an applet, you over-ride the init(), start(), and paint() methods with methods to do something ...

83. Using toString().......

// Override toString() for Box Class class Box { double width; double height; double depth; Box (double w, double h, double d) { width = w; height = h; depth = d; } public String toString() { return "Dimensions are " + width + " by " + depth + " by " + height + "."; } } class toStringDemo ...

84. toString()

hey Kieran, welcome to the ranch, You will get lots of help here, but a wee suggestion, this makes it easier for people to read you code; use the code button below the add reply button, and place your code between this, then it looks more like code with the indentation. also, most people might not know what you are doing, ...

85. toString() problem

A Java String is an object. For our purposes, an object is a location in your computer's memory containing some data. You create an object using the "new" operator. Now, of course, it's possible to have two locations containing the characters t,e,s,t. In your program, there's one that Java gives you for free because you used the token "test" in your ...

86. Should toString() return a null ?

Java is smart enough that whenever you don't create a toString() method that when you instantiate an object in your main method and you want it to return something, you don't have to type in SOP(test.toString) you just have to type SOP(test) (test being the new object to the class). In order for it to return null you would have to ...

87. "toString()" question

Hello all, Here's another question from majji's that i've messed up with... Question 9 The following code will give 1: Byte b1 = new Byte("127"); 2: 3: if(b1.toString() == b1.toString()) 4: System.out.println("True"); 5: else 6: System.out.println("False"); A) Compilation error, toString() is not avialable for Byte. B) Prints "True". C) Prints "False". The answer is "C" thinking is that,the addresss of "b1" ...

88. toString() method

89. toString Clarification

90. toString()

toString() is a method available on all objects, so we have to get an object of some sort into your statement. It might be tempting to try int i = 5; String s = i.toString(); but "int" is a primitive type, not an object so that won't compile. Here's an option ... make an object instance of class Integer, which is ...

91. when to use "new"? (about Inetger.toString() )

I'm coding on GUI and wondering when to "new" sth: /* create and label 9 buttons */ for (int i = 0 ; i < 9 ; i++) { button[i] = new Button() ; button[i].setLabel(new Integer.toString(i+1)) ; } In the last line, I assume that I should "new" an Integer object and then use its toString() method to convert the "i+1" ...

92. Problem Using toString method from a different class

Hi, I can not get the toString method to work from another class. // First Class Separate file public class MyClass1 { private long num1; private double num2; public MyClass1 (long num1, double num2) throws OneException, AnotherException { // Some Code Here... } // Override the toString() method public String toString() { return "Number 1: " + num1+ " Number ...

93. Problems overwriting toString() method.

my assignment is to create a deck class that holds 52 cards in it which obtain their values from a Card class that I wrote earlier. I am supposed to overwrite the toString method of java with one of my ownt that prints out a string with all 52 cards represented not by their numeric values as they are in my ...

94. Enumerated type toString()

Say you have an enumerated type whose members are basic color names (RED, BLUE, YELLOW, GREEN, etc). You do some bitwise arithmatic on vars of that type, resulting in a value that is constrained by the nature of the operations to always still be a member of that type. Is there any direct way to translate that new value into the ...

95. toString() method overloading

dear friends i have created 3 java files 1) Employee 2) Nameof_emp 3) Emploeetest which has main method my problem is how should i overload tostring method of Nameof_emp to get full name of person Here is Employee class package My_emp_project; public class Employee { private Nameof_emp name; private double in_time; private double out_time; private double work_h; public Employee(String s1, String ...

96. toString() method invoked

The code below works fine i am not clear about one point is that how the toString() method (line 35) is invoked when it is not called can anyone explain... 1. package test; 2. 3. class Book1 4. { 5. private String title; 6. private String author; 7. 8. Book1() 9. { 10. this("unknown", "unknown"); 11. } 12 13. Book1(String title, ...

97. toString()

98. regarding toString()

99. problem using toString()

100. toString or String.valueOf()

I have declared the following values as int and double but my problem is that Ive created an array which returns a string which means since Prefnum is declared as an int then it will have to be converted to a string, now do I used String.valueOf or toString to convert so I can print out these values as strings? The ...  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.