Implementing ToString Method
Implementing ToString Method
method. The java toString() method is used when we need a string representation of an
object. It is defined in Object class. This method can be overridden to customize
the String representation of the Object. Below is a programshowing the use of the Object’s
Default toString java method.
class PointCoordinates {
private int x, y;
public PointCoordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
Download ToStringDemo.java
In the above example when we try printing PointCoordinates object, it internally calls the
Object’s toString() method as we have not overridden the java toString() method. Since out
example has no toString method, the default one in Object is used. The format of the
default toString method of the Object is as shown below.
Class Name, “@”, and the hex version of the object’s hashcode concatenated into a string.
The default hashCode method in Object is typically implemented by converting
the memory address of the object into an integer.
Below is an example shown of the same program by Overriding the default Object toString()
method. The toString() method must be descriptive and should generally cover all the
contents of the object.
class PointCoordinates {
private int x, y;
public PointCoordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
// Custom toString() Method.
public String toString() {
return "X=" + x + " " + "Y=" + y;
}
}
Download ToStringDemo2.java
Autoboxing is the automatic conversion that the Java compiler makes between the
primitive types and their corresponding object wrapper classes. For example,
converting an int to an Integer, a double to a Double, and so on. If the conversion
goes the other way, this is called unboxing.
The rest of the examples in this section use generics. If you are not yet familiar with
the syntax of generics, see the Generics (Updated) lesson.
Although you add the int values as primitive types, rather than Integer objects, to li,
the code compiles. Because li is a list of Integerobjects, not a list of int values, you
may wonder why the Java compiler does not issue a compile-time error. The compiler
does not generate an error because it creates an Integer object from i and adds the
object to li. Thus, the compiler converts the previous code to the following at
runtime:
List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
li.add(new Integer.valueOf(i));
Converting a primitive value (an int, for example) into an object of the corresponding
wrapper class (Integer) is called autoboxing. The Java compiler applies autoboxing
when a primitive value is:
Because the remainder (%) and unary plus (+=) operators do not apply
to Integer objects, you may wonder why the Java compiler compiles the method
without issuing any errors. The compiler does not generate an error because it invokes
the intValue method to convert an Integer to anint at runtime:
public static int sumEven(List<Integer> li) {
int sum = 0;
for (Integer i : li)
if (i.intValue() % 2 == 0)
sum += i.intValue();
return sum;
}
Autoboxing and unboxing lets developers write cleaner code, making it easier to read.
The following table lists the primitive types and their corresponding wrapper classes,
which are used by the Java compiler for autoboxing and unboxing:
There is a wrapper class for every primitive date type in Java. This class encapsulates a single value for
the primitive data type. For instance the wrapper class for int is Integer, for float is Float, and so on.
Remember that the primitive name is simply the lowercase name of the wrapper except for char, which
maps to Character, and int, which maps to Integer.
The wrapper classes in the Java API serve two primary purposes:
To provide a mechanism to “wrap” primitive values in an object so that the primitives can be
included in activities reserved for objects, like as being added to Collections, or returned from a
method with an object return value.
To provide an assortment of utility functions for primitives. Most of these functions are related to
various conversions: converting primitives to and from String objects, and converting primitives
and String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.
The wrapper object of a wrapper class can be created in one of two ways: by instantiating the wrapper
class with the new operator or by invoking a static method on the wrapper class. We will explore this
further in this article.
Creating Wrapper Objects with the new Operator
Before we can instantiate a wrapper class, we need to know its name and the arguments its constructor
accepts. The name of the wrapper class corresponding to each primitive data type, along with the
arguments its constructor accepts, is listed below:
All the wrapper classes are declared final. That means you cannot derive a subclass from any of them.All
the wrapper classes except Boolean and Character are subclasses of an abstract class called Number,
whereas Boolean and Character are derived directly from the Object class.All of the wrapper classes
except Character provide two constructors: one that takes a primitive of the type being constructed, and
one that takes a String representation of the type being constructed—for example,
Code:
The value may also be passed as a variable, as shown in the following example:
Code:
Note that there is no way to modify a wrapped value—that is, the wrapped values are immutable. To
wrap another value, you need to create another object.
All wrapper classes offers static valueOf() methods which give you another approach to creating wrapper
objects. Because it's a static method, it can be invoked directly on the class (without instantiating it), and
will return the corresponding object that is wrapping what you passed in as an argument.
Both methods take a String representation of the appropriate type of primitive as their first argument, the
second method (when provided) takes an additional argument, int radix, which indicates in what base
(for example binary, octal, or hexadecimal) the first argument is represented—for example,
Code:
or
Code:
A storage capability without the corresponding retrieval capability is not of much use. Once you store a
primitive in a wrapper object, often you will want to retrieve the stored primitive at a later time.
xxxValue() method
When you need to convert the value of a wrapped numeric to a primitive, use one of the many
xxxValue() methods. All of the methods in this family are no-arg methods. Each of the six numeric
wrapper classes has six methods, so that any numeric wrapper can be converted to any primitive numeric
type.
Code:
or
Code:
If you do not need to store a value in a wrapper but just want to perform a quick operation on it, such as
converting the type, you can do it by using an appropriate static method of the appropriate wrapper
class. For example, all the wrapper classes except Character offer a static method that has the following
signature:
The <type> may be any of the primitive types except char (byte, short, int, long, float, double, or
boolean), and the <Type> is the same as <type> with the first letter uppercased; for example:
Each of these methods parses the string passed in as a parameter and returns the corresponding
primitive type.
For example, consider the following code:
Code:
String s = "123";
int i = Integer.parseInt(s);
The second line will assign an int value of 123 to the int variable i.
The six parseXxx() methods (one for each numeric wrapper type) are closely related to the valueOf()
method that exists in all of the numeric wrapper classes (plus Boolean). Both parseXxx() and valueOf()
take a String as an argument, throw a NumberFormatException if the String argument is not properly
formed, and can convert String objects from different bases (radix), when the underlying primitive type is
any of the four integer types.
Code:
The next examples involve using the radix argument, (in this case binary):
Code:
The class Object, the super class of all classes, has a toString() method. Since we know that all other
Java classes inherit from class Object, we also know that all other Java classes have a toString() method.
The idea of the toString() method is to allow you to get some meaningful representation of a given
object. For instance, if you have a Collection of various types of objects, you can loop through the
Collection and print out some sort of meaningful representation of each object using the toString()
method, which is guaranteed to be in every class. All of the wrapper classes have a no-arg, nonstatic,
instance version of toString(). This method returns a String with the value of the primitive wrapped in the
object—for instance,
Code:
All of the numeric wrapper classes provide an overloaded, static toString() method that takes a primitive
numeric of the appropriate type (Double.toString() takes a double, Long.toString() takes a long, etc.),
and, of course, returns a String with that primitive’s value—for example,
Code:
Finally, Integer and Long provide a third toString() method. It is static, its first argument is the
appropriate primitive, and its second argument is a radix. The radix argument tells the method to take
the first argument (which is radix 10 or base 10 by default), and convert it to the radix provided, then
return the result as a String—for instance,
Code:
The Integer and Long wrapper classes let you convert numbers in base 10 to other bases. These
conversion methods, toXxxString(), take an int or long, and return a String representation of the
converted number, for example,
Code:
2 {
4 {
5 System.out.println("Integer range:");
8 System.out.println("Double range:");
11 System.out.println("Long range:");
14 System.out.println("Short range:");
17 System.out.println("Byte range:");
20 System.out.println("Float range:");
23 }
24 }
Integer range:
min: -2147483648
max: 2147483647
Double range:
min: 4.9E-324
max: 1.7976931348623157E308
Long range:
min: -9223372036854775808
max: 9223372036854775807
Short range:
min: -32768
max: 32767
Byte range:
min: -128
max: 127
Float range:
min: 1.4E-45
max: 3.4028235E38
class Point
{
int x, y;
}
class FinalClassDemo
{
public static void main(String args[])
{
Colored3dPoint cObj = new Colored3dPoint();
cObj.z = 10;
cObj.color = 1;
cObj.x = 5;
cObj.y = 8
Output
x=5
y=8
z = 10
Color = 1