Java 中的toSttring方法

本文详细介绍了Java中对象的toString方法实现,通过一个具体的Apple类示例,展示了如何自定义toString方法来返回对象的状态信息,这对于调试和理解对象在运行时的状态非常有用。

一般都是对自身信息的描述:

 

输出一个对象,对于toString可以省略,结果是一样的

 

package tostring;

/**
 * Date:2019/9/21
 * Author:zkh
 * DESC:
 */
public class Apple {
    private  String color;
    private  int weight;
    public  Apple(){
    }

    public Apple(String color, int weight) {
        this.color = color;
        this.weight = weight;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Integer getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }
    public String toString(){
        return "一个苹果的颜色是:"+color+",重量是:"+weight;
    }
}

 

 

package tostring;

/**
 * Date:2019/9/21
 * Author:zkh
 * DESC:
 */
public class ToStringDemo {
    public static void main(String[] args) {
        Apple apple = new Apple("红色", 56);
        System.out.println(apple.toString());//结果和下面一句一样的
        System.out.println(apple);//结果和上面一句一样的
    }
}

 

Java 中,`toPlainString` 和 `toString` 是 `BigDecimal` 类的两个方法,用于将 `BigDecimal` 对象转换为字符串,二者存在明显区别。 ### `toPlainString` 方法 `toPlainString` 方法返回不带指数字段的 `BigDecimal` 的字符串表示形式,也就是直接显示数值,不使用科学计数法。例如: ```java import java.math.BigDecimal; public class BigDecimalDemo { public static void main(String[] args) { BigDecimal bg = new BigDecimal("1E11"); System.out.println(bg.toPlainString()); } } ``` 上述代码输出结果为 `100000000000`,直接显示了数值,没有使用科学计数法[^4]。 ### `toString` 方法 `toString` 方法在有必要时会使用科学计数法来表示 `BigDecimal` 对象。例如: ```java import java.math.BigDecimal; public class Test05 { public static void main(String[] args) { BigDecimal num = new BigDecimal(Math.pow(0.521, 35)); System.out.println(num.toString()); } } ``` 当运行上述代码时,如果结果是一个非常小或非常大的数,`toString` 方法可能会使用科学计数法来表示,如 `5.148554641076956121994511276767154838481760200726351203835429763013462401E-8` [^2][^3]。 ### 二者区别总结 - `toPlainString` 方法始终以普通的十进制格式输出,不使用指数形式。 - `toString` 方法在数值需要时会使用科学计数法来表示,以更简洁地表示非常大或非常小的数。 ### 代码对比示例 ```java import java.math.BigDecimal; public class ComparisonExample { public static void main(String[] args) { BigDecimal bd = new BigDecimal("0.0000001"); System.out.println("toPlainString: " + bd.toPlainString()); System.out.println("toString: " + bd.toString()); } } ``` 上述代码输出结果为: ``` toPlainString: 0.0000001 toString: 1E-7 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值