0% found this document useful (0 votes)
90 views13 pages

Implementing ToString Method

The document discusses Java wrapper classes and autoboxing/unboxing. It explains that wrapper classes allow primitive types to be used as objects by encapsulating primitive values. The key wrapper classes are Boolean, Byte, Character, Float, Integer, Long, and Short. Autoboxing converts primitives to wrapper objects automatically, while unboxing converts wrapper objects to primitives. This allows cleaner code when passing primitives to methods expecting objects and vice versa.

Uploaded by

riya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
90 views13 pages

Implementing ToString Method

The document discusses Java wrapper classes and autoboxing/unboxing. It explains that wrapper classes allow primitive types to be used as objects by encapsulating primitive values. The key wrapper classes are Boolean, Byte, Character, Float, Integer, Long, and Short. Autoboxing converts primitives to wrapper objects automatically, while unboxing converts wrapper objects to primitives. This allows cleaner code when passing primitives to methods expecting objects and vice versa.

Uploaded by

riya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 13

Implementing toString method in java is done by overriding the Object’s toString

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;
}
}

public class ToStringDemo {

public static void main(String args[]) {


PointCoordinates point = new PointCoordinates(10, 10);
// using the Default Object.toString() Method
System.out.println("Object toString() method : " + point);
// implicitly call toString() on object as part of string concatenation
String s = point + " testing";
System.out.println(s);
}
}

Download ToStringDemo.java

When you run the ToStringDemo program, the output is:


Object toString() method : PointCoordinates@119c082
PointCoordinates@119c082 testing

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;
}
}

public class ToStringDemo2 {

public static void main(String args[]) {


PointCoordinates point = new PointCoordinates(10, 10);
System.out.println(point);
String s = point + " testing";
System.out.println(s);
}
}

Download ToStringDemo2.java

When you run the ToStringDemo2 program, the output is:


X=10 Y=10
X=10 Y=10 testing

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.

Here is the simplest example of autoboxing:


Character ch = 'a';

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.

Consider the following code:


List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
li.add(i);

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:

 Passed as a parameter to a method that expects an object of the corresponding


wrapper class.
 Assigned to a variable of the corresponding wrapper class.

Consider the following method:


public static int sumEven(List<Integer> li) {
int sum = 0;
for (Integer i: li)
if (i % 2 == 0)
sum += i;
return sum;
}

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;
}

Converting an object of a wrapper type (Integer) to its corresponding primitive (int)


value is called unboxing. The Java compiler applies unboxing when an object of a
wrapper class is:

 Passed as a parameter to a method that expects a value of the corresponding


primitive type.
 Assigned to a variable of the corresponding primitive type.

The Unboxing example shows how this works:


import java.util.ArrayList;
import java.util.List;

public class Unboxing {

public static void main(String[] args) {


Integer i = new Integer(-8);

// 1. Unboxing through method invocation


int absVal = absoluteValue(i);
System.out.println("absolute value of " + i + " = " + absVal);

List<Double> ld = new ArrayList<>();


ld.add(3.1416); // Π is autoboxed through method invocation.

// 2. Unboxing through assignment


double phi = ld.get(0);
System.out.println("phi = " + phi);
}

public static int absoluteValue(int i) {


return (i < 0) ? -i : i;
}
}

The program prints the following:


absolute value of -8 = 8
phi = 3.1416

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:

Primitive type Wrapper class


boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
ava is an object-oriented language and as said everything in java is an object. But what about the
primitives? They are sort of left out in the world of objects, that is, they cannot participate in the object
activities, such as being returned from a method as an object, and being added to a Collection of objects,
etc. . As a solution to this problem, Java allows you to include the primitives in the family of objects by
using what are called wrapper classes.

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:

Primitive datatype-->Wrapper Class-->Constructor arguments

 boolean--> Boolean--> boolean or String


 byte--> Byte--> byte or String
 char--> Character--> char
 short--> Short--> short or String
 int-->Integer--> int or String
 long--> Long--> long or String
 float-->Float--> float double or String
 double-->Double--> double or String

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:

Boolean wboo = new Boolean("false");


Boolean yboo=new Boolean(false);
Byte wbyte = new Byte("2");
Byte ybyte=new Byte(2);
Short wshort = new Short("4");
Short yshort = new Short(4);
Integer wint = new Integer("16");
Integer yint = new Integer(16);
Long wlong = new Long("123");
Long ylong = new Long(123);
Float wfloat = new Float("12.34f");
Float yfloat = new Float(12.34f);
Double wdouble = new Double("12.56d");
Double wdouble = new Double(12.56d);
Character c1 = new Character('c');

The value may also be passed as a variable, as shown in the following example:

Code:

boolean boo = false;


Boolean wboo = new Boolean(boo);
byte b = 2;
Byte wbyte = new Byte(b);
short s = 4;
Short wshort = new Short(s);
int i = 16;
Integer wint = new Integer(i);
long l = 123;
Long wlong = new Long(l);
float f = 12.34f;
Float wfloat = new Float(f);
double d = 12.56d;
Double wdouble = new Double(d);

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.

Wrapping Primitives Using a static Method

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:

Integer i2 = Integer.valueOf("101011", 2); // converts 101011 to 43 and


assigns the
// value 43 to the Integer object
i2

or

Code:

Float f2 = Float.valueOf("3.14f"); // assigns 3.14 to the Float object f2

Methods to Create Wrapper Objects

Wrapper class-->method Signature-->method arguments

 Boolean--> static Boolean valueOf(…)-->boolean or String


 Character--> static Character valueOf(…)-->Char
 Byte--> static Byte valueOf(…)-->byte, String, or String and radix
 Short--> static Short valueOf(…)-->short, String, or String and radix
 Integer--> static Integer valueOf(…)-->int, String, or String and radix
 Long--> static Long valueOf(…)-->long, String, or String and radix
 Float--> static Float valueOf(…)-->float or String
 Double--> static Double valueOf(…)-->double or String
The valueOf(…) method in the Character class accepts only char as an argument, while any other
wrapper class will accept either the corresponding primitive type or String as an argument.The
valueOf(…) method in the integer number wrapper classes (Byte, Short, Integer, and Long) also accepts
two arguments together: a String and a radix, where radix is the base.

Using Wrapper Conversion Utilities

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:

Integer i2 = new Integer(42); // make a new wrapper object


byte b = i2.byteValue(); // convert i2's value to a byte primitive
short s = i2.shortValue(); // another of Integer's xxxValue methods
double d = i2.doubleValue(); // yet another of Integer's xxxValue methods

or

Code:

Float f2 = new Float(3.14f); // make a new wrapper object


short s = f2.shortValue(); // convert f2's value to a short primitive
System.out.println(s); // result is 3 (truncated, not rounded)

xxx Parsexxx(String) method

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:

static <type> parse<Type>(String s)

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:

static int parseInt (String s)

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.

Methods to Convert Strings to Primitive Types

Wrapper Class--> Method Signature--> Method Arguments

 Boolean--> static boolean parseBoolean(…)--> String


 Character--> Not Available
 Byte static byte parseByte(…)--> String, or String and radix
 Short--> static short parseShort(…)--> String, or String and radix
 Integer--> static int parseInt(…)--> String, or String and radix
 Long--> static long parseLong(…)--> String, or String and radix
 Float--> static float parseFloat(…)--> String
 Double--> static double parseDouble(…)--> double or String

parseXxx() and valueOf()

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.

The difference between the two methods is:

 parseXxx() returns the named primitive.


 valueOf() returns a newly created wrapped object of the type that invoked the method.

Some examples of these methods in action:

Code:

double d4 = Double.parseDouble("3.14"); // convert a String to a


primitive
System.out.println("d4 = " + d4); // result is "d4 = 3.14"
Double d5 = Double.valueOf("3.14"); // create a Double object
System.out.println(d5 instanceof Double ); // result is "true"

The next examples involve using the radix argument, (in this case binary):

Code:

long L2 = Long.parseLong("101010", 2); // binary String to a primitive


System.out.println("L2 = " + L2); // result is "L2 = 42"
Long L3 = Long.valueOf("101010", 2); // binary String to Long object
System.out.println("L3 value = " + L3); // result is "L2 value = 42"
toString() method

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:

Double d = new Double("3.14");


System.out.println("d = " + d.toString() ); // result is "d = 3.14"

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:

System.out.println("d = " + Double.toString(3.14); // result is "d = 3.14"

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:

System.out.println("hex = " + Long.toString(254,16); // result is "hex = fe"

toXxxString() method(Binary, Hexadecimal, Octal)

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:

String s3 = Integer.toHexString(254); // convert 254 to hex


System.out.println("254 in hex = " + s3); // result is "254 in hex = fe"
String s4 = Long.toOctalString(254); // convert 254 to octal
System.out.println("254 in octal = "+ s4); // result is "254 in octal = 376"

public class FindRanges

2 {

3 public static void main(String[] args)

4 {
5 System.out.println("Integer range:");

6 System.out.println(" min: " + Integer.MIN_VALUE);

7 System.out.println(" max: " + Integer.MAX_VALUE);

8 System.out.println("Double range:");

9 System.out.println(" min: " + Double.MIN_VALUE);

10 System.out.println(" max: " + Double.MAX_VALUE);

11 System.out.println("Long range:");

12 System.out.println(" min: " + Long.MIN_VALUE);

13 System.out.println(" max: " + Long.MAX_VALUE);

14 System.out.println("Short range:");

15 System.out.println(" min: " + Short.MIN_VALUE);

16 System.out.println(" max: " + Short.MAX_VALUE);

17 System.out.println("Byte range:");

18 System.out.println(" min: " + Byte.MIN_VALUE);

19 System.out.println(" max: " + Byte.MAX_VALUE);

20 System.out.println("Float range:");

21 System.out.println(" min: " + Float.MIN_VALUE);

22 System.out.println(" max: " + Float.MAX_VALUE);

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

Examples of final class

Example 2 : Program that illustrates how to use final class in java


using Colored3dPoint class

class Point
{
int x, y;
}

class ColoredPoint extends Point


{
int color;
}

// Colored3dPoint class cannot be extended further

final class Colored3dPoint extends ColoredPoint


{
int z;
}

class FinalClassDemo
{
public static void main(String args[])
{
Colored3dPoint cObj = new Colored3dPoint();

cObj.z = 10;
cObj.color = 1;
cObj.x = 5;
cObj.y = 8

System.out.println("x = " + cObj.x);


System.out.println("y = " + cObj.y);
System.out.println("z = " + cObj.z);
System.out.println("Color = " + cObj.color);
}
}

Output

x=5
y=8
z = 10
Color = 1

You might also like