The String class is under the java.lang package, so there is no need to import the package when using it.
The String class represents a string, and all string literals (such as "abc") in Java programs are implemented as instances of this class.
Strings are immutable, their values cannot be changed after creation
Although the value of String are immutable, but they can be shared
Strings are effectively equivalent to character arrays (char[]), but the underlying principle is byte arrays (byte[])
Project | Value |
---|---|
public String() | Create a blank string object without any content |
Create a string object based on the contents of the character array | |
Create a string based on the contents of the byte array Object | |
Create a string object by direct assignment, the content is abc |
char[ ] chs = {'a','b','c'};String s1 = new String(chs);String s2 = new String(chs);In the above code, the JVM will first create a character array, and then there will be a new address every time new is issued, but the string contents referenced by s1 and s2 are the same. 5. Comparison of stringsUse "==" for comparison
import java.util.Scanner; public class ArrayDemo{ public static void main(String[] args) { String username="abc"; String passworld="123"; //使用循环实现三次登陆机会 for(int i=0;i<3;i++){ Scanner sc=new Scanner(System.in); System.out.println("请输入用户名:"); String name=sc.nextLine(); System.out.println("请输入密码:"); String pwd=sc.nextLine(); if(name.equals(username)&&pwd.equals(passworld)){ System.out.println("登陆成功!"); break; }else{ System.out.println("用户名或密码错误,请重新登录!"); } } } }
The above is the detailed content of How to use String in Java?. For more information, please follow other related articles on the PHP Chinese website!