Pages

Tuesday, July 10, 2012

toString() method in Java

This method returns the string representation of the object.
If we try to print the object directly without overriding the toString() method for that calss, then we'll get the output  in the format.

ClassName@HexDecRepresentationOfObject or
getClass().getName() + '@' + Integer.toHexString(hashCode())

By default ArrayList overrides the toString method, so if we print the object of ArrayList it'll nicely print the added objects.

A simple example

describing the toString() method:
package com.ex.tostring;

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

public class ToStringSample {
 private int empNo;
 private String empName;
 
 public ToStringSample(int eno,String ename) {
  this.empNo = eno;
  this.empName = ename;
 }
 
 public String toString() {
  return "Employee Name : " this.empName "\n" "Emplyee Id : " this.empNo;
 }
 
 public static void main(String[] args) {
  ToStringSample emp = new ToStringSample(123,"Sachin");
  System.out.println(emp);
  List<String> list = new ArrayList<String>();
  list.add("Sachin");
  list.add("Federer");
  list.add("Vishwanathan Anand");
  System.out.println(list);
 }
} 

output:
Employee Name : Sachin 
Emplyee Id : 123 
[Sachin, Federer, Vishwanathan Anand] 

Now comment toString() method in the above class and execute. 
The expected output will be :
com.ex.tostring.ToStringSample@3e25a5
[Sachin, Federer, Vishwanathan Anand] 

Happy coding...!!!

No comments:

Post a Comment