5, a trap in an expression

Source: Internet
Author: User

The trap of a string;

The first time a string is used directly, the JVM caches it into a string pool;

Examples of memory leaks:

String str= "Hello"

String str=str+ "Java"

The sequence of characters contained in a string cannot be changed. So the second STR is pointing to another string object, at which time the Hello string is in memory, the garbage collection mechanism does not recycle it, and then a memory leak occurs.

If you want to use string mutable strings generally use StringBuffer and StringBuilder, but most of the methods in StringBuffer use the synchronized modifier to ensure thread safety, but it can reduce the efficiency of the method to perform. Use the StringBuilder class to represent strings in environments that do not have multiple threads.

Automatic promotion rules for expression types;

1, all byte,short. and char types are promoted to type int.

char (Byte,short) _int_long_float_double

2, the data type of the entire arithmetic expression is automatically promoted to the same type as the highest-level operand of the expression.

Short svalue=5;//defines a short type variable, and the svalue is automatically promoted to int. svalue=svalue-2;//An error occurred when assigning an int type to a short type variable. Svalue-=2 can compile normally, because he is equivalent to svalue= (svalue) (sValue-2); It contains the hermit type conversion. (Almost all binocular operators contain hermit conversions)
int val=3; int result=20/val; System.out.println ("" +result);//output 6, the visible result is the int type.
System.out.println ("Hello" + ' a ' +7); System.out.println (' A ' +7+ "hello"); output Helloa7 104hello when the base type and string type are connected, the system automatically converts the value of the base type to the string type.

2, IME may also cause errors.

Java programs typically cannot contain full-width characters, such as Chinese Spaces, tab tabs.

5, a trap in an expression

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.