Java five-way output error-prone analysis (avoid small errors)

Source: Internet
Author: User

Collect a few error-prone or fun Java output problems, share to everyone, later in the programming learning in a little attention to OK.

1. Invisible spaces?

Will the output below be normal?

 Package Basic; Public class integertest {     Public Static void Main(String[] args) {        System. out.println(Integer.parseint("1"));        System. out.println(Integer.parseint("2")); }}


Parsing: Copy the above code (do not knock your own hand) to run in their own environment to see, is not the output of the following error:

1
Exception in thread "main" Java.lang.NumberFormatException:For Input string: "2"
At java.lang.NumberFormatException.forInputString (Unknown Source)
At Java.lang.Integer.parseInt (Unknown Source)
At Java.lang.Integer.parseInt (Unknown Source)
At Basic. Integertest.main (Integertest.java:7)

To say that the second sentence has a problem, the surface can not be completely seen any problem is not!
In fact, the reason for the error here involves a concept-0 of the width of the space , may have been contacted, but believe that more people have not even heard, what is the 0 width of space? It is actually a Unicode character, is a space, the key is that it has no width, so we are generally invisible to the naked eye. But you can see under Vim , the second statement above 2 in front of a 0-width space, put into vim after opening you will find the following statement:

System .  out . println (Integer. parseint ("<feff>2"));


Defined in the Unicode specification, each file is preceded by a character that represents the encoding order, which is called "0-width non-newline space" (zerowidthno-breakspace), denoted by the name FEFF . This happens to be two bytes, and FF is 1 larger than FE. So the following statement will output 65279, just right FEFF .

System .  out . println ((int)"2". charAt (0));
2. class static member initialization

Can the following program compile and pass? If passed, say the result and explain, cannot compile, say wrong reason.

class A{     Public Static int X;    Static { X = B.Y + 1;}} Public class B{     Public Static int Y = A.X + 1;    Static {}     Public Static void Main(String[] args) {        System. out.println("X ="+A.X+", Y ="+B.Y);    }}


Parse: This program can run correctly, the class running process is as follows:

First loading the main class B, initializing the static member Y, discovering the need for the information of Class A, so load Class A, initialize static member X, also use class B information, because at this time the Class B is not successfully loaded so here is the default value of 0, so that the Class A is the X 1, and then return to Class B, Y is 2

3. The actual process of packing and unpacking

About automatic boxing, I believe most people understand what is the matter, but really fully understand it?
Let's look at the following code:

 Short S1 = 1 ;  Short S2 = S1 ; System .  out . println (s1= =s2);


Everyone knows of course printing true. Now add a sentence to try:

 short  s1  =  1   short  s2  =  s1   s1  ++;  system   out   println    ( s1  ==  s2   


Or is it true? No, this time the output is false. Why? Don't S1 and S2 refer to the same object? With these questions you are not very clear about the process of automatic boxing unpacking, in fact the above code can be translated into the following code (the actual execution process, to master):

 Short S1 = New  Short(( Short)1); Short S2 = S1; Short tempS1 = S1.Shortvalue();tempS1++;S1 = New  Short(tempS1);System. out.println(S1 == S2);


Oh, so that's clear, so we'll be careful when it comes to automatic boxing.

4. Your self-righteous abnormality

First two lines of code:

nulltest mynulltest = NULL ; System .  out . println (mynulltest. getInt ());


Believe that many people see this code, will be self-righteous said: NullPointerException . Is it true? You haven't seen how the Nulltest class is defined. Now look at the definition of this class:

class nulltest {public     staticintgetInt(){         return  1 ;     }}


found that getInt() the method body does not use any class variables and class methods, so this will output 1 normally.
Remember: the use of class variables and class methods depends only on the type of reference. Even if the reference is null, it can still be called. From a good practice point of view, it is wise to use it NullTest.getInt() instead myNullTest.getInt() , but there is no guarantee that you will not encounter such code, so be careful.

5. How to change the length parameter and array?

The variable-length parameter feature brings a powerful concept that can help developers simplify code. But what is behind the variable-length parameters? Basically, is an array.

 Public void Calc (int ... myints ){}calc(1,2,3 );


The compiler translates the preceding code into something like this:

int []ints={1,2,3}; Calc (ints);


But here are two points to note:
-Beware of air conditioning with a statement, which is equivalent to passing a null as a parameter.
Calc ();
Equivalent to
int[] ints = null;
Calc (ints);
-Of course, the following code causes a compilation error because the two statements are equivalent:
public void M1 (int[] myints) {...}
public void M1 (int ... myints) {...}

Resources
    • 0 width Space

Java five-way output error-prone analysis (avoid small errors)

Related Article

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.