Java beginners must know about Java strings (1)

Source: Internet
Author: User

Java beginners must know about Java strings (1)

Below I have summarized 10 questions that Java developers often raise about Java strings. If you are also a beginner in Java, take a closer look:

1. How to compare strings? Should I use "=" or equals ()?

In general, "=" is used to compare the reference address of a string, while equals () is used to compare the value of a string. When two strings with the same value are compared with "=", the result may be false, while when equals () is used, it must be true. Unless the two strings are the same new objects, equals () should be used to compare whether the string values are the same ().

2. Why should char [] be used to store security-sensitive information better than String?

String is immutable, which means that once it is created, it will permanently reside in the memory until the Garbage Collector recycles it. However, with Array Storage, You can explicitly change the elements in the array. Therefore, with array storage, security information may not exist anywhere in the system memory.

3. Can I declare the switch statement using a string?

JAVA 7 and later versions are supported. In JDK 7, you can use strings to compare the switch statements. Jdk 6 or earlier versions cannot be used as follows:

 
 
  1. // java 7 only! 
  2. switch (str.toLowerCase()) { 
  3.       case "a": 
  4.            value = 1; 
  5.            break; 
  6.       case "b": 
  7.            value = 2; 
  8.            break; 

4. How to convert a string to a numeric int type?

 
 
  1. int n = Integer.parseInt("10"); 

It is very simple, but it is often used and easy to be ignored.

5. How to use space characters to separate strings?

We can easily use regular expressions to separate strings. "s" indicates space characters, such as "", "t", "r", and "n"

 
 
  1. String[] strArray = aString.split("s+"); 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.