Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use String in Java

Shulou Source: shulou.com Published: 2022-06-01 00:42:14 09月21日 Update

Today, the editor will share with you the relevant knowledge points about how to use String in Java. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Overview of 1.String

The String class is under the java.lang package, so you don't need a guide package when using it.

The String class represents a string, and all string literals in the Java program (such as "abc") are implemented as instances of this class.

two。 Characteristics

Strings are immutable and their values cannot be changed after they are created

Although the values of String are immutable, they can be shared

A string is equivalent to a character array (char []), but the underlying principle is a byte array (byte []).

The 3.String constructor project Valuepublic String () creates a blank string object without any content public String (char [] chs) creates a string object based on the contents of the character array public String (byte [] bys) creates a string object String = "abc" directly assigns values according to the contents of the byte array, and the content is the characteristic of the abc4.String object.

For string objects created through new, each time new requests a memory space, although the content is the same, but the address value is different.

Char [] chs = {'axiaqingjinyuanjiaoyuanjiaoyuanjiaoyuanjiaoyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongjiaoyuanshu (char)

String S1 = new String (chs)

String S2 = new String (chs)

In the above code, JVM first creates an array of characters, and then each time new has a new address, except that S1 and S2 reference the same string content.

5. Comparison of strings

Use "=" for comparison

Basic type: compare whether the data values are the same

Reference type: compare whether the address value is the same

A string is an object, and it compares whether the content is the same, which is achieved by a method called equals ()

Public boolean equals (Object anObject); compares this string to the specified object, and since we are comparing the string object, the parameter passes a string directly.

6. Implement user login

The code is as follows:

Import java.util.Scanner;public class ArrayDemo {public static void main (String [] args) {String username= "abc"; String passworld= "123"; / / use a loop to achieve three login opportunities for (int item0)

Tags: Character string content object same array knowledge article address method user different code byte password namely time characteristic user name type Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB vpn Shulou Information NVidia macOS