SlideShare a Scribd company logo
1 of 27
Download to read offline
Introduction - what this is about 
Puzzles in java are those situations where the code is broken and 
you are tricked by some API or the language itself. 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Introduction - what this is about 
Puzzles in java are those situations where the code is broken and 
you are tricked by some API or the language itself. 
Those were started mostly by Joch Bloch and there even a 
book(some of the examples are taken from there) 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Introduction - what this is about 
Puzzles in java are those situations where the code is broken and 
you are tricked by some API or the language itself. 
Those were started mostly by Joch Bloch and there even a 
book(some of the examples are taken from there) 
Want it to be interactive 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Awards as I think you will be lazy 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
SplittingSizes 
public class RegexSplit { 
public static void main(String[] args) { 
String[] nothing = "".split(":"); 
String[] bunchOfNothing = ":".split(":"); 
System.out.printf("%d|%d%n", nothing.length, 
bunchOfNothing.length); 
} 
} 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
SplittingSizes 
public class RegexSplit { 
Answers 
(a) 1j2 
(b) 1j0 
(c) 0j2 
(d) Throws an exception 
(e) None of the above 
public static void main(String[] args) { 
String[] nothing = "".split(":"); 
String[] bunchOfNothing = ":".split(":"); 
System.out.printf("%d|%d%n", nothing.length, 
bunchOfNothing.length); 
} 
} 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
SplittingSizes 
public class RegexSplit { 
Answers 
(a) 1j2 
(b) 1j0 - Explanation follows. . . 
(c) 0j2 
(d) Throws an exception 
(e) None of the above 
public static void main(String[] args) { 
String[] nothing = "".split(":"); 
String[] bunchOfNothing = ":".split(":"); 
System.out.printf("%d|%d%n", nothing.length, 
bunchOfNothing.length); 
} 
} 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
If you navigate through the source for String.split, you’ll discover 
that str.split(":") is effectively the same as 
Pattern.compile(":").split(str, 0). 
so. . . lets look there: 
Pattern.split(Charsequence, int): 
If this pattern does not match any subsequence of the input 
then the resulting array has just one element, namely the 
input sequence in string form. 
If n is zero then the pattern will be applied as many times as 
possible, the array can have any length, and trailing empty 
strings will be discarded. [ emphasis added. ] 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Joy of sets 
import java.net.*; 
public class UrlSet { 
private static final String[] URL_NAMES = { 
"http://javapuzzlers.com", 
"http://www.summerartcircle.com", 
"http://www.google.com", 
"http://javapuzzlers.com", 
"http://findbugs.sourceforge.net", 
"http://www.cs.umd.edu" 
}; 
public static void main(String[] args) throws Exception { 
Set<URL> favourites = new HashSet<URL>(); 
for (String urlName : URL_NAMES){ 
favourites.add(new URL(urlName)); 
} 
System.out.println(favourites.size()); 
} 
} 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Joy of sets 
import java.net.*; 
public class UrlSet { 
Answers 
(a) 4 
(b) 5 
(c) Throws an exception 
(d) None of the above 
private static final String[] URL_NAMES = { 
"http://javapuzzlers.com", 
"http://www.summerartcircle.com", 
"http://www.google.com", 
"http://javapuzzlers.com", 
"http://findbugs.sourceforge.net", 
"http://www.cs.umd.edu" 
}; 
public static void main(String[] args) throws Exception { 
Set<URL> favourites = new HashSet<URL>(); 
for (String urlName : URL_NAMES){ 
favourites.add(new URL(urlName)); 
} 
System.out.println(favourites.size()); 
} 
} 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Joy of sets 
import java.net.*; 
public class UrlSet { 
Answers 
(a) 4 (assuming you are connected 
private static final String[] URL_NAMES = { 
to the net) 
"http://javapuzzlers.com", 
"http://www.summerartcircle.com", 
"http://www.google.com", 
"http://javapuzzlers.com", 
"http://findbugs.sourceforge.net", 
"http://www.cs.umd.edu" 
(b) 5 
(c) Throws an exception 
(d) None of the above - it varies 
from run to run 
}; 
public static void main(String[] args) throws Exception { 
Set<URL> favourites = new HashSet<URL>(); 
for (String urlName : URL_NAMES){ 
favourites.add(new URL(urlName)); 
} 
System.out.println(favourites.size()); 
} 
} 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
URL equals and hashCode are broken! 
Two URL objects are equal if they have the same protocol, reference 
equivalent hosts, have the same port number on the host, and the 
same file and fragment of the file. 
Two hosts are considered equivalent if both host names can be 
resolved into the same IP addresses; else if either host name can’t be 
resolved, the host names must be equal without regard to case; or 
both host names equal to null. 
Since hosts comparison requires name resolution, this operation is a 
blocking operation. 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Another look 
public class Histogram { 
private static final String[] words = { "I", "recommend", 
"polygene", "lubricants" }; 
public static void main(String[] args) { 
int[] histogram = new int[5]; 
for (String word1 : words) { 
for (String word2 : words) { 
String pair = word1 + word2; 
int bucket = Math.abs(pair.hashCode()) 
% histogram.length; 
histogram[bucket]++; 
} 
} 
int pairCount = 0; 
for (int freq : histogram) { 
pairCount += freq; 
} 
System.out.println(’C’ + pairCount); 
} 
} 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Another look 
public class Histogram { 
Answers 
(a) 83 
(b) C16 
(c) S 
(d) None of the above 
private static final String[] words = { "I", "recommend", 
"polygene", "lubricants" }; 
public static void main(String[] args) { 
int[] histogram = new int[5]; 
for (String word1 : words) { 
for (String word2 : words) { 
String pair = word1 + word2; 
int bucket = Math.abs(pair.hashCode()) 
% histogram.length; 
histogram[bucket]++; 
} 
} 
int pairCount = 0; 
for (int freq : histogram) { 
pairCount += freq; 
} 
System.out.println(’C’ + pairCount); 
} 
} 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Another look 
public class Histogram { 
Answers 
(a) 83 
(b) C16 
(c) S 
(d) None of the above - throws 
private static final String[] words = { "I", "recommend", 
"polygene", "lubricants" }; 
public static void main(String[] args) { 
int[] histogram = new int[5]; 
for (String word1 : words) { 
for (String word2 : words) { 
ArrayOutOfBoundsException 
String pair = word1 + word2; 
int bucket = Math.abs(pair.hashCode()) 
% histogram.length; 
histogram[bucket]++; 
} 
} 
int pairCount = 0; 
for (int freq : histogram) { 
pairCount += freq; 
} 
System.out.println(’C’ + pairCount); 
} 
} 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Math.abs(int) can return a negative number, and so can the % 
operator 
The hashcode of “polygenelubricants” is actually 
Integer.MIN_VALUE i.e. 
"polygenelubricants".hashCode() == Integer.MIN_VALUE 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Long division 
public class LongDivision { 
public static void main(String[] args) { 
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000; 
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000; 
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY); 
} 
} 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Long division 
public class LongDivision { 
public static void main(String[] args) { 
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000; 
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000; 
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY); 
} 
} 
Answers 
(a) 0 
(b) 5 
(c) 1000 
(d) Throws an exception 
(e) None of the above 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Long division answer 
public class LongDivision { 
public static void main(String[] args) { 
//Multiplication is not with long numbers! 
final long MICROS_PER_DAY = 24L * 60 * 60 * 1000 * 1000; 
final long MILLIS_PER_DAY = 24L * 60 * 60 * 1000; 
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY); 
} 
} 
Answers 
(a) 0 
(b) 5 - not actually long division 
(c) 1000 
(d) Throws an exception 
(e) None of the above 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
The Dating Game 
import java.util.*; 
public class DatingGame { 
public static void main(String[] args) { 
Calendar cal = Calendar.getInstance(); 
cal.set(1999, 12, 31); // Year, Month, Day 
System.out.print(cal.get(Calendar.YEAR) + " "); 
Date d = cal.getTime(); 
System.out.print(d.getDay() + " "); 
System.out.println(cal.get(Calendar.DAY_OF_MONTH)); 
} 
} 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
The Dating Game 
import java.util.*; 
public class DatingGame { 
Answers 
(a) 1999 31 31 
(b) 1999 31 1 
(c) 2000 1 31 
(d) 2000 31 31 
(e) None of the above 
public static void main(String[] args) { 
Calendar cal = Calendar.getInstance(); 
cal.set(1999, 12, 31); // Year, Month, Day 
System.out.print(cal.get(Calendar.YEAR) + " "); 
Date d = cal.getTime(); 
System.out.print(d.getDay() + " "); 
System.out.println(cal.get(Calendar.DAY_OF_MONTH)); 
} 
} 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
The Dating Game 
import java.util.*; 
public class DatingGame { 
Answers 
(a) 1999 31 31 
(b) 1999 31 1 
(c) 2000 1 31 - maybe the Y2K 
public static void main(String[] args) { 
Calendar cal = Calendar.getInstance(); 
cal.set(1999, 12, 31); // Year, Month, Day 
System.out.print(cal.get(Calendar.YEAR) + " "); 
Date d = cal.getTime(); 
System.out.print(d.getDay() + " "); 
System.out.println(cal.get(Calendar.DAY_OF_MONTH)); 
} 
} 
problem? 
(d) 2000 31 31 
(e) None of the above 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
The Dating Game - answer 
When the Java platform was first released, its only support for 
calendar calculations was the Date class. This class was limited in 
power, especially when it came to support for internationalization, and 
it had a basic design flaw: Date instances were mutable. In release 
1.1, the Calendar class was added to the platform to rectify the 
shortcomings of Date; most Date methods were deprecated. 
Unfortunately, this only made a bad situation worse. 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
The Dating Game - answer 
When the Java platform was first released, its only support for 
calendar calculations was the Date class. This class was limited in 
power, especially when it came to support for internationalization, and 
it had a basic design flaw: Date instances were mutable. In release 
1.1, the Calendar class was added to the platform to rectify the 
shortcomings of Date; most Date methods were deprecated. 
Unfortunately, this only made a bad situation worse. 
The program just illustrates some of the shortcomings in the current 
API. The Calendar doesn’t warn us when it overflows and the months 
start the count from 0 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
The Dating Game - answer 
When the Java platform was first released, its only support for 
calendar calculations was the Date class. This class was limited in 
power, especially when it came to support for internationalization, and 
it had a basic design flaw: Date instances were mutable. In release 
1.1, the Calendar class was added to the platform to rectify the 
shortcomings of Date; most Date methods were deprecated. 
Unfortunately, this only made a bad situation worse. 
The program just illustrates some of the shortcomings in the current 
API. The Calendar doesn’t warn us when it overflows and the months 
start the count from 0 
Use Joda Time which will be included in java8. . . 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Some comments and references 
Use Sonar which will catch some of the problems from this 
presentation with the findbugs plugin 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
Some comments and references 
Use Sonar which will catch some of the problems from this 
presentation with the findbugs plugin 
Clickable links: 
Advanced Topics in Programming Languages: Java Puzzlers 
Java-Puzzlers InfoQ 
Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls

More Related Content

What's hot

QA Auotmation Java programs,theory
QA Auotmation Java programs,theory QA Auotmation Java programs,theory
QA Auotmation Java programs,theory archana singh
 
Effective Java with Groovy
Effective Java with GroovyEffective Java with Groovy
Effective Java with GroovyNaresha K
 
Les nouveautés de C# 6
Les nouveautés de C# 6Les nouveautés de C# 6
Les nouveautés de C# 6Microsoft
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIjagriti srivastava
 
Java practical(baca sem v)
Java practical(baca sem v)Java practical(baca sem v)
Java practical(baca sem v)mehul patel
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance PuzzlersDoug Hawkins
 
JVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksJVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksDoug Hawkins
 
Next Generation Developer Testing: Parameterized Testing
Next Generation Developer Testing: Parameterized TestingNext Generation Developer Testing: Parameterized Testing
Next Generation Developer Testing: Parameterized TestingTao Xie
 
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...Flink Forward
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in JavaDoug Hawkins
 
Introduction to julia
Introduction to juliaIntroduction to julia
Introduction to julia岳華 杜
 
COSCUP: Introduction to Julia
COSCUP: Introduction to JuliaCOSCUP: Introduction to Julia
COSCUP: Introduction to Julia岳華 杜
 
Computer java programs
Computer java programsComputer java programs
Computer java programsADITYA BHARTI
 
Works Applications Test - Chinmay Chauhan
Works Applications Test - Chinmay ChauhanWorks Applications Test - Chinmay Chauhan
Works Applications Test - Chinmay ChauhanChinmay Chauhan
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsBaruch Sadogursky
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)Alok Kumar
 

What's hot (20)

Chapter 4 - Classes in Java
Chapter 4 - Classes in JavaChapter 4 - Classes in Java
Chapter 4 - Classes in Java
 
QA Auotmation Java programs,theory
QA Auotmation Java programs,theory QA Auotmation Java programs,theory
QA Auotmation Java programs,theory
 
Effective Java with Groovy
Effective Java with GroovyEffective Java with Groovy
Effective Java with Groovy
 
Les nouveautés de C# 6
Les nouveautés de C# 6Les nouveautés de C# 6
Les nouveautés de C# 6
 
JVM Mechanics
JVM MechanicsJVM Mechanics
JVM Mechanics
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Java practical(baca sem v)
Java practical(baca sem v)Java practical(baca sem v)
Java practical(baca sem v)
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance Puzzlers
 
Mutation @ Spotify
Mutation @ Spotify Mutation @ Spotify
Mutation @ Spotify
 
JVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksJVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's Tricks
 
Next Generation Developer Testing: Parameterized Testing
Next Generation Developer Testing: Parameterized TestingNext Generation Developer Testing: Parameterized Testing
Next Generation Developer Testing: Parameterized Testing
 
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...
 
Clojure class
Clojure classClojure class
Clojure class
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
 
Introduction to julia
Introduction to juliaIntroduction to julia
Introduction to julia
 
COSCUP: Introduction to Julia
COSCUP: Introduction to JuliaCOSCUP: Introduction to Julia
COSCUP: Introduction to Julia
 
Computer java programs
Computer java programsComputer java programs
Computer java programs
 
Works Applications Test - Chinmay Chauhan
Works Applications Test - Chinmay ChauhanWorks Applications Test - Chinmay Chauhan
Works Applications Test - Chinmay Chauhan
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 

Similar to Java puzzles

Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Ayes Chinmay
 
Top 20 java programming interview questions for sdet
Top 20 java programming interview questions for sdetTop 20 java programming interview questions for sdet
Top 20 java programming interview questions for sdetDevLabs Alliance
 
Fnt software solutions placement paper
Fnt software solutions placement paperFnt software solutions placement paper
Fnt software solutions placement paperfntsofttech
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages VictorSzoltysek
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - StockholmJan Kronquist
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Cody Engel
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Víctor Bolinches
 
java 8 Hands on Workshop
java 8 Hands on Workshopjava 8 Hands on Workshop
java 8 Hands on WorkshopJeanne Boyarsky
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
Inheritance and-polymorphism
Inheritance and-polymorphismInheritance and-polymorphism
Inheritance and-polymorphismUsama Malik
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 

Similar to Java puzzles (20)

Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
Top 20 java programming interview questions for sdet
Top 20 java programming interview questions for sdetTop 20 java programming interview questions for sdet
Top 20 java programming interview questions for sdet
 
Fnt software solutions placement paper
Fnt software solutions placement paperFnt software solutions placement paper
Fnt software solutions placement paper
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
sample_midterm.pdf
sample_midterm.pdfsample_midterm.pdf
sample_midterm.pdf
 
Poly-paradigm Java
Poly-paradigm JavaPoly-paradigm Java
Poly-paradigm Java
 
Java oops features
Java oops featuresJava oops features
Java oops features
 
7
77
7
 
Java Quiz Questions
Java Quiz QuestionsJava Quiz Questions
Java Quiz Questions
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
Pattern Matching in Java 14
Pattern Matching in Java 14Pattern Matching in Java 14
Pattern Matching in Java 14
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
java 8 Hands on Workshop
java 8 Hands on Workshopjava 8 Hands on Workshop
java 8 Hands on Workshop
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Inheritance and-polymorphism
Inheritance and-polymorphismInheritance and-polymorphism
Inheritance and-polymorphism
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 

Recently uploaded

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 

Recently uploaded (20)

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Java puzzles

  • 1. Introduction - what this is about Puzzles in java are those situations where the code is broken and you are tricked by some API or the language itself. Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 2. Introduction - what this is about Puzzles in java are those situations where the code is broken and you are tricked by some API or the language itself. Those were started mostly by Joch Bloch and there even a book(some of the examples are taken from there) Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 3. Introduction - what this is about Puzzles in java are those situations where the code is broken and you are tricked by some API or the language itself. Those were started mostly by Joch Bloch and there even a book(some of the examples are taken from there) Want it to be interactive Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 4. Awards as I think you will be lazy Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 5. SplittingSizes public class RegexSplit { public static void main(String[] args) { String[] nothing = "".split(":"); String[] bunchOfNothing = ":".split(":"); System.out.printf("%d|%d%n", nothing.length, bunchOfNothing.length); } } Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 6. SplittingSizes public class RegexSplit { Answers (a) 1j2 (b) 1j0 (c) 0j2 (d) Throws an exception (e) None of the above public static void main(String[] args) { String[] nothing = "".split(":"); String[] bunchOfNothing = ":".split(":"); System.out.printf("%d|%d%n", nothing.length, bunchOfNothing.length); } } Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 7. SplittingSizes public class RegexSplit { Answers (a) 1j2 (b) 1j0 - Explanation follows. . . (c) 0j2 (d) Throws an exception (e) None of the above public static void main(String[] args) { String[] nothing = "".split(":"); String[] bunchOfNothing = ":".split(":"); System.out.printf("%d|%d%n", nothing.length, bunchOfNothing.length); } } Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 8. If you navigate through the source for String.split, you’ll discover that str.split(":") is effectively the same as Pattern.compile(":").split(str, 0). so. . . lets look there: Pattern.split(Charsequence, int): If this pattern does not match any subsequence of the input then the resulting array has just one element, namely the input sequence in string form. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded. [ emphasis added. ] Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 9. Joy of sets import java.net.*; public class UrlSet { private static final String[] URL_NAMES = { "http://javapuzzlers.com", "http://www.summerartcircle.com", "http://www.google.com", "http://javapuzzlers.com", "http://findbugs.sourceforge.net", "http://www.cs.umd.edu" }; public static void main(String[] args) throws Exception { Set<URL> favourites = new HashSet<URL>(); for (String urlName : URL_NAMES){ favourites.add(new URL(urlName)); } System.out.println(favourites.size()); } } Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 10. Joy of sets import java.net.*; public class UrlSet { Answers (a) 4 (b) 5 (c) Throws an exception (d) None of the above private static final String[] URL_NAMES = { "http://javapuzzlers.com", "http://www.summerartcircle.com", "http://www.google.com", "http://javapuzzlers.com", "http://findbugs.sourceforge.net", "http://www.cs.umd.edu" }; public static void main(String[] args) throws Exception { Set<URL> favourites = new HashSet<URL>(); for (String urlName : URL_NAMES){ favourites.add(new URL(urlName)); } System.out.println(favourites.size()); } } Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 11. Joy of sets import java.net.*; public class UrlSet { Answers (a) 4 (assuming you are connected private static final String[] URL_NAMES = { to the net) "http://javapuzzlers.com", "http://www.summerartcircle.com", "http://www.google.com", "http://javapuzzlers.com", "http://findbugs.sourceforge.net", "http://www.cs.umd.edu" (b) 5 (c) Throws an exception (d) None of the above - it varies from run to run }; public static void main(String[] args) throws Exception { Set<URL> favourites = new HashSet<URL>(); for (String urlName : URL_NAMES){ favourites.add(new URL(urlName)); } System.out.println(favourites.size()); } } Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 12. URL equals and hashCode are broken! Two URL objects are equal if they have the same protocol, reference equivalent hosts, have the same port number on the host, and the same file and fragment of the file. Two hosts are considered equivalent if both host names can be resolved into the same IP addresses; else if either host name can’t be resolved, the host names must be equal without regard to case; or both host names equal to null. Since hosts comparison requires name resolution, this operation is a blocking operation. Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 13. Another look public class Histogram { private static final String[] words = { "I", "recommend", "polygene", "lubricants" }; public static void main(String[] args) { int[] histogram = new int[5]; for (String word1 : words) { for (String word2 : words) { String pair = word1 + word2; int bucket = Math.abs(pair.hashCode()) % histogram.length; histogram[bucket]++; } } int pairCount = 0; for (int freq : histogram) { pairCount += freq; } System.out.println(’C’ + pairCount); } } Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 14. Another look public class Histogram { Answers (a) 83 (b) C16 (c) S (d) None of the above private static final String[] words = { "I", "recommend", "polygene", "lubricants" }; public static void main(String[] args) { int[] histogram = new int[5]; for (String word1 : words) { for (String word2 : words) { String pair = word1 + word2; int bucket = Math.abs(pair.hashCode()) % histogram.length; histogram[bucket]++; } } int pairCount = 0; for (int freq : histogram) { pairCount += freq; } System.out.println(’C’ + pairCount); } } Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 15. Another look public class Histogram { Answers (a) 83 (b) C16 (c) S (d) None of the above - throws private static final String[] words = { "I", "recommend", "polygene", "lubricants" }; public static void main(String[] args) { int[] histogram = new int[5]; for (String word1 : words) { for (String word2 : words) { ArrayOutOfBoundsException String pair = word1 + word2; int bucket = Math.abs(pair.hashCode()) % histogram.length; histogram[bucket]++; } } int pairCount = 0; for (int freq : histogram) { pairCount += freq; } System.out.println(’C’ + pairCount); } } Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 16. Math.abs(int) can return a negative number, and so can the % operator The hashcode of “polygenelubricants” is actually Integer.MIN_VALUE i.e. "polygenelubricants".hashCode() == Integer.MIN_VALUE Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 17. Long division public class LongDivision { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000; final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000; System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY); } } Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 18. Long division public class LongDivision { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000; final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000; System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY); } } Answers (a) 0 (b) 5 (c) 1000 (d) Throws an exception (e) None of the above Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 19. Long division answer public class LongDivision { public static void main(String[] args) { //Multiplication is not with long numbers! final long MICROS_PER_DAY = 24L * 60 * 60 * 1000 * 1000; final long MILLIS_PER_DAY = 24L * 60 * 60 * 1000; System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY); } } Answers (a) 0 (b) 5 - not actually long division (c) 1000 (d) Throws an exception (e) None of the above Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 20. The Dating Game import java.util.*; public class DatingGame { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); cal.set(1999, 12, 31); // Year, Month, Day System.out.print(cal.get(Calendar.YEAR) + " "); Date d = cal.getTime(); System.out.print(d.getDay() + " "); System.out.println(cal.get(Calendar.DAY_OF_MONTH)); } } Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 21. The Dating Game import java.util.*; public class DatingGame { Answers (a) 1999 31 31 (b) 1999 31 1 (c) 2000 1 31 (d) 2000 31 31 (e) None of the above public static void main(String[] args) { Calendar cal = Calendar.getInstance(); cal.set(1999, 12, 31); // Year, Month, Day System.out.print(cal.get(Calendar.YEAR) + " "); Date d = cal.getTime(); System.out.print(d.getDay() + " "); System.out.println(cal.get(Calendar.DAY_OF_MONTH)); } } Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 22. The Dating Game import java.util.*; public class DatingGame { Answers (a) 1999 31 31 (b) 1999 31 1 (c) 2000 1 31 - maybe the Y2K public static void main(String[] args) { Calendar cal = Calendar.getInstance(); cal.set(1999, 12, 31); // Year, Month, Day System.out.print(cal.get(Calendar.YEAR) + " "); Date d = cal.getTime(); System.out.print(d.getDay() + " "); System.out.println(cal.get(Calendar.DAY_OF_MONTH)); } } problem? (d) 2000 31 31 (e) None of the above Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 23. The Dating Game - answer When the Java platform was first released, its only support for calendar calculations was the Date class. This class was limited in power, especially when it came to support for internationalization, and it had a basic design flaw: Date instances were mutable. In release 1.1, the Calendar class was added to the platform to rectify the shortcomings of Date; most Date methods were deprecated. Unfortunately, this only made a bad situation worse. Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 24. The Dating Game - answer When the Java platform was first released, its only support for calendar calculations was the Date class. This class was limited in power, especially when it came to support for internationalization, and it had a basic design flaw: Date instances were mutable. In release 1.1, the Calendar class was added to the platform to rectify the shortcomings of Date; most Date methods were deprecated. Unfortunately, this only made a bad situation worse. The program just illustrates some of the shortcomings in the current API. The Calendar doesn’t warn us when it overflows and the months start the count from 0 Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 25. The Dating Game - answer When the Java platform was first released, its only support for calendar calculations was the Date class. This class was limited in power, especially when it came to support for internationalization, and it had a basic design flaw: Date instances were mutable. In release 1.1, the Calendar class was added to the platform to rectify the shortcomings of Date; most Date methods were deprecated. Unfortunately, this only made a bad situation worse. The program just illustrates some of the shortcomings in the current API. The Calendar doesn’t warn us when it overflows and the months start the count from 0 Use Joda Time which will be included in java8. . . Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 26. Some comments and references Use Sonar which will catch some of the problems from this presentation with the findbugs plugin Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls
  • 27. Some comments and references Use Sonar which will catch some of the problems from this presentation with the findbugs plugin Clickable links: Advanced Topics in Programming Languages: Java Puzzlers Java-Puzzlers InfoQ Nikola Petrov<nikola.petrov@ontotext.com> Java puzzlers - Traps, Pitfalls