×

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method is used most frequently to obtain a string representation for an object. The reason for not using the same method is that this procedure was automatically invoked whenever used a print statement. Therefore, this function is overridden to return specific elements of the Object.

Example1:StringOverride.java

//Program is for overriding the toString() method in Java
//importing packages
import java.io.*;
import java.util.*;
class MethodOverride{
private double rem, imp;
public MethodOverride(double rem, double imp) {
this.rem = rem;
this.imp = imp;
}
}
// the class StringOverride to test the MethodOverride class
class StringOverride{
public static void main(String[] args) {
MethodOverride obj = new MethodOverride(100, 115);
System.out.println(obj);
}
}

Output

MethodOverride@76ed5528

Explanation: The output consists of the class name, the "at" symbol, and the Object's hashCode at the end. In Java, all classes directly or indirectly originate from the Object class. Some fundamental functions, like clone(), function toString(), equals(), etc., are available in the Object class. "Class name @ hash code" is printed by the function toString() method's default invocation of Object. We can override our class's function toString() to produce appropriate output.

Example2: StringOverride.java

//Program for overriding the toString() method in Java
//importing packages
import java.io.*;
import java.util.*;
public class StringOverride {
// Main section of the program
public static void main(String[] args) {
// an object is created for the class 
Program p1 = new Program(23,19);
// The complex number is displayed
System.out.println(p1);
}
}
// The Superclass
class Program {
// the variables of the complex number
private double real, imaginary;
// the constructor is used for declaring the default values
// the parameters are passed to the constructor
public Program(double real, double imaginary) {
// it indicates the current values of the number 
this.real=real;
this.imaginary=imaginary;
}
public double getReal() {
return this. real;
}
public double getImaginary() {
return this. imaginary;
}
public void setReal(double real) {
this.real = real;
}
public void setImaginary(double imaginary) {
this.imaginary = imaginary;
}
// the toString() method is overrides
@Override
public String toString() {
return this.real + " + " + this.imaginary + "i";
}
}

Output

23.0 + 19.0i

Related Topics

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

How to stop execution after a certain time in Java

We will learn how to stop a long-running execution after a set amount of time in this post. We will take a look at a few alternative approaches to this...

6 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

Sudoku in Java

Sudoku is a combinatorial-number-placement puzzle with a logic-based approach. The goal of a traditional Sudoku puzzle is to fill in the numbers on a 9 by 9 grid so that...

6 minutes read.

Java Implements Keyword

To understand about the keyword implements we need to learn about the concept of the interfaces and inheritance in java programming languages. So let us learn about the interface and...

3 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.