Java (1)

Source: Internet
Author: User
Java (1) 1. Time to change (currency Calculation Problem)

Problem description: how much change should the shopkeeper look for him if Tom has purchased $2.0 and purchased $1.10 USD?

1 public class Change {2     public static void main(String[] args) {3         System.out.println(2.00-1.10);//0.89999999999999994     }5 }

Result: 0.8999999999999999

The problem is that the number 1.10 cannot be exactly represented as a double because it is represented as the double value closest to it. More generally, the problem is thatNot all decimals can be exactly expressed using binary floating point numbers.

One way to solve this problem is to use an integer type, such as int or long, and perform computation in units. If this line is adopted, make sure that the integer type is large enough to indicate all the values you will use in the program.

     System. out. println (200-110) + "cents ");

Another way to solve this problem is to use BigDecimal that executes the exact decimal operation. Note: you must use the BigDecimal (String) constructor instead of the BigDecimal (double) constructor. BigDecimal: immutable, any-precision signed decimal number. The BigDecimal value is (unscaledValue × 10-scale ).

1 import java.math.BigDecimal;2 3 public class Change {4     public static void main(String[] args) {5         System.out.println(new BigDecimal("2.00")6             .subtract(new BigDecimal("1.10")));//0.907     }8 }

Conclusion: Do not use float or double for exact answers. For currency calculations, use int, long, or BigDecimal. BigDecimal computing may be slower than those of the original type. For some programs that use a large number of decimal computing tasks, this may become a problem. For most programs, this is not important at all.

 

2. Conditional Operators

First look at the following program code:

1 public class DosEquis {2     public static void main(String[] args) {3         char x='X';4         int i=0;5         System.out.println(true?x:0);//X6         System.out.println(false?i:x);//887     }8 }

Running result: X 88

The running result is X88, not XX. Why?

The following describes the three core points in the criterion of the condition expression result type:

    1) if the second and third operands have the same type, it is the type of the conditional expression. In other words, you can avoid great troubles by bypassing the computation of the hybrid type.

2) If the type of one operand is T, T indicates byte, short, or char, And the other operand isConstant expression of int typeThe value can be represented by type T, so the type of the conditional expression is T.

3) Otherwise, binary numbers will be used for the operand type, and the type of the conditional expression is the type after the second and third operands are upgraded.

2 and 3 are key to this puzzle. In the two conditional expressions of the program, the type of one operand is char, and the type of the other is int. In both expressions, the int operand is 0, which can be expressed as a char. However, only the int operands in the first expression are constants (0), while the int operands in the second expression are variables (I ). Therefore, point 2nd is applied to the first expression. The returned type is char, and point 3rd is applied to the second expression, the returned type is the type after the binary numbers are used for int and char, that is, int.

Demo extension:

1 public class DosEquis {2 public static void main (String [] args) {3 char x = 'X '; 4 // test constants of the int type 5 int I = 12; 6 System. out. println (true? X: 12); // X 7 System. out. println (true? X: I); // 88 8 // test the long type constant 9 long l = 12L; 10 System. out. println (true? X: 12L); // 8811 System. out. println (true? X: l); // 8812 // test the float type constant 13 double d = 12.0; 14 System. out. println (true? X: 12.0); // 88.015 System. out. println (true? X: d); // 88.016} 17}
3. Value assignment operator (compound value assignment expression)

Half a catty:  

Let's give a declaration of the variables x and I. It must be a legal statement:

 

    X + = I;

 

However, it is not:

 

    X = x + I;

 

Many Programmers think that expressions (x = x + I;) are short expressions (x + = il. However, this is not very accurate. Both expressions are value assignment expressions. The following day, the sentence uses a simple value assignment operator (=), and the first statement uses a composite value assignment operator. (Compound assignment operators include: + =,-=, * =,/=, % =, <=, >=, >>>=, & =, ^ =, and! =). As mentioned in the Java language specification, compound assignmentE1 op = E2;Equivalent to simple assignmentE1 = (T) (E1) op (E2 ));,Where T is the E1 type, Unless E1 is calculated only once.

In other words,The composite value assignment expressions automatically convert the calculation results they execute to the type of the variable on the left.If the result type is the same as the type of the variable, the type will not be affected. However, if the result type is wider than the variable type, the composite value assignment operator will implicitly execute forced type conversion. Therefore, we have a good reason to explain why a compilation error may occur when trying to execute an equivalent simple assignment.

Sample Code:

1 public class Demo {2 public static void main (String [] args) {3 short x = 0; 4 int I = 123456; 5 x + = I; // composite value assignment compilation will not produce any errors: contains a hidden transformation! 6 7 // x = x + I; // compilation error: Type mismatch: cannot convert from int to limit 8} 9}

To avoid implicit type conversion (precision will be involved) with compound value assignment expressions, do not mention that compound value assignment operators act on byte, short, or char type variables. When you apply a composite value assignment operator to an int type variable, make sure that the right side of the expression is not of the long, float, or double type. When you apply a composite value assignment operator to a float variable, make sure that the right side of the expression is not a double type.

VIII:

Contrary to the preceding example, if the statements about variables x and I are as follows:

    X = x + I;

However, it is not:

   X + = I;

At first glance, this puzzle may look the same as the previous one. But rest assured that they are not the same. Which statement of the two puzzles must be legal and which statement must be illegal is the opposite.

Just like the previous puzzle, the puzzle also relies on details in the specification for composite assignment operators. The similarities between the two are blocked. Based on the previous puzzles, you may think that compound assignment operators are less restrictive than simple assignment operators. In general, this is correct, but there is such a field where the simple value assignment operator will look looser.

  The composite value assignment operator requires that both operands belong to the original type, such as int, or the encapsulated original type, such as Integer, but with one exception: if the operand on the left side of the + = Operator is of the String type, it allows the operand on the right side to be of any type. In this case, the operator performs the String join operation.The simple value assignment operator (=) allows the object reference type on the left, which is much looser: You can use them to represent anything you want to represent, as long as the variable on the right side of the expression is compatible with the value assignment on the left.

Sample Code:

1 public class Demo {2 public static void main (String [] args) {3 Object o = "Buy"; 4 String s = "valid tive Java! "; 5// Simple assignment is legal, because o + s is of the String type, and the String type is compatible with the Object assignment:6 o = o + s; 7// The compound value assignment is invalid because the left side is an Object reference type, and the right side is a String type:8 // o + = s; 9 // compilation error: The operator + = is undefined for the argument type (s) Object, String 10} 11}

 

4. String "+" connection operation: Livestock Farm

Readers of George Orwell's Animal Farm may remember the old colonel's statement: "All animals are equal ." The following Java program tries to test this declaration. So what will it print out?

 1 public class Demo { 2     public static void main(String[] args) { 3         final String pig = "length: 10"; 4         final String dog = "length: " + pig.length(); 5         System.out.println("pig=:"+pig+",dog="+dog); 6         //pig=:length: 10,dog=length: 10 7         System.out. println("Animals are equal: "+ pig == dog);//false 8          9         String str1="length: 10";10         String str2="length: " + str1.length();11         String str3="length: 10";12         System.out. println(str1==str2);//false13         System.out.println(str1==str3);//true14     }15 }

The surface analysis of the program may think that it should print out the Animal are equal: true. After all, pig and dog are both final string-type variables and they are initialized as character sequences "length: 10 ". In other words, strings referenced by pig and dog are always equal to each other. However, the = Operator tests whether the two objects reference the same object. In this example, they are not referenced to the same object.

The constant of the String type during compilation isMemory limit. In other words, if two constant expressions of the String type indicate the same character sequence, they are represented by the same object reference. If you use a constant expression to initialize pig and dog, they actually point to the same object, but dog is not initialized using a constant expression. Since the language has imposed restrictions on operations allowed in constant expressions, and method calls are not included, this program should print Animal are equal: false, right?

Actually not. If you run the program, you will find that it prints only false, and there is nothing else. It does not print Animal are equal :. How can it not print this string literal constant? After all, printing is correct! Because:+ The operator, whether used as an addition or a string join operation, has a higher priority than the = Operator.Therefore, the parameters of the println method are calculated as follows:

System. out. println ("Animals are equal:" + pig) = dog );

Of course, the value of this Boolean expression is false, which is the output of the program.

Dizzy Hello

See the following program:

 1 /** 2  * Generated by the IBM IDL-to-Java compiler, version 1.0 3  * from F:\TestRoot\apps\a1\units\include\PolicyHome.idl 4  * Wednesday, June 17, 1998 6:44:40 o’clock AM GMT+00:00 5  */ 6 public class Demo { 7     public static void main(String[] args) { 8         System.out.print("Hell"); 9         System.out.println("o world!");10     }11 }

This puzzle looks quite simple. The program contains two statements: the first prints Hell, and the second prints o world in the same line, effectively connecting the two strings. Therefore, you may expect the program to print Hello world. However, it is a pity that you have made a mistake. In fact, it cannot be compiled at all.

The problem is that the third line of the comment contains characters.\ Units.These characters begin with a backslash (\) and followed by the letter u, and it (\ u) represents the beginning of a Unicode escape character. Unfortunately, these characters are not followed by four hexadecimal numbers. Therefore, this Unicode escape character is a constructor, And the compiler is asked to reject the program.Unicode escape characters must be properly constructed, even in comments.

1 public class Demo {2 public static void main (String [] args) {3 // \ u must be followed by four hexadecimal numbers, otherwise, the compilation error 4 char ch = '\ u0065'; 5 System. out. println (ch); // e6} 7}

 

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.