search
HomeJavajavaTutorialRegaining the basics of Java (12): Summary of the most commonly used type of Java: String

Regain the basics of java (12): Summary of the most commonly used type of String in java

1. Overview of the String class

  1. Character char One character '' String String One or more ""

    2. String is a reference data type and belongs to the java.lang package

    3. Coding table ascii unicode

4. Java language supports unicode

2. Construction method

 空构造 public String()           
 String s1=new String();            
 System.out.println(s1);           
 输出结果为空。    
 参数为字符串   
 public  String(String  s)           
 String s2=new String("hello");  //String  s2="hello";            
 System.out.println(s2);           
 输出结果为  hello    
 参数为字节数组  
 public String( byte[]  bytes )  转换            
 byte[] t={97,98,99,'d'};   //byte b='d';            
 String s3=new String(t);            
 System.out.println(s3);           
 输出结果为   abcd   它是将byte数组类型转化为ASCII                       
 表对应的字符    
 参数为字符数组  public String( char[]  value )  转换           
 char[] c={'a','b','c',100};  //char d=100;            
 String s4=new String(c);            
 System.out.println(s4);            
 输出结果为   abcd   它是将char数组类型转化为ASCII                       
 表对应的字符。

3. String is Memory allocation map of a special reference type

1. 它支持两种写法:   
String s="hello";   //s也是对象   
String s=new String("hello");            
注意:
String s1="hello";String s2="hello";这时有三个对象  
s1、s2、hello2. 画内存分配图
  • new String

Regaining the basics of Java (12): Summary of the most commonly used type of Java: String

  • Memory allocation in two ways: new and non-new

    Regaining the basics of Java (12): Summary of the most commonly used type of Java: String

  • Empty

Regaining the basics of Java (12): Summary of the most commonly used type of Java: String

  • 3. A string constant can be used directly as an object

    Regaining the basics of Java (12): Summary of the most commonly used type of Java: String

4. +

  1. Splicing strings can only splice strings

2. If When a string is spliced ​​with a non-string, Java will automatically convert the non-string into a string, and then splice it

3. Note: the memory when using + to splice strings Allocation diagram (String objects are immutable)

Regaining the basics of Java (12): Summary of the most commonly used type of Java: String


4. Even if the String object is not new, then string splicing is performed New memory space is opened in the heap every time

5. When string constants are spliced, new memory space is not opened in the heap (emphasis)

5. Methods for determining function-related issues

boolean equals(Object obj)       
String s1="hello";        
String s2=new String("HellO");        
System.out.println(s1==s2);        
System.out.println(s1.equals(s2));        
输出结果为  false  false  ; 
equals比较的是内容区分大小写boolean equalsIgnoreCase(String str)String s3="hello";
String s4="Hello";System.out.println(s3==s4);
System.out.println(s3.equalsIgnoreCase(s4));
輸出結果為 false   true  ;
equalsIgnoreCase比较的是内容不区分大小写boolean contains(String str)String s1="hello";
System.out.println(s1.contains("ho"));输出结果为  false   这个方法是看“hello”中是否包含ho            
记得不能分开,如果是he的话结果就是 trueboolean startsWith(String str)System.out.println(s1.startsWith("he"));
输出结果是:true   
这个方法是求输入的这个字符串是否                    
以你定义的这个字符串开头的!                      
这里就是看  “hello”是否以he开头                    
如果换成e   结果就为false了。
boolean endsWith(String str)        
System.out.println(s1.endsWith("llo"));
输出结果为:true   这个方法是求输入的这个字符串是否                    
以你定义的这个字符串结尾的!                      
这里就是看  “hello”是否以lo结尾                    
如果换位ll  结果就为false了。boolean isEmpty()     ""  null        
s1="";System.out.println(s1.isEmpty());
输出结果为:true   这个方法是看 s1这个字符串是否为""                     
如果是就为true
注意:null1.null在Java中是作为常量存在的2.它表示对象不存在3.一个是可以作为初始值来用,一个是可以加快垃圾回收的速度

6. Methods for obtaining function-related functions

int length()        
String s1="heloool";System.out.println(s1.length());    
输出结果为:7     
这个方法是来求一个字符串的长度的。            
char charAt(int index)            
System.out.println(s1.charAt(0));    
输出结果为 h   这个方法是用来输入字符串的某个字符的地址坐标来                   
输出这个坐标所对应的值;如果输入2的话输出应该为l。      
int indexOf(int ch) 和int indexOf(String str);    
System.out.println(s1.indexOf("he"));    
输出结果为  0   这个方法是用来寻找输入的字符串(例如he)在当前字                           
符串(heloool)中首次出现的,首个字符的位置。                           
注意he要连写,并且不能为ho这种形式  他们都会                           
输出  -1    
int indexOf(int ch,int fromIndex)和int indexOf(String str,int fromIndex)    
System.out.println(s1.indexOf("l",4));    
输出结果为  6   这个方法是用来寻找输入的字符串(例如l)在当前字                           
符串(heloool)中你定义的从哪个地址坐标(4)开始                           
出现的,首个字符的位置。    
String substring(int start)和    
String substring(int start,int end)            
////        
String substring(int start)             
System.out.println(s1.substring(3));      
输出结果为:oool    这个方法是为了求出  s1这个字符串中 从3开始                 
包括(3)这个坐标,开始输出字符串,一直到结尾。                     
//      
String substring(int start,int end)            
System.out.println(s1.substring(2,5));     
输出结果为  loo    这个方法是为了求出  s1这个字符串中 从2开始                 
包括(2)这个坐标,开始输出字符串,一直到5(不包括5                                      
这个坐标)。       
注意:java有两个原则     一、就近原则;二、顾前不顾后原则。

7. Methods for converting function-related functions

byte[] getBytes()        
String s1="abcde";        
byte[] b=s1.getBytes();        
for (int i = 0; i < b.length; i++) {            
System.out.println(b[i]);}输出结果为:97 98 99 100 101(竖着写)            
这个方法表示将一个String 类型的字符串转化为:byte            
类型的数组;对应的值为ASCII表值。
char[] toCharArray()        
char[] c=s1.toCharArray();        
for (int i = 0; i < c.length; i++) {            
System.out.println(c[i]);}输出结果为:a b c d e (竖着写)这个方法表示将一个字符转变为数组 。
注意   数组类型为charstatic String valueOf(char[] chs)  //相当于  new  String(char[] c)        
String s2=String.valueOf(c);        
System.out.println(s2);输出结果为:abcde                 
这个方法是将c这个数组转化为字符串  
static String valueOf(基本数据类型 i)          
int j=100;        
s2=String.valueOf(j);   //s2=j+"";        
System.out.println(s2+100); 输出结果为:100100            这个方法是将基本数据类型转化为字符串。  
注意   :  我们一般将基本数据类型转化为字符串类型一般用              
s2=j+"";String toLowerCase()        
String s3="hElLo";        
System.out.println(s3.toLowerCase());输出结果为:hello            
这个方法是将字符串统一为小写形式。
String toUpperCase()System.out.println(s3.toUpperCase());输出结果为:HELLO                  
这个方法是将字符串统一为大写形式。
String concat(String str)        “+”        
String s4=s3.concat(",world");        
System.out.println(s4);       
输出结果为:hElLo,world            
这个方法是将字符串进行拼接。

8. Other functions of the String class

替换String replace(String old,String new)        
String s1="helloe";        
s1=s1.replace("l", "123");        
System.out.println(s1);输出结果为:he123123oe            
这个方法是将字符串中的l全部用123来替换。分割  
String[] split(String regex)        
String s2="abcdeffcdtt";        
String[] ss=s2.split("cd");        
for (int i = 0; i < ss.length; i++) {            
System.out.println(ss[i]);        
}输出结果为:ab  eff  tt(竖着写)            
这个方法是从cd分割,且不要cd  其前与后都            
分别存入数组。              
去除字符串两端的空格  
String trim()        
String s3="   he   llo  world   ";        
s3=s3.trim();        
System.out.println(s3);输出结果为:he   llo  world            
这个方法是将s3字符串两端的空格去掉!        
s3=s3.replace(" ", "");        
System.out.println(s3);        输出结果为:helloworld           
注意:     用""来替换" "  这样就起到了删除效果补充:  
int lastIndexOf(int ch)int lastIndexOf(int ch,int fromIndex)int lastIndexOf(String s)        
String s4="hello";        
System.out.println(s4.indexOf("l"));          //输出为2    这个是从前向后找        
System.out.println(s4.lastIndexOf("l"));          //输出为3    这个是从后向前找!
int lastIndexOf(String s,int fromIndex)

The above is a summary of the basics of Java (12): the most commonly used type of String in Java. For more related content, please pay attention to PHP Chinese Net (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

What does 'platform independence' mean in the context of Java?What does 'platform independence' mean in the context of Java?Apr 23, 2025 am 12:05 AM

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Can Java applications still encounter platform-specific bugs or issues?Can Java applications still encounter platform-specific bugs or issues?Apr 23, 2025 am 12:03 AM

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

How does cloud computing impact the importance of Java's platform independence?How does cloud computing impact the importance of Java's platform independence?Apr 22, 2025 pm 07:05 PM

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

What role has Java's platform independence played in its widespread adoption?What role has Java's platform independence played in its widespread adoption?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

How do containerization technologies (like Docker) affect the importance of Java's platform independence?How do containerization technologies (like Docker) affect the importance of Java's platform independence?Apr 22, 2025 pm 06:49 PM

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!