×

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

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.

Thread Concept in Java

What is a Thread? A subprocess that is lightweight in Java is known as a thread. It is the smallest unit of a process. For the running of multiple tasks parallelly...

3 minutes read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

&& Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Series Program in Java

Series Program in Java The series program in Java is written to print the mathematical series such as the Fibonacci series, Pell series, etc. A few of the renowned series are...

12 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must...

3 minutes read.

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to...

2 minutes read.

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.