Why to use?
To get the value of reference object.
Every Class in java is inherited from Object Class by default, which is in java.lang. toString is a method that is associated with the Object Class.
Concider this example:
public class mainprog {
public static void main(String[] args) {
String name = "Sourav"
System.out.println(name);
}
}
o/p is Sourav
Here the String Class must have overwritten the toString method, that it has inherited from Object Class
What if we create our own class(String class is by default in Java) and do the same.
Comcider the following:
public class People {
private String name;
private int id;
public People(){
}
public People(String name, int id){
this.name = name;
this.id = id;
}
}
Lets call into main function:
public class Execution {
public static void main(String[] args) {
People p = new People("Sourav",21);
System.out.println(p);
}
}
o/p: com.notestng.People@2a139a55 --> Displayed as Hashcode, no importance of value...
So, we need to override the People class and tell java that boss we want it out way and not your way.
public class People {
private String name;
private int id;
public People(){
}
public People(String name, int id){
this.name = name;
this.id = id;
}
public String toString(){ // ADDED TO THE CODE
return "Name is: "+ this.name+" and ID is: "+this.id;
}
}
Lets Run it...
public class Execution {
public static void main(String[] args) {
People p = new People("Sourav",21);
System.out.println(p);
}
}
o/p : Name is: Sourav and ID is: 21
This is the use of isString() method in Java
toString() in Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment