ToString

Conversions

ToString

🙋 Need help? Ask an expert now!

Another string conversion method that will prove useful to you in the future is the toString() method, which takes almost any object in Java and converts it to a String. Let's take a look at this example.

ToStringExample.java
package exlcode;

public class ToStringExample {

  public static int exampleVariableOne = 11;
  public static double exampleVariableTwo = Math.PI;
  public static String exampleVariableThree = Integer.toString(exampleVariableOne);
  public static String exampleVariableFour = Double.toString(exampleVariableTwo);

  public static void main(String[] args) {
    System.out.println(exampleVariableThree);
    System.out.println(exampleVariableFour);
  }
}

This method is useful when you want to print certain expressions. Although primitive data types that we have covered up to this point would print without needing to be converted into a String, there will be other objects we will master, such as arrays, that cannot be print directly, so keep the toString method in mind as we move forward and learn about arrays.

Edit Me on GitHub!

Application Question

#!exl::repl('index.prob.repl.yaml')




...

You've Reached the End of this Course! 🎓🎉

Great work, are you ready to learn more?

View More Courses