Home 类库下载 java类库 Strings in Java

Strings in Java

Oct 29, 2016 am 11:52 AM
programming

In Java language, strings are treated as objects, and the class String can be used to represent strings (the first letter of the class name is all capitalized).

1. String constant

A string constant is a string of characters enclosed in double quotes.

For example: "Hello World"

2. String represents a string variable

String is used to create a string object. String usage example:

1 String s=new String(); //Generate an empty string

2 String s1="Hello World"; // Declare s1 as a reference to the string "Hello World"

3. String.equals() method for judging equality of strings

There are particularities in judging equality in Java. Often, the answer obtained by directly using == may be What is correct may also be wrong, look at this example:

String s1="a";
 String s2="a";
 s1+="b";
 System.out.println(s1=="ab");         // false
 System.out.println(s1==s2+"b");     // false
 System.out.println(s2=="a");           // true
 System.out.println(s1.equals("ab")); // true
 System.put.println(new String("ab")==new String("ab"));  // false
Copy after login

After reading this code, you may understand. == judgment not only judges whether the contents in the memory address are equal, but also judges whether the referenced addresses are equal; and the equals() method is used to judge whether the contents are equal. Do you understand now?

There are also the following points to note:


In Java, only one copy of a string constant ("a") with the same content is saved to save memory, so s1 and s2 actually refer to the same an object.

When the compiler compiles the sentence s1, it will remove the "+" sign and directly connect the two strings to get one string ("ab"). This optimization work is done automatically by the Java compiler.

When you create a string object directly using the new keyword, although the values ​​are the same (both are "ab"), they are still two independent objects.

4. Access strings

The String class provides methods such as length(), charAt(), indexOf(), lastIndexOf(), getChars(), getBytes(), toCharArray(), etc.

public int length() This method returns the number of characters in the string

public char charAt(int index) This method returns the character at the index position in the string, where the index value range is 0~length-1

public int indexOf(int ch)

public lastIndexOf(in ch)

Returns the first and last position of the character ch in the string

public int indexOf(String str)

public int lastIndexOf(String str)

Returns the first and last position of the first character in the substring str that appears in the string

public int indexOf(int ch,int fromIndex)

public lastIndexOf(in ch,int fromIndex)

Return the first and last position of the character ch in the string after the position fromIndex

public int indexOf(String str,int fromIndex)

public int lastIndexOf(String str,int fromIndex)

Return sub The first and last positions of the first character in the string str that appear after the position fromIndex in the string.

public void getchars(int srcbegin,int end,char buf[],int dstbegin)

srcbegin is the position of the first character to be extracted in the source string, end is the last character to be extracted in the source string position, the character array buf[] stores the destination string, and dstbegin is the starting position of the extracted string in the destination string.

public void getBytes(int srcBegin, int srcEnd,byte[] dst, int dstBegin)

The parameters and usage are the same as above, except that the characters in the string are represented by 8 bits.

5. Modify the string

The purpose of modifying the string is to get a new string. For the use of each method, please refer to the java API.

Methods provided by the String class:


concat( )

replace( )

substring( )

toLowerCase( )

toUpperCase( )

public String contat(String str);

Used Concatenates the current string object with the given string str.

public String replace(char oldChar,char newChar);

Used to replace all specific characters appearing in the string with specified characters to generate a new string.

public String substring(int beginIndex);

public String substring(int beginIndex,int endIndex);

Used to get the substring within the specified range in the string.

public String toLowerCase();

Convert all characters in the string to lowercase.

public String toUpperCase();

Convert all characters in the string to uppercase.


Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Remove duplicate values ​​from PHP array using regular expressions Remove duplicate values ​​from PHP array using regular expressions Apr 26, 2024 pm 04:33 PM

How to remove duplicate values ​​from PHP array using regular expressions: Use regular expression /(.*)(.+)/i to match and replace duplicates. Iterate through the array elements and check for matches using preg_match. If it matches, skip the value; otherwise, add it to a new array with no duplicate values.

What is programming for and what is the use of learning it? What is programming for and what is the use of learning it? Apr 28, 2024 pm 01:34 PM

1. Programming can be used to develop various software and applications, including websites, mobile applications, games, and data analysis tools. Its application fields are very wide, covering almost all industries, including scientific research, health care, finance, education, entertainment, etc. 2. Learning programming can help us improve our problem-solving skills and logical thinking skills. During programming, we need to analyze and understand problems, find solutions, and translate them into code. This way of thinking can cultivate our analytical and abstract abilities and improve our ability to solve practical problems.

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Build browser-based applications with Golang Build browser-based applications with Golang Apr 08, 2024 am 09:24 AM

Build browser-based applications with Golang Golang combines with JavaScript to build dynamic front-end experiences. Install Golang: Visit https://golang.org/doc/install. Set up a Golang project: Create a file called main.go. Using GorillaWebToolkit: Add GorillaWebToolkit code to handle HTTP requests. Create HTML template: Create index.html in the templates subdirectory, which is the main template.

Collection of C++ programming puzzles: stimulate thinking and improve programming skills Collection of C++ programming puzzles: stimulate thinking and improve programming skills Jun 01, 2024 pm 10:26 PM

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values ​​of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

Get Go modules quickly and easily with Go Get Get Go modules quickly and easily with Go Get Apr 07, 2024 pm 09:48 PM

Through GoGet, you can quickly and easily obtain Go modules. The steps are as follows: Run in the terminal: goget[module-path], where module-path is the module path. GoGet automatically downloads the module and its dependencies. The location of the installation is specified by the GOPATH environment variable.

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Unleash Your Inner Programmer: C for Absolute Beginners Unleash Your Inner Programmer: C for Absolute Beginners Oct 11, 2024 pm 03:50 PM

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

See all articles