Expressive Puzzlers (1)

Puzzle 1:

当求余运算(remainder operation)符 % 返回一个非零余数时,余数的符号位和左边操作数的符号位相同。例如
        System.out.println(( - 53 ) % 9 );  //  -8
        System.out.println( 53 % ( - 9 ));  // 8
        System.out.println(( - 53 ) % ( - 9 ));  // -8

Puzzle 2:

ContractedBlock.gif ExpandedBlockStart.gif Change.java
import java.math.BigDecimal;
public class Change
{
    
public static void main(String args[])
    {
        System.out.println(
2.00 - 1.10);//0.8999999999999999
        System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.10")));//0.90
        System.out.printf("%.2f%n"2.00-1.10);//0.90
    }
}

关于浮点数的二进制表示~~
(1)二进制浮点数并不能精确表示所有的小数
(2)对计算精度要求比较准确(例如金融计算)时,不要使用float和double,尽量使用int, long,BigDecimal.
(3)推荐阅读文章:What Every Computer Scientist Should Know About Floating-Point Arithmetic
网上很多地方都有的。另一本牛书 Computer Systems A Programmers's Perspective上也有讲浮点数
(4)JLS 3.10.1由规范可知 0.1, .1, 1. 都是合法的浮点数。需要注意的是在java中,浮点数有两种原生类型float,double,当浮点数的后缀是F或者f时,该浮点数为float类型,没有后缀或者后缀是D或者d时,该浮点数是double类型的。注意下面的例子
ContractedBlock.gif ExpandedBlockStart.gif FloatPoint.java
public class FloatPoint
{
    
public static void main(String [] args)
    {
        
double x = .12345;
        
double y = 1234.;
        
double z = 1.123432343;
        
        
//float a = 0.1; -- 可能损失精度
        float b = 0.1f;
        
float c = .1234f;
        
//float d = .123; --可能损失精度
        System.out.println("x = " + x);
        System.out.println(
"y = " + y);
        System.out.println(
"z = " + z);
        
        System.out.println(
"b = " + b);
        System.out.println(
"c = " + c);
    }
}

结果:
ContractedBlock.gif ExpandedBlockStart.gif 结果
= 0.12345
= 1234.0
= 1.123432343
= 0.1
= 0.1234

Puzzle 3:
需要注意java是如何处理整数溢出的,看下面的例子就一目了然了,别忘了long是 8 bytes,int是 4 bytes的~~
ContractedBlock.gif ExpandedBlockStart.gif LongDividion.java
public class LongDivision
{
    
public static void main(String[] args)
    {
        
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000L;
        
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;

        
final int micros_per_day = (int) MICROS_PER_DAY;
        
final int millis_per_day = (int)MILLIS_PER_DAY;
        
        System.out.println(Long.toHexString(MICROS_PER_DAY));  
//      141dd76000
        System.out.println(Integer.toHexString(micros_per_day));  //     1dd76000
         System.out.println("*********************************");
        System.out.println(micros_per_day); 
// 500654080
        System.out.println(millis_per_day); // 86400000
    }
}

Puzzle 4:
添加long型整数的后缀时要使用L避免用l,同样不要单独使用小写字母l作为变量名,理由是显而易见的:l和1在大多数字体中太难区分。
Puzzle 5:
(1)和十进制数不同,当十六进制、八进制数的最高位是1时,表示它是一个负数(在十进制数中,表示一个负数要显式使用符号-)
(2)尽量避免混合类型运算,例如本例中的 long型和int型的加法,在java中,一个整数如果没有后缀L或l,则它是一个int型而不是long型。
ContractedBlock.gif ExpandedBlockStart.gif JoyOfHex.java
public class JoyOfHex
{
    
public static void main(String[] args)
    {
        System.out.println(Long.toHexString(
0x100000000L + 0xcafebabe));//cafebabe instead of 1cafebabe
        System.out.println(Long.toHexString(0x100000000L + 0xcafebabeL)); // 1cafebabe
        System.out.println(0xffffffffL); // 4294967295
        System.out.println(0xffffffff); // -1
    }
}
Puzzle 6:
The rule " Sign extension is performed if the type of the original value is signed; zero extension if it is a char, regardless of the type to which it is being converted" describes the sign extension behavior when converting from narrower integral types to wider.

ContractedBlock.gif ExpandedBlockStart.gif Multicast.java
public class Multicast
{
    
public static void main(String[] args)
    {
        
/*  int -> byte : 0xffffffff -> 0xff
        *        byte -> char: 0xff -> 0xffff
        *        char -> int : 0xffff -> 0x0000ffff
        
*/
        System.out.println((
int) (char) (byte-1); //0x0000ffff = 65535
    }
}
Puzzle 6:
JLS 15.7 Evaluation Order
ContractedBlock.gif ExpandedBlockStart.gif CleverSwap.java
public class CleverSwap
{
    
public static void main(String[] args)
    {
        
int x = 1984;
        
int y = 2001;
        x 
^= y ^= x ^= y;
        System.out.println(
"x = " + x + "; y = " + y); // x = 0; y = 1984
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java™ Puzzlers: Traps, Pitfalls, and Corner Cases.chm,英文版本,chm 格式,大小 1 Mb,作者:Joshua Bloch、Neal Gafter。 内容预览: Chapter 1. Introduction Chapter 2. Expressive Puzzlers Puzzle 1: Oddity Puzzle 2: Time for a Change Puzzle 3: Long Division Puzzle 4: It's Elementary Puzzle 5: The Joy of Hex Puzzle 6: Multicast Puzzle 7: Swap Meat Puzzle 8: Dos Equis Puzzle 9: Tweedledum Puzzle 10: Tweedledee Chapter 3. Puzzlers with Character Puzzle 11: The Last Laugh Puzzle 12: ABC Puzzle 13: Animal Farm Puzzle 14: Escape Rout Puzzle 15: Hello Whirled Puzzle 16: Line Printer Puzzle 17: Huh? Puzzle 18: String Cheese Puzzle 19: Classy Fire Puzzle 20: What's My Class? Puzzle 21: What's My Class, Take 2 Puzzle 22: Dupe of URL Puzzle 23: No Pain, No Gain Chapter 4. Loopy Puzzlers Puzzle 24: A Big Delight in Every Byte Puzzle 25: Inclement Increment Puzzle 26: In the Loop Puzzle 27: Shifty i's Puzzle 28: Looper Puzzle 29: Bride of Looper Puzzle 30: Son of Looper Puzzle 31: Ghost of Looper Puzzle 32: Curse of Looper Puzzle 33: Looper Meets the Wolfman Puzzle 34: Down for the Count Puzzle 35: Minute by Minute Chapter 5. Exceptional Puzzlers Puzzle 36: Indecision Puzzle 37: Exceptionally Arcane Puzzle 38: The Unwelcome Guest Puzzle 39: Hello, Goodbye Puzzle 40: The Reluctant Constructor Puzzle 41: Field and Stream Puzzle 42: Thrown for a Loop Puzzle 43: Exceptionally Unsafe Puzzle 44: Cutting Class Puzzle 45: Exhausting Workout Chapter 6. Classy Puzzlers Puzzle 46: The Case of the Confusing Constructor Puzzle 47: Well, Dog My Cats! Puzzle 48: All I Get Is Static Puzzle 49: Larger Than Life Puzzle 50: Not Your Type Puzzle 51: What's the Point? Puzzle 52: Sum Fun Puzzle 53: Do Your Thing Puzzle 54: Null and Void Puzzle 55: Creationism Chapter 7. Library Puzzlers Puzzle 56: Big Problem Puzzle 57: What's in a Name? Puzzle 58: Making a Hash of It Puzzle 59: What's the Difference? Puzzle 60: One-Liners Puzzle 61: The Dating Game Puzzle 62: The Name Game Puzzle 63: More of the Same Puzzle 64: The Mod Squad Puzzle 65: A Strange Saga of a Suspicious Sort Chapter 8. Classier Puzzlers Puzzle 66: A Private Matter Puzzle 67: All Strung Out Puzzle 68: Shades of Gray Puzzle 69: Fade to Black Puzzle 70: Package Deal Puzzle 71: Import Duty Puzzle 72: Final Jeopardy Puzzle 73: Your Privates Are Showing Puzzle 74: Identity Crisis Puzzle 75: Heads or Tails? A Glossary of Name Reuse Chapter 9. More Library Puzzlers Puzzle 76: Ping Pong Puzzle 77: The Lock Mess Monster Puzzle 78: Reflection Infection Puzzle 79: It's a Dog's Life Puzzle 80: Further Reflection Puzzle 81: Charred Beyond Recognition Puzzle 82: Beer Blast Puzzle 83: Dyslexic Monotheism Puzzle 84: Rudely Interrupted Puzzle 85: Lazy Initialization Chapter 10. Advanced Puzzlers Puzzle 86: Poison-Paren Litter Puzzle 87: Strained Relations Puzzle 88: Raw Deal Puzzle 89: Generic Drugs Puzzle 90: It's Absurd, It's a Pain, It's Superclass! Puzzle 91: Serial Killer Puzzle 92: Twisted Pair Puzzle 93: Class Warfare Puzzle 94: Lost in the Shuffle Puzzle 95: Just Desserts Appendix A. Catalog of Traps and Pitfalls 1. Lexical Issues 2. Integer Arithmetic 3. Floating-Point Arithmetic 4. Expression Evaluation 5. Flow of Control 6. Class Initialization 7. Instance Creation and Destruction 8. Other Class- and Instance-Related Topics 9. Name Reuse 10. Strings 11. I/O 12. Threads 13. Reflection 14. Serialization 15. Other Libraries Appendix B. Notes on the IllusionsAmbiguous Figures Impossible Figures Geometrical Illusions: Size Geometrical Illusions: Direction Subjective Contours Anomalous Motion Illusions Illusions of Lightness Compound Illusions

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值