在java中不同数据类型可以转换类型输出

1. 基本数据类型 ->String类型

  • int 、float 、double 、boolean 类型转换成字符串类型其实非常简单;只需要一个空字符就可以实现,即 + ” “;
    例:
		int n1 = 100;
		float f1 = 1.2F;
		double d1 = 2.3;
		boolean b1 = true;
		String s1 = n1 + "";
		String s2 = f1 + "";
		String s3 = d1 + "";
		String s4 = b1 + "";
		System.out.println(s1 + " " + s2 + " " + s3 + " " + s4);
  • s1、s2、s3、s4 就是int 、float 、double 、boolean类型变量转换后的结果;

2. String类型 ->对应的基本数据类型

  • 这种转换需要引用parse实现转换,格式:类型.parse类型(类型首字母大写)
    例:
		String s5 = "123";
		int num1 = Integer.parseInt(s5);
		float num2 = Float.parseFloat(s5);
		double num3 = Double.parseDouble(s5);
		long num4 = Long.parseLong(s5);
		byte num5 = Byte.parseByte(s5);
		short num6 = Short.parseShort(s5);
		boolean b = Boolean.parseBoolean("true");
		char c = s5.charAt(0);//得到字符串的第一个字符
  • 其中 int num1 = Integer.parseInt(s5); Integer是 int 的全称;
  • 而 String类型转换成char类型则是:字符串.charAt(0) 表示取到字符串的第一个字符(字符串储存是从0开始的);同理charAt(1) 表示取到字符串的第二个字符

接下来用个简单例子演示转换后的输出
代码:

public class StringToBasic {
	//编写一个main方法
	public static void main(String[] args) {

		//基本数据类型 ->String类型

		int n1 = 100;
		float f1 = 1.2F;
		double d1 = 2.3;
		boolean b1 = true;
		String s1 = n1 + "";
		String s2 = f1 + "";
		String s3 = d1 + "";
		String s4 = b1 + "";
		System.out.println(s1 + " " + s2 + " " + s3 + " " + s4);

		//String ->对应的基本数据类型

		String s5 = "123";
		//会在OOP 学对象和方法的时候回详细
		//解读 使用 基本数据类型对应的包装类,的方法,得到基本数据类型
		int num1 = Integer.parseInt(s5);
		float num2 = Float.parseFloat(s5);
		double num3 = Double.parseDouble(s5);
		Long num4 = Long.parseLong(s5);
		byte num5 = Byte.parseByte(s5);
		short num6 = Short.parseShort(s5);
		boolean b = Boolean.parseBoolean("true");
		char c = s5.charAt(0);//得到字符串的第一个字符

		System.out.println("=========================");
		System.out.println(num1);
		System.out.println(num2);
		System.out.println(num3);
		System.out.println(num4);
		System.out.println(num5);
		System.out.println(num6);
		System.out.println(b);
		System.out.println(c);
	}
}

运行结果:
在这里插入图片描述
注意:文件名是类.java;这里就是 StringToBasic.java


版权声明:本文为m0_61235733原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/m0_61235733/article/details/126921182