Use tostring in java

How to use the toString() in Java

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

What is toString()?

A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.

How to use the toString() method

The toString() method in Java has two implementations;

  • The first implementation is when it is called as a method of an object instance. The example below shows this implementation
class HelloWorld
public static void main( String args[] )
//Creating an integer of value 10
Integer number=10;
// Calling the toString() method as a function of the Integer variable
System.out.println( number.toString() );
>
>
  • The second implementation is when you call the member method of the relevant class by passing the value as an argument. The example below shows how to do this
class HelloWorld
public static void main( String args[] )
// The method is called on datatype Double
// It is passed the double value as an argument
System.out.println(Double.toString(11.0));
// Implementing this on other datatypes
//Integer
System.out.println(Integer.toString(12));
// Long
System.out.println(Long.toString(123213123));
// Booleam
System.out.println(Boolean.toString(false));
>
>

What is interesting is that this method can also be over-ridden as part of a class to cater to the customized needs of the user. The example below shows how to do this!

class Pet
String name;
Integer age;
Pet(String n, Integer a)
this.name=n;
this.age=a;
>
//Over-riding the toString() function as a class function
public String toString()
return "The name of the pet is " + this.name + ". The age of the pet is " + this.age;
>
>
class HelloWorld
public static void main( String args[] )
Pet p = new Pet("Jane",10);
//Calling the class version of toString()
System.out.println(p.toString());
//Calling the original toString()
System.out.println(Integer.toString(12));
>
>

In the code above, from lines 11 to 13 we have simply created a new method within the Pet class with the same name as the toString() method. On line 20 when the toString() method is called, it is the class version of the method that is invoked. However as seen on line 22, the method does not change for any other data type!

Learn in-demand tech skills in half the time

Источник

Как использовать метод toString() Java

Каждый класс в Java является дочерним классом для класса Object . Класс Object содержит метод toString() . Он используется для получения строкового представления объекта. Каждый раз, когда мы пытаемся вывести ссылку на Object , вызывается метод toString() .

Если мы не определили в классе метод toString() , то будет вызван метод toString() класса Object .

Метод toString() Java: синтаксис

public String toString() < return getClass().getName()+"@"+Integer.toHexString(hashCode()); >// программа Java для демонстрации // работы метода toString() class Best_Friend < String name; int age; String college; String course; String address; Best_Friend (String name, int age, String college, String course, String address) < this.name = name; this.age = age; this.college = college; this.course = course; this.address = address; >public static void main(String[] args) < Best_Friend b = new Best_Friend("Gulpreet Kaur", 21, "BIT MESRA", "M.TECH", "Kiriburu"); System.out.println(b); System.out.println(b.toString()); >>
Best_Friend@232204a1 Best_Friend@232204a1

Пояснение : В приведенной выше программе мы создаем объект класса Best_Friend и предоставляем всю информацию о друге. Но когда мы пытаемся вывести Object , мы отображаем данные из classname@HashCode_in_Hexadeciaml_form . Если нужна соответствующая информация об объекте Best_friend , тогда нужно переопределить метод toString Java класса Object в классе Best_Friend .

// программа Java для демонстрации // работы метода toString() class Best_Friend < String name; int age; String college; String course; String address; Best_Friend (String name, int age, String college, String course, String address) < this.name = name; this.age = age; this.college = college; this.course = course; this.address = address; >public String toString() < return name + " " + age + " " + college + " " + course + " " + address; >public static void main(String[] args) < Best_Friend b = new Best_Friend("Gulpreet Kaur", 21, "BIT MESRA", "M.TECH", "Kiriburu"); System.out.println(b); System.out.println(b.toString()); >>
Gulpreet Kaur 21 BIT MESRA M.TECH Kiriburu Gulpreet Kaur 21 BIT MESRA M.TECH Kiriburu

Примечание . Во всех классах контейнерах, коллекциях, классах String , StringBuffer , StringBuilder метод toString Java переопределяется для значимого представления String . Поэтому настоятельно рекомендуется также переопределить метод toString() и в нашем классе.

// программа Java для демонстрации // работы метода toString() import java.util.*; class Best_Friend < String name; int age; String college; String course; String address; Best_Friend (String name, int age, String college, String course, String address) < this.name = name; this.age = age; this.college = college; this.course = course; this.address = address; >public static void main(String[] args) < Best_Friend b = new Best_Friend("Gulpreet Kaur", 21, "BIT MESRA", "M.TECH", "Kiriburu"); System.out.println(b); String s = new String("Gulpreet Kaur"); System.out.println(s); Integer i = new Integer(21); System.out.println(i); ArrayList l = new ArrayList(); l.add("BIT"); l.add("M.TECH"); System.out.println(l); >>
Best_Friend@232204a1 Gulpreet Kaur 21 [BIT, M.TECH]

Пожалуйста, оставляйте свои комментарии, если найдете ошибку в примерах использования метода toString или захотите поделиться дополнительной информацией по теме статьи.

Источник

toString() Method in Java

Java Course - Mastering the Fundamentals

The toString() method of the Object class returns the string representation of an object in Java. If we print any object, the Java Compiler internally invokes the toString() method on that object. The value returned by the toString() method is then printed.

Since toString() method is defined in Object class and all classes inherit from the Object class, toString() method can be invoked on objects of all classes.

Introduction

toString method in Java

The Object class is the parent of all the classes in Java. Hence, all the methods available in the Object class are available in all the Java classes by default. One of them is the toString() method. By using this method we can get the String representation of any object.

However, by overriding the default implementation of toString() method in Object class, we can provide custom logic regarding how to print the object of a class.

Example

Let’s see an example of default implementation of toString() method in Object class.

Explanation:

This program prints Student@4ca8195f and Student@65e579dc (the hexcode after ‘@’ can be different) as the string representation of std1 and std2 . to the console. To understand the output, let’s see the default implementation of toString() method in the Object class:

Default Implementation of toString() method:

As it is visible in the default implementation, toString() method returns the name of the class and hashCode of the object separated by ‘@’ . Thus the hashCode of std1 and std2 are 4ca8195f and 65e579dc respectively. This may differ when you run the code.

If we want to define the string representation of Student class objects differently, we need to override the toString() method in the Student class.

We don’t explicitly extend the Object class. This is the work of the Java compiler. The compiler checks for the method toString() and invokes whichever is required (default or overridden).

Override the toString() method in Java

Let’s override the toString() method to custom define the string representation of Student class objects.

Explanation:

  • Here we can see, we have written our custom implementation, where we have concatenated the name and rollNo of the student to the returning string.
  • On running the code we get Student .
  • Now this is some useful information regarding the Student object std . In the similar way if you want to have the String representation of an object, you need to override the existing implementation.

Java Classes with toString() Overridden by Default

override tostring in java

Let’s talk about some of the classes in Java that have implemented the toString() method to give some meaningful String representation of the objects.

In Java, all the wrapper classes like Byte , Integer , Long , Float , Double , Boolean , Character have overridden the toString() method. The collection classes such as String , StringBuilder and StringBuffer have also overridden the toString() method as well. Let’s check the running code to make it more clear.

Here we can notice two things,

  1. We have not used the toString() to print the String value of objects, because System.out.println() method by default uses toString() method internally.
  2. We have not implemented the toString() method, Java has itself overridden it for us.

Using static toString() method in Wrapper Classes

The Wrapper classes in Java have a static implementation of the toString() method as well. We can directly get the String value without defining an object of the class.

Using valueOf() method in String Class

One more way to get the String representation of an object is to use the String.valueOf() method of the String class, which internally invokes the toString() method on that particular object.

Conclusion

  • The toString() method is defined in the Object class. It returns the String representation of objects in Java.
  • The default implementation of toString() method returns the concatenation of class name and hashcode value of the object separated by @ .
  • We can override the definition of toString() method in Java in a class to custom define the string representation of its objects.
  • System.out.println() invokes the toString() method internally to print an object in the console.
  • Wrapper and Collection classes have their own implementation of toString() method.

Источник

Читайте также:  Adding checkbox in html
Оцените статью