Detailed explanation of strings in Java
String
In java, strings are treated as objects of type String. The String class is located in the java.lang package, which is automatically imported by all programs by default.
Methods to create String objects:
String s1 = "java"; String s2 = new String(); String s3 = new String("Java");
Immutability of Java strings
String objects cannot be modified after they are created , is immutable. The so-called modification actually creates a new object, pointing to a different memory space.
If you need a string that can be changed, you can use StringBuffer or StringBuilder.
Each time a new string is generated, a new object is generated. Even if the contents of the two strings are the same, it will be "false" when compared using "==". If you only need to compare whether the contents are the same, you should Use the "equals()" method.
The constant pool in Java is used to save data in compiled class files that have been determined during compilation.
package cn.test;public class Demo12 { public static void main(String[] args) { String s1 = "java";//先检查字符串常量池中是否有"java"字符串,如果有则直接指向,如果没有就在字符串常量池中添加"java"字符串并指向它,所以这种方式创建字符串时最多创建一个对象,或者不创建对象 String s2 = "java";//s2直接指向字符串常量池中的"java" String s3 = new String("java");//在堆内存申请一块内存存储字符串"java",s3指向其内存块对象,同时检查字符串常量池中是否有"java"字符串,如果没有就添加字符串"java"到常量池中,所以new String()有可能创建两个对象 String s4 = new String("java"); System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s3 == s4); s1 = "欢迎来到" + s1; System.out.println(s1); System.out.println(s3.equals(s4)); } }
Execution result:
true
false
false
Welcome to java
true
- ##String class Commonly used methods
##Example 1:
String fileName = "HelloWorld.java"; String email = "xiaoli@163.com"; // 判断.java文件名是否正确:合法的文件名应该以.java结尾 int index = fileName.lastIndexOf('.'); String prefix = fileName.substring(index+1); if ( index > 0 && prefix.equals("java")) { System.out.println("Java文件名正确"); } else { System.out.println("Java文件名无效"); } // 判断邮箱格式是否正确:合法的邮箱名中至少要包含"@", 并且"@"是在"."之前 int index2 = email.indexOf('@'); int index3 = email.indexOf('.'); if (index2 != -1 && index3 > index2) { System.out.println("邮箱格式正确"); } else { System.out.println("邮箱格式无效"); } String str = "boo:and:foo"; String[] arr = str.split(":"); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]); }
String str = "boo:and:foo"; String[] arr = str.split(":"); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]); }
Execution results:
The Java file name is correct
The email format is correct booandfoo
Example 2:
String str = "abcd阿"; byte[] b = str.getBytes(); for (int j = 0; j < b.length; j++) { System.out.print("[" + b[j] + "]"); }
Running result:
[97][98][99][100][-80][- 94]
Note: 1 byte is equal to 8 bits. In gbk encoding, 1 Chinese character storage requires 2 bytes, and 1 English character storage requires 1 byte.
Example 3 :
String s = "aljlkdsflkjsadjfklhasdkjlflkajdflwoiudsafhaasdasd"; // 出现次数int num = 0; // 循环遍历每个字符,判断是否是字符 a ,如果是,累加次数for ( int i = 0;i < s.length(); i++ ) { // 获取每个字符,判断是否是字符a if ( s.charAt(i) == 'a' ) { // 累加统计次数 num++; } } System.out.println("字符a出现的次数:" + num);
Running result:
Number of occurrences of character a: 8
- StringBuilder class
- The String class is mutable, and many temporary
will be generated when strings are frequently manipulated. This problem can be avoided by using StringBuilder or StringBuffer. They are basically similar, the difference is that StringBuffer is thread safe, so the performance is slightly higher. Therefore, in general, to create a string object with variable content, the StringBuilder class is preferred. StringBuilder str2 = new StringBuilder("java");
The above is the detailed content of Detailed explanation of strings in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.
