在 Java 中连接字符串的最佳方法是 concat() 方法。此方法将一个字符串附加到另一个字符串的末尾。该方法返回一个字符串,其值为传递到方法中的字符串,附加到用于调用此方法的字符串的末尾。示例实时演示public class Test { public static void main(String args[]) { String s = "Strings are immutable"; s = s.concat(" all the time"); System.out.println(s); }} 输出Strings are immutable all the time
您可以使用 concat() 方法或 + 运算符组合/连接两个字符串。示例import java.util.Scanner; public class ConncatSample { public static void main(String []args) { Scanner sc = new Scanner(System.in); System.out.println("Enter your first name"); String firstName = sc.nextLine(); System.out.println("Enter your last name"); String lastName = sc.nextLine(); String completeName = firstName+lastName; System.out.print("Hi your complete name is :: "); System.out.println(completeName); }} 输出Enter your first name KrishnaKasyap Enter your last name BhagavatulaHi your complete ... 阅读更多
要在当前类中导入任何包,您需要使用 import 关键字,例如 import packagename;示例实时演示import java.lang.String; public class Sample { public static void main(String args[]) { String s = new String("Hello"); System.out.println(s); }} 输出Hello