Java Gotcha's By Rick Mercer with help from the book:

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Shlomo Hershkop1 Introduction to java Class 1 Fall 2003 Shlomo Hershkop.
Introduction to Computers and Programming Lecture 7:
Introduction to Computers and Programming Lecture 7:
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Mathematical Operators: working with floating point numbers and more operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this.
Review… Yong Choi BPA CSUB. Access Modifier public class HelloWorldApp –More detailes of Java key (reserved) wordJava key (reserved) word –The keyword,
Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
16-Aug-15 Java Puzzlers From the book Java Puzzlers by Joshua Bloch and Neal Gafter.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Introduction to Java. Main() Main method is where the program execution begins. There is only one main Displaying the results: System.out.println (“Hi.
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
JAVA PROGRAMMING PART II.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
Chapter 3: Data Types and Operators JavaScript - Introductory.
CSC 204 Programming I Loop I The while statement.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
1 Advanced Programming IF. 2 Control Structures Program of control –Program performs one statement then goes to next line Sequential execution –Different.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
1 Operations Making Things Happen (Chap. 3) Expressions.
Primitive data Week 3. Lecture outcomes Primitive data – integer – double – string – char – Float – Long – boolean Declaration Initialisation Assignments.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
1 Java Gotcha's Most of these examples are from this book: Java™ Puzzlers: Traps, Pitfalls, and Corner Cases Author(s): Joshua Bloch and Neal Gafter Publisher:
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs -
Apr, 2011 Dating with Java Larry Li. Objective Hello world program Setup development environment Data types and variables Operators and Expressions Control.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
COMP Primitive and Class Types Yi Hong May 14, 2015.
The assignment expressions. The assignment operator in an assignment statement We have seen the assignment statement: Effect: var = expr; Stores the value.
Operators in JAVA. Operator An operator is a symbol that operates on one or more arguments to produce a result. Java provides a rich set of operators.
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
© A+ Computer Science - A reference variable stores the memory address of an object. Monster fred = new Monster(); Monster sally.
Variables and Types Java Part 3. Class Fields  Aka member variable, field variable, instance variable, class variable.  These are the descriptors of.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
1 Advanced Programming IF. 2 Control Structures Program of control –Program performs one statement then goes to next line Sequential execution –Different.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
A data type in a programming language is a set of data with values having predefined characteristics.data The language usually specifies:  the range.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Programming Principles Operators and Expressions.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
 Array ◦ Single & Multi-dimensional  Java Operators ◦ Assignment ◦ Arithmetic ◦ Relational ◦ Logical ◦ Bitwise & other.
Structured Programming Structured Programming is writing a program in terms of only 3 basic control structures: sequence selection repetition We have already.
Asserting Java © Rick Mercer Chapter 7 The Java Array Object.
Object Oriented Programming Lecture 2: BallWorld.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
CompSci 230 S Programming Techniques
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Selections Java.
Operators and Expressions
An Introduction to Java – Part I, language basics
Problem 1 Given n, calculate 2n
Presentation transcript:

Java Gotcha's By Rick Mercer with help from the book: Java™ Puzzlers: Traps, Pitfalls, and Corner Cases Joshua Bloch and Neal Gafter

Every programming language has its quirks. Are you a code sleuth? Have you ever spent days chasing a bug caused by a trap or pitfall in Java or its libraries? Here are some diabolical puzzles

Oddity // Does this method return true if n is odd? public boolean isOdd(int n) { return n % 2 == 1; }

Ö Yes, but it's wrong when n is negative // Try this return n % 2 != 0; // or use bitwise AND operation (faster) return (n & 1) == 1; // n & 1 ands the rightmost bit with 1 // if n is 25, n & 1 is 1 // 00011001 & 00000001 is 00000001 // Expression is 0 unless n is odd // if n is 24, n & 1 is 0 // 00011000 & 00000001 is 00000000

Simple Arithmetic @Test public void simpleArithmetic() { // Does this assertion pass? assertEquals(444, 123 + 32l); }

Ö Eyes Deceive It is 123 + 32L, which is 155 Use L instead of l for Long

The laughs are on me @Test public void simpleChars() { // Which, if any, of these two assertions pass? assertEquals("Ha", "H" + "a"); // a. assertEquals("Ha", 'H' + 'a'); // b. }

Ö Answer Only a. java.lang.AssertionError: expected:<Ha> but was:<169>

Operator Precedence @Test public void stringIntern() { String pig = "length: 10"; String dog = "length: " + pig.length(); // Which, if any, of these two assertions pass? assertEquals("Animals equal: false", "Animals equal: " + pig == dog); assertEquals("Animals equal: true", }

Ö Neither. Precedence rules have + evaluating before ==. The actual value (2nd arg to assert) is "Animals equal: " + pig == dog which evaluates to "Animals equal: pig" == dog which as an argument evaluates to false assertEquals uses the equals method when the type do not match, equals returns false "string".equals(true) is false These asssertions pass assertEquals("Animals equal: false", "Animals equal: " + (pig == dog)); assertEquals("Animals equal: true", "Animals equal: " + (pig.equals(dog)));

From a 227 Student Can this recursive solution ever work? // Part of escape obstacle course in findExit if(escape = false) findExit(r-1, c); // row above findExit(r, c+1); // col to the right Can this recursive solution ever work?

Ö No The boolean expressions are ALWAYS false An assignment statement evaluates to the value of the right value (expression to the right of =) What is the value of booleanVar = true

From a 127B Student Can this recursive solution ever work? @Test public void testRecursion() { assertEquals(6, sumInts(3)); } int sumInts(int n) { if(n <= 1) return n; else return n * sumInts(n--); Can this recursive solution ever work?

Ö No n is not decremented until after the function call Use f(n-1) f(n--) results in a StackOverflowError Use f(n-1)

Output from this program? \u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020\u0020 \u0063\u006c\u0061\u0073\u0073\u0020\u0055\u0067\u006c\u0079 \u007b\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020 \u0020\u0020\u0020\u0020\u0073\u0074\u0061\u0074\u0069\u0063 \u0076\u006f\u0069\u0064\u0020\u006d\u0061\u0069\u006e\u0028 \u0053\u0074\u0072\u0069\u006e\u0067\u005b\u005d\u0020\u0020 \u0020\u0020\u0020\u0020\u0061\u0072\u0067\u0073\u0029\u007b \u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074 \u002e\u0070\u0072\u0069\u006e\u0074\u006c\u006e\u0028\u0020 \u0022\u0048\u0065\u006c\u006c\u006f\u0020\u0077\u0022\u002b \u0022\u006f\u0072\u006c\u0064\u0022\u0029\u003b\u007d\u007d

Ö Answer: Unicode not very readable Hello World \u0070 in hexadecimal is 112 in decimal or the character 'p' Unicode not very readable Suggestion" avoid Unicode till you need it System.out.println(123.45 + " \u20ac" ); 123.45 €

assertEquals('@', '\u0040'); assertEquals('A', '\u0041'); assertEquals('B', '\u0042'); assertEquals('`', '\u0060'); assertEquals('a', '\u0061'); assertEquals('b', '\u0062'); assertEquals('€', '\u20ac');

Is “true” true? @Test public void trueOr() { // Does this assertion pass? assertEquals("Compare 5 to 4", "true", 5 > 4); }

Ö Answer "true" is not true However, JUnit show this: No java.lang.AssertionError: Compare 5 to 4 expected:<true> but was:<true>

Output? @Test public void whoopsForgotToBreak() { int choice = 2; switch (choice) { case 1: System.out.println("one"); case 2: System.out.println("two"); case 3: System.out.println("three"); }

Ö Add breaks two three int choice = 2; switch (choice) { case 1: System.out.println("one"); break; case 2: System.out.println("two"); case 3: System.out.println("three"); }

BTW: Java 7 allows String in a switch statement String choice = "2"; switch (choice) { case "1": System.out.println("one"); break; case "2": System.out.println("two"); case "3": System.out.println("three"); }

Java plus plus @Test public void thatDarnedPostIncrement() { int j = 0; for (int i = 0; i < 10; i++) j = j++; // Does this assertion pass? assertEquals(10, j); }

Ö Answer: No Use ++j; instead j = j++; is postfix increment operator j is 0 after the loop When you use a postfix operator as part of a larger expression, the expression's value is returned before the postfix operator is processed the assignment completes before the increment Use ++j; instead

Output? int j = 0; int k = 0; System.out.println(j++); //? _____ System.out.println(++k); //? _____ System.out.println(j); //? _____ int[] x = { 5, 4, 3 }; int i = 0; System.out.println(i + " " + x[i++]); //? _____ System.out.println(i + " " + x[i]); //? _____ System.out.println(i + " " + x[++i]); //? _____

O 0 1 With array 0 5 1 4 1 3

Is there any Output? public class Huh { public static void main(String[] args) { new B(); } class B { int j; String s; { System.out.println("Hello world " + j + " " + s);

Ö Answer: Yes This is an initializer, a method with no heading; { } Hello world 0 null This is an initializer, a method with no heading; { }

Add to 0 three times @Test public void testBigInt() { BigInteger five = new BigInteger("5"); BigInteger fifty = new BigInteger("50"); BigInteger fiveHundred = new BigInteger("500"); BigInteger total = BigInteger.ZERO; total.add(five); total.add(fifty); total.add(fiveHundred); // Does this assertion pass? assertEquals(555, total); }

Ö No BigInteger, like String is immutable This will pass BigInteger total = BigInteger.ZERO; total = total.add(five); total = total.add(fifty); total = total.add(fiveHundred); // Does this assertion pass assertEquals(555, total);

No Warning @Test public void testHashMap() { HashMap<String, BigInteger> hm = new HashMap<String, BigInteger>(); hm.put("a", new BigInteger("123456")); hm.put("b", new BigInteger("1234567")); hm.put("c", new BigInteger("1234567")); hm.put("a", new BigInteger("654321")); BigInteger aBigInt = hm.get("a"); // Does this assertion pass? assertEquals(123456, aBigInt.intValue()); }

Ö No, the first mapping was destroyed // Return old value if the key exists // return null if there was no mapping to the key hm.put("a", new BigInteger("123456")); BigInteger bi = hm.put("a", new BigInteger("9999")); // put returned the old value mapped to the key "a" assertEquals(123456, bi.intValue());

Output? int n = 0; try { n = n / 0; } catch (Exception e) { System.out.println("A"); } finally { System.out.println("B"); } System.out.println("C");

Ö A B C Finally blocks always execute unless System.exit(0) is encountered first

Output? int n = 0; try { n = n / 999; } catch (Exception e) { System.out.println("A"); } finally { System.out.println("B"); } System.out.println("C");

Ö B C

Output int n = 0; try { n = n / 999; } catch (Exception e) { System.out.println("A"); System.exit(0); } finally { System.out.println("B"); } System.out.println("C");

Ö B C

Output int n = 0; try { n = n / 0; } catch (Exception e) { System.out.println("A"); System.exit(0); } finally { System.out.println("B"); } System.out.println("C");

Ö A

To intern or not to intern String data = new String("123"); String moreData = new String("123"); System.out.println(data==moreData); To intern or not to intern Which assertion(s) pass? 1 and 2 1 only 2 only Neither @Test public void stringIntern() { String s1 = "UofA"; String s2 = new String("UofA"); assertTrue(s1.equals(s2)); // 1 assertTrue(s1 == s2); // 2 }

Ö b) 1 only == compares reference values, with new, a new string is created. Without new, Java tries to find the characters in the string pool where all instances of String are stored. If found, Java returns a reference to the existing instance In Java, String is a Flyweight to save memory Both of these assertions pass: String s1 = "UofA"; String s2 = "UofA"; assertTrue(s1.equals(s2)); // 1 assertTrue(s1 == s2); // 2

To intern or not to intern @Test public void testIntegerInterns() { Integer a = -128; Integer b = -128; Integer c = 127; Integer d = 127; Integer e = 345; Integer f = 345; // Which, if any, of these assertions fail? assertTrue(a == b); // a. assertTrue(c == d); // b. assertTrue(e >= f); // c. assertTrue(e == f); // d. }

Ö d only == compares reference values so you would think all 3 fail, but.... java.sun.com/docs/books/jls/download/langspec-3.0.pdf explicitly states that wrappers for values in the range -128 to 127 will be interned by any JVM. If you use the int literal, you get a reference to that existing instance Flyweight: Do not create a new Integer(1), just return a reference to that instance from the existing pool of Integers -128..127 to save memory

Are Doubles interned? @Test public void testEqualEquals() { Double a = 4.2; Double b = 4.2; // Which, if any, of these assertions fail? assertTrue(a >= b); // a. assertTrue(a <= b); // b. assertTrue(a.equals(b)); // c. assertTrue(a == b); // d. assertTrue(a.compareTo(b) == 0); // e. assertTrue(a.compareTo(4.2) == 0); // f. }

Ö The == compares reference values, not the numeric values assertTrue(a == b); // d. fails The == compares reference values, not the numeric values Why does a == b evaluate to false? There is no Double pool a and b refer to two different objects with the same value == compares references, not the 4.2s