用连接运算符“+”连接字符串

编写Example类,在main()方法中通过运算符“+”,实现字符串连接(包括基本数据类型及对象)并查看输出结果。

运行结果:

Eclipse中运行Example类,结果如图1所示。

  1  Example类的运行结果

解题关键:

l         在字符串中运算“+”用于实现字符串连接。

答案:

Example.java文件代码如下:

public class Example {

      public static void main(String[] args) {

            System.out.println("MWQ" + 9412);      // int型连接输出结果是MWQ9412

            System.out.println("10" + 7.5F);            // float型连接输出结果是107.5

            System.out.println("This is " + true);     // 与布尔型连接输出结果是This is true

            System.out.println("MR" + "MWQ");      // 字符串间连接输出结果是MRMWQ

            // 与引用类型连接输出结果是路径:C:\text.txt

            System.out.println("路径:" + (new java.io.File("C:/text.txt")));

            System.out.println();

            System.out.println(100 + 6.4 + "MR");   //字符串在后输出结果是106.4MR

            System.out.println("MR" + 100 + 6.4);   //字符串在前输出结果是MR1006.4

      }

}