SlideShare a Scribd company logo
Java Puzzlers based on GoogleTechTalk
Many thanks..... James Gosling and Sun Microsystems for Java   Google for TechTalks video   Joshua Bloch for Java Puzzlers  
Long Division @Test public void LongDivision() {      final long MICROS_PER_DAY =24*60*60*1000*1000;      final long MILLIS_PER_DAY =24*60*60*1000;      long res =( MICROS_PER_DAY / MILLIS_PER_DAY );      assertEquals(1000, res );  } Result: 1000 - Ok or Error?
Long Division @Test public void LongDivision() {      final long MICROS_PER_DAY =24*60*60*1000*1000;      final long MILLIS_PER_DAY =24*60*60*1000;      long res = ( MICROS_PER_DAY / MILLIS_PER_DAY );      assertEquals(1000, res);  } Result:  Ok or  Error ,  because  res  is  5 . Why?

Recommended for you

仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#

This document discusses F# and FParsec. It provides examples of parsing expressions in FParsec using lazy evaluation and references, as opposed to NParsec which uses bindings. FParsec allows defining recursive parsers in a natural way in F#.

fsharp
Monad Laws Must be Checked
Monad Laws Must be CheckedMonad Laws Must be Checked
Monad Laws Must be Checked

Here I link up up some very useful material by Robert Norris (@tpolecat) and Martin Odersky (@odersky) to introduce Monad laws and reinforce the importance of checking the laws. E.g. while Option satisfies the laws, Try is not a lawful Monad: it trades the left identity law for the bullet-proof principle. * ERRATA * 1) on the first slide the Kleisli composition signature appears three times, but one of the occurrences is incorrect in that it is (>=>)::(a->mb)->(b->mb)->(a->mc) whereas is should be (>=>)::(a->mb)->(b->mc)->(a->mc) - thank you Jules Ivanic.

associativityflatmapfunction composition
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...

(download for best quality slides) Gain a deeper understanding of why right folds over very large and infinite lists are sometimes possible in Haskell. See how lazy evaluation and function strictness affect left and right folds in Haskell. Learn when an ordinary left fold results in a space leak and how to avoid it using a strict left fold. This version eliminates some minor imperfections and corrects the following two errors: slide 15: "as sharing is required" should be "as sharing is not required" slide 43: 푠푓표푙푑푙 (⊕) 푎 should be 푠푓표푙푑푙 (⊕) 푒

call-by-namecall-by-valueeager
Long Division @Test public void LongDivision() {      final long MICROS_PER_DAY =24L*60*60*1000*1000;      final long MILLIS_PER_DAY =24L*60*60*1000;      long res = ( MICROS_PER_DAY / MILLIS_PER_DAY );      assertEquals(1000, res);  } Result:  Ok ,  because  res  is  1000 .
It's Elementary       @Test      public void itsElementary() {          System.out.println(12345 + 5432l);      } Result: 66666 ?
It's Elementary       @Test      public void itsElementary() {          Integer i1 = new Integer(54321);          Integer i2 = new Integer(5432l);          System.out.println(i1-i2);      } Result: 0?
It's Elementary       @Test      public void itsElementary() {          System.out.println(12345 + 5432l);      } Result:  17777  Why???

Recommended for you

The Expression Problem - Part 2
The Expression Problem - Part 2The Expression Problem - Part 2
The Expression Problem - Part 2

Understand the expression problem See Haskell and Scala code illustrating the problem Learn how FP typeclasses can be used to solve the problem See the Haskell solution to the problem and a translation into Scala Part 2

Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals

Complete Information till 2D arrays. In this slides you can also find information about loops and control decision.... Best slides for beginners who wants to learn about C programming language..

Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0

First part of this presentation explains basics and advantages of using functional programming approaches with lambda calculus. Second part of this presentation explains how can we use lambda calculus in C# 3.0

functionalcalculusprogramming
What is the size?       @Test      public void whatIsTheSize() {          Set<Short> list = new HashSet<Short>();          for (short i = 0; i<100; i++ ) {              list.add(i);              list.remove( i - 1);          }          assertEquals(1,list.size());      } Result: 1 ? 
What is the size?       @Test      public void whatIsTheSize() {          Set<Short> list = new HashSet<Short>();          for (short i = 0; i<100; i++ ) {              list.add(i);              list.remove( i - 1);          }          assertEquals(1,list.size());      } Result:  100 . Why????
What is size [2] ?       final String[] URL_NAMES = {              &quot;http://www.google.com&quot;,              &quot;http://www.google.lv&quot;,              &quot;http://google.com&quot;,      };      @Test      public void urlSet() throws MalformedURLException {          Set<URL> favorites = new HashSet<URL>();          for(String name: URL_NAMES) {              favorites.add( new URL(name));          }          assertEquals( 3 ,favorites.size());      } What is size, 3 ? 
What is size [2] ?       final String[] URL_NAMES = {              &quot;http://www.google.com&quot;,              &quot;http://www.google.lv&quot;,              &quot;http://google.com&quot;,      };      @Test      public void urlSet() throws MalformedURLException {          Set<URL> favorites = new HashSet<URL>();          for(String name: URL_NAMES) {              favorites.add( new URL(name));          }          assertEquals( 3 ,favorites.size());      } Size is  1 . Why???

Recommended for you

Lecture2
Lecture2Lecture2
Lecture2

The document provides an introduction to the CLIPS expert system shell. It discusses CLIPS' components like facts, rules, and the inference engine. It explains how CLIPS uses forward chaining to match facts to rules and fire actions. The objectives are to understand rule-based expert system concepts and apply them using CLIPS.

Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions

This PDF contains notes about control flow and functions in problem solving and python programming (as per Anna university syllabus)

operators in pythonstrings in pythoncontrol flows in python
Operators
OperatorsOperators
Operators

The document discusses various Java operators including assignment, arithmetic, relational, logical, bitwise, and shift operators. It provides examples of using each operator type on primitive data types like int and boolean. Key points include: - Assignment (=), arithmetic (+ - * / %), relational (>, <, ==, !=), logical (&&, ||, !) and bitwise (& | ^ ~) operators in Java. - Implicit type promotions and casts that occur with arithmetic and relational operators. - Short-circuit evaluation behavior of logical && and || operators. - Using shift operators (<< >> >>>) to manipulate bits in binary representations of integers.

Evil class DB {     private static final DB db = new DB();     public static DB getDB(){ return db; }     private static final String URL=System.getProperty(&quot;url&quot;);     private static final String USR=System.getProperty(&quot;usr&quot;);     private static final String PSW=System.getProperty(&quot;psw&quot;);     private DB(){         this.connection = URL+&quot;:&quot;+USR+&quot;:&quot;+PSW;     }     private String connection;     public String getConnection() {         return connection;     } } DB db = DB.getDB(); System.out.println(db.getConnection()); What is result?
Evil class DB {     private static final DB db =  new DB();     public static DB getDB(){ return db; }     private static final String URL=System.getProperty(&quot;url&quot;);     private static final String USR=System.getProperty(&quot;usr&quot;);     private static final String PSW=System.getProperty(&quot;psw&quot;);     private DB(){         this.connection = URL+&quot;:&quot;+USR+&quot;:&quot;+PSW;     }     private String connection;     public String getConnection() {         return connection;     } } DB db = DB.getDB(); System.out.println(db.getConnection()); null:null:null
&quot;Hamlet&quot;       @Test      public void hamlet(){          Random rnd = new Random();          boolean toBe = rnd.nextBoolean();          Number result = (toBe || !toBe) ?                  new Integer(3): new Float(1);          System.out.println(result);      } (a)     3 (b)     1.0 (c)     Throws exception (d)     None of the above
&quot;Hamlet&quot;       @Test      public void hamlet(){          Random rnd = new Random();          boolean toBe = rnd.nextBoolean();          Number result =  (toBe || !toBe) ?                  new Integer(3): new Float(1);          System.out.println(result);      } (a)     3 (b)     1.0 (c)     Throws exception (d)     None of the above     3.0 , Why???

Recommended for you

Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4

The document discusses different parameter passing techniques in programming languages, including pass by value, pass by reference, and pass by result/value-result. It provides examples in languages like C, C++, Java, C#, Pascal, Ada to illustrate how each technique works and the differences between them. It also covers topics like parameter modes (in, out, in-out), parameter arrays, and variable arguments.

OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions

This document contains sample questions and explanations for the OCP Java SE 8 exam related to lambda expressions and functional interfaces. It includes multiple choice questions testing knowledge of valid lambda expression syntax, lambda behavior and scoping, and proper usage of the @FunctionalInterface annotation. The explanations provide detailed reasoning for the correct answers and why the other options are incorrect.

java 8java certificationlambda
The Ring programming language version 1.5.3 book - Part 35 of 184
The Ring programming language version 1.5.3 book - Part 35 of 184The Ring programming language version 1.5.3 book - Part 35 of 184
The Ring programming language version 1.5.3 book - Part 35 of 184

The document provides documentation on various functions available in the Ring programming language standard library (stdlib). It describes functions for generating permutations, reading lines from a file, finding substrings, changing substrings, sleeping, checking if a file is the main source file, checking if a directory exists, making directories, getting file sizes, trimming strings, getting the epoch time, executing system commands, listing all files in a folder, and more. It also provides details on classes in the stdlib like the String, List, Stack, Queue, HashTable, Tree, Math, DateTime, File, and other classes along with their methods.

ringring programmingring programming language
&quot;Hamlet&quot;       @Test      public void hamlet(){          Random rnd = new Random();          boolean toBe = rnd.nextBoolean();          Integer i = new Integer(3);          Float f = new Float(1);          Number result = (toBe || !toBe) ? i : f;          System.out.println( result == i);      } (a)     true (b)     false (c)     Throws exception (d)     None of the above  
&quot;Hamlet&quot;       @Test      public void hamlet(){          Random rnd = new Random();          boolean toBe = rnd.nextBoolean();          Integer i = new Integer(3);          Float f = new Float(1);          Number result = (toBe || !toBe) ? i : f;          System.out.println( result == i);      } (a)     true (b)      false (c)     Throws exception (d)     None of the above  
The type of a conditional expression is determined as follows: If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression. If one of the second and third operands is of type boolean and the type of the other is of type Boolean, then the type of the conditional expression is boolean. If one of the second and third operands is of the null type and the type of the other is a reference type, then the type of the conditional expression is that reference type. Otherwise, if the second and third operands have types that are convertible  (§5.1.8)  to numeric types, then there are several cases: If one of the operands is of type byte or Byte and the other is of type short or Short, then the type of the conditional expression is short. If one of the operands is of type  T  where  T  is byte, short, or char, and the other operand is a constant expression of type int whose value is representable in type  T , then the type of the conditional expression is  T . If one of the operands is of type Byte and the other operand is a constant expression of type int whose value is representable in type byte, then the type of the conditional expression is byte. If one of the operands is of type Short and the other operand is a constant expression of type int whose value is representable in type short, then the type of the conditional expression is short. If one of the operands is of type; Character and the other operand is a constant expression of type int whose value is representable in type char, then the type of the conditional expression is char. Otherwise, binary numeric promotion  (§5.6.2)  is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands. Note that binary numeric promotion performs unboxing conversion (§5.1.8)  and value set conversion  (§5.1.13) . Otherwise, the second and third operands are of types  S1  and  S2  respectively. Let  T1  be the type that results from applying boxing conversion to  S1 , and let  T2  be the type that results from applying boxing conversion to  S2 . The type of the conditional expression is the result of applying capture conversion  (§5.1.10)  to  lub(T1, T2)   (§15.12.2.7) . Java Language Spesification 15.25
video.google.com    youtube.com     Google

Recommended for you

The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold

This slide deck is my homage to SICP, the book which first introduced me to the Functional Programming triad of map, filter and fold. It was during my Computer Science degree that a fellow student gave me a copy of the first edition, not long after the book came out. I have not yet come across a better introduction to these three functions. The upcoming slides are closely based on the second edition of the book, a free online copy of which can be found here: https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html. Download for original image quality. Errata: slide 20: the Clojure map function is in fact the Scheme one repeated - see code below for correction. Scheme code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-scheme Clojure code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-clojure

sicpstructure and interpretation of computer programsfunctional programming
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term Rewriting

Lecture 4 of compiler construction course on program transformation by means of strategic term rewriting in Stratego

term rewritingtransformationprogram transformation
Declare Your Language: Name Resolution
Declare Your Language: Name ResolutionDeclare Your Language: Name Resolution
Declare Your Language: Name Resolution

Scope graphs are used to represent the binding information in programs. They provide a language-independent representation of name resolution that can be used to conduct and represent the results of name resolution. Separating the representation of resolved programs from the declarative rules that define name binding allows language-independent tooling to be developed for name resolution and other tasks.

compilersdeclare your languagelanguage definition

More Related Content

What's hot

Ch06
Ch06Ch06
Ch06
Hankyo
 
Computer programming 2 Lesson 11
Computer programming 2  Lesson 11Computer programming 2  Lesson 11
Computer programming 2 Lesson 11
MLG College of Learning, Inc
 
Software Construction Assignment Help
Software Construction Assignment HelpSoftware Construction Assignment Help
Software Construction Assignment Help
Programming Homework Help
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
bleis tift
 
Monad Laws Must be Checked
Monad Laws Must be CheckedMonad Laws Must be Checked
Monad Laws Must be Checked
Philip Schwarz
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Philip Schwarz
 
The Expression Problem - Part 2
The Expression Problem - Part 2The Expression Problem - Part 2
The Expression Problem - Part 2
Philip Schwarz
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
umar78600
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
Sheik Uduman Ali
 
Lecture2
Lecture2Lecture2
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
DhivyaSubramaniyam
 
Operators
OperatorsOperators
Operators
Daman Toor
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
Ismar Silveira
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
Ganesh Samarthyam
 
The Ring programming language version 1.5.3 book - Part 35 of 184
The Ring programming language version 1.5.3 book - Part 35 of 184The Ring programming language version 1.5.3 book - Part 35 of 184
The Ring programming language version 1.5.3 book - Part 35 of 184
Mahmoud Samir Fayed
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold
Philip Schwarz
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term Rewriting
Eelco Visser
 
Declare Your Language: Name Resolution
Declare Your Language: Name ResolutionDeclare Your Language: Name Resolution
Declare Your Language: Name Resolution
Eelco Visser
 
Break and continue statement in C
Break and continue statement in CBreak and continue statement in C
Break and continue statement in C
Innovative
 
Oleksii Holub "Expression trees in C#"
Oleksii Holub "Expression trees in C#" Oleksii Holub "Expression trees in C#"
Oleksii Holub "Expression trees in C#"
Fwdays
 

What's hot (20)

Ch06
Ch06Ch06
Ch06
 
Computer programming 2 Lesson 11
Computer programming 2  Lesson 11Computer programming 2  Lesson 11
Computer programming 2 Lesson 11
 
Software Construction Assignment Help
Software Construction Assignment HelpSoftware Construction Assignment Help
Software Construction Assignment Help
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
 
Monad Laws Must be Checked
Monad Laws Must be CheckedMonad Laws Must be Checked
Monad Laws Must be Checked
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
 
The Expression Problem - Part 2
The Expression Problem - Part 2The Expression Problem - Part 2
The Expression Problem - Part 2
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 
Lecture2
Lecture2Lecture2
Lecture2
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
 
Operators
OperatorsOperators
Operators
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
 
The Ring programming language version 1.5.3 book - Part 35 of 184
The Ring programming language version 1.5.3 book - Part 35 of 184The Ring programming language version 1.5.3 book - Part 35 of 184
The Ring programming language version 1.5.3 book - Part 35 of 184
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term Rewriting
 
Declare Your Language: Name Resolution
Declare Your Language: Name ResolutionDeclare Your Language: Name Resolution
Declare Your Language: Name Resolution
 
Break and continue statement in C
Break and continue statement in CBreak and continue statement in C
Break and continue statement in C
 
Oleksii Holub "Expression trees in C#"
Oleksii Holub "Expression trees in C#" Oleksii Holub "Expression trees in C#"
Oleksii Holub "Expression trees in C#"
 

Viewers also liked

How to become a LinkedIn Rockstar
How to become a LinkedIn RockstarHow to become a LinkedIn Rockstar
How to become a LinkedIn Rockstar
joemarshall1188
 
Mobile app development 12 13 y1 ict ssp l17 rev
Mobile app development 12 13 y1 ict ssp l17 revMobile app development 12 13 y1 ict ssp l17 rev
Mobile app development 12 13 y1 ict ssp l17 rev
Miles Berry
 
2013 campaign qa's
2013 campaign qa's2013 campaign qa's
2013 campaign qa's
Anna Fischer
 
Social Business Imperative Women's President Organization
Social Business Imperative Women's President OrganizationSocial Business Imperative Women's President Organization
Social Business Imperative Women's President Organization
Liz Bullock
 
What do YOU have to do to become an Innovator?
What do YOU have to do to become an Innovator?What do YOU have to do to become an Innovator?
What do YOU have to do to become an Innovator?
Uninstall.io
 
Mobile Workforce Report Q4 2012
Mobile Workforce Report Q4 2012Mobile Workforce Report Q4 2012
Mobile Workforce Report Q4 2012
iPass
 
The EUN Learning Resource Exchange (LRE)
The EUN Learning Resource Exchange (LRE)The EUN Learning Resource Exchange (LRE)
The EUN Learning Resource Exchange (LRE)
David Massart
 

Viewers also liked (7)

How to become a LinkedIn Rockstar
How to become a LinkedIn RockstarHow to become a LinkedIn Rockstar
How to become a LinkedIn Rockstar
 
Mobile app development 12 13 y1 ict ssp l17 rev
Mobile app development 12 13 y1 ict ssp l17 revMobile app development 12 13 y1 ict ssp l17 rev
Mobile app development 12 13 y1 ict ssp l17 rev
 
2013 campaign qa's
2013 campaign qa's2013 campaign qa's
2013 campaign qa's
 
Social Business Imperative Women's President Organization
Social Business Imperative Women's President OrganizationSocial Business Imperative Women's President Organization
Social Business Imperative Women's President Organization
 
What do YOU have to do to become an Innovator?
What do YOU have to do to become an Innovator?What do YOU have to do to become an Innovator?
What do YOU have to do to become an Innovator?
 
Mobile Workforce Report Q4 2012
Mobile Workforce Report Q4 2012Mobile Workforce Report Q4 2012
Mobile Workforce Report Q4 2012
 
The EUN Learning Resource Exchange (LRE)
The EUN Learning Resource Exchange (LRE)The EUN Learning Resource Exchange (LRE)
The EUN Learning Resource Exchange (LRE)
 

Similar to Java Puzzlers

C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
jahanullah
 
Loops
LoopsLoops
Loops
Kamran
 
C tutorial
C tutorialC tutorial
C tutorial
Anurag Sukhija
 
Chapter 2
Chapter 2Chapter 2
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 
ch04-conditional-execution.ppt
ch04-conditional-execution.pptch04-conditional-execution.ppt
ch04-conditional-execution.ppt
Mahyuddin8
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
sholavanalli
 
Java căn bản - Chapter5
Java căn bản - Chapter5Java căn bản - Chapter5
Java căn bản - Chapter5
Vince Vo
 
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Udayan Khattry
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
Woody Pewitt
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
ShashikantSathe3
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
Yaser Zhian
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
Christoffer Noring
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java Programming
Pathomchon Sriwilairit
 
Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, code
Kamil Witecki
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
Daniel Wellman
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
BAINIDA
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
ssuser3cbb4c
 
C tutorial
C tutorialC tutorial

Similar to Java Puzzlers (20)

C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
 
Loops
LoopsLoops
Loops
 
C tutorial
C tutorialC tutorial
C tutorial
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
ch04-conditional-execution.ppt
ch04-conditional-execution.pptch04-conditional-execution.ppt
ch04-conditional-execution.ppt
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Java căn bản - Chapter5
Java căn bản - Chapter5Java căn bản - Chapter5
Java căn bản - Chapter5
 
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java Programming
 
Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, code
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
 
C tutorial
C tutorialC tutorial
C tutorial
 

More from Dmitry Buzdin

How Payment Cards Really Work?
How Payment Cards Really Work?How Payment Cards Really Work?
How Payment Cards Really Work?
Dmitry Buzdin
 
Как построить свой фреймворк для автотестов?
Как построить свой фреймворк для автотестов?Как построить свой фреймворк для автотестов?
Как построить свой фреймворк для автотестов?
Dmitry Buzdin
 
How to grow your own Microservice?
How to grow your own Microservice?How to grow your own Microservice?
How to grow your own Microservice?
Dmitry Buzdin
 
How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?
Dmitry Buzdin
 
Delivery Pipeline for Windows Machines
Delivery Pipeline for Windows MachinesDelivery Pipeline for Windows Machines
Delivery Pipeline for Windows Machines
Dmitry Buzdin
 
Big Data Processing Using Hadoop Infrastructure
Big Data Processing Using Hadoop InfrastructureBig Data Processing Using Hadoop Infrastructure
Big Data Processing Using Hadoop Infrastructure
Dmitry Buzdin
 
JOOQ and Flyway
JOOQ and FlywayJOOQ and Flyway
JOOQ and Flyway
Dmitry Buzdin
 
Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIs
Dmitry Buzdin
 
Whats New in Java 8
Whats New in Java 8Whats New in Java 8
Whats New in Java 8
Dmitry Buzdin
 
Архитектура Ленты на Одноклассниках
Архитектура Ленты на ОдноклассникахАрхитектура Ленты на Одноклассниках
Архитектура Ленты на Одноклассниках
Dmitry Buzdin
 
Dart Workshop
Dart WorkshopDart Workshop
Dart Workshop
Dmitry Buzdin
 
Riding Redis @ask.fm
Riding Redis @ask.fmRiding Redis @ask.fm
Riding Redis @ask.fm
Dmitry Buzdin
 
Rubylight JUG Contest Results Part II
Rubylight JUG Contest Results Part IIRubylight JUG Contest Results Part II
Rubylight JUG Contest Results Part II
Dmitry Buzdin
 
Rubylight Pattern-Matching Solutions
Rubylight Pattern-Matching SolutionsRubylight Pattern-Matching Solutions
Rubylight Pattern-Matching Solutions
Dmitry Buzdin
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
Dmitry Buzdin
 
Rubylight programming contest
Rubylight programming contestRubylight programming contest
Rubylight programming contest
Dmitry Buzdin
 
Continuous Delivery
Continuous Delivery Continuous Delivery
Continuous Delivery
Dmitry Buzdin
 
Introduction to DevOps
Introduction to DevOpsIntroduction to DevOps
Introduction to DevOps
Dmitry Buzdin
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
Dmitry Buzdin
 

More from Dmitry Buzdin (20)

How Payment Cards Really Work?
How Payment Cards Really Work?How Payment Cards Really Work?
How Payment Cards Really Work?
 
Как построить свой фреймворк для автотестов?
Как построить свой фреймворк для автотестов?Как построить свой фреймворк для автотестов?
Как построить свой фреймворк для автотестов?
 
How to grow your own Microservice?
How to grow your own Microservice?How to grow your own Microservice?
How to grow your own Microservice?
 
How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?
 
Delivery Pipeline for Windows Machines
Delivery Pipeline for Windows MachinesDelivery Pipeline for Windows Machines
Delivery Pipeline for Windows Machines
 
Big Data Processing Using Hadoop Infrastructure
Big Data Processing Using Hadoop InfrastructureBig Data Processing Using Hadoop Infrastructure
Big Data Processing Using Hadoop Infrastructure
 
JOOQ and Flyway
JOOQ and FlywayJOOQ and Flyway
JOOQ and Flyway
 
Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIs
 
Whats New in Java 8
Whats New in Java 8Whats New in Java 8
Whats New in Java 8
 
Архитектура Ленты на Одноклассниках
Архитектура Ленты на ОдноклассникахАрхитектура Ленты на Одноклассниках
Архитектура Ленты на Одноклассниках
 
Dart Workshop
Dart WorkshopDart Workshop
Dart Workshop
 
Riding Redis @ask.fm
Riding Redis @ask.fmRiding Redis @ask.fm
Riding Redis @ask.fm
 
Rubylight JUG Contest Results Part II
Rubylight JUG Contest Results Part IIRubylight JUG Contest Results Part II
Rubylight JUG Contest Results Part II
 
Rubylight Pattern-Matching Solutions
Rubylight Pattern-Matching SolutionsRubylight Pattern-Matching Solutions
Rubylight Pattern-Matching Solutions
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
 
Rubylight programming contest
Rubylight programming contestRubylight programming contest
Rubylight programming contest
 
Continuous Delivery
Continuous Delivery Continuous Delivery
Continuous Delivery
 
Introduction to DevOps
Introduction to DevOpsIntroduction to DevOps
Introduction to DevOps
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
 

Java Puzzlers

  • 1. Java Puzzlers based on GoogleTechTalk
  • 2. Many thanks..... James Gosling and Sun Microsystems for Java   Google for TechTalks video   Joshua Bloch for Java Puzzlers  
  • 3. Long Division @Test public void LongDivision() {      final long MICROS_PER_DAY =24*60*60*1000*1000;      final long MILLIS_PER_DAY =24*60*60*1000;      long res =( MICROS_PER_DAY / MILLIS_PER_DAY );      assertEquals(1000, res );  } Result: 1000 - Ok or Error?
  • 4. Long Division @Test public void LongDivision() {      final long MICROS_PER_DAY =24*60*60*1000*1000;      final long MILLIS_PER_DAY =24*60*60*1000;      long res = ( MICROS_PER_DAY / MILLIS_PER_DAY );      assertEquals(1000, res);  } Result: Ok or  Error ,  because res  is 5 . Why?
  • 5. Long Division @Test public void LongDivision() {      final long MICROS_PER_DAY =24L*60*60*1000*1000;      final long MILLIS_PER_DAY =24L*60*60*1000;      long res = ( MICROS_PER_DAY / MILLIS_PER_DAY );      assertEquals(1000, res);  } Result: Ok ,  because res  is 1000 .
  • 6. It's Elementary      @Test      public void itsElementary() {          System.out.println(12345 + 5432l);      } Result: 66666 ?
  • 7. It's Elementary      @Test      public void itsElementary() {          Integer i1 = new Integer(54321);          Integer i2 = new Integer(5432l);          System.out.println(i1-i2);      } Result: 0?
  • 8. It's Elementary      @Test      public void itsElementary() {          System.out.println(12345 + 5432l);      } Result: 17777  Why???
  • 9. What is the size?      @Test      public void whatIsTheSize() {          Set<Short> list = new HashSet<Short>();          for (short i = 0; i<100; i++ ) {              list.add(i);              list.remove( i - 1);          }          assertEquals(1,list.size());      } Result: 1 ? 
  • 10. What is the size?      @Test      public void whatIsTheSize() {          Set<Short> list = new HashSet<Short>();          for (short i = 0; i<100; i++ ) {              list.add(i);              list.remove( i - 1);          }          assertEquals(1,list.size());      } Result: 100 . Why????
  • 11. What is size [2] ?       final String[] URL_NAMES = {              &quot;http://www.google.com&quot;,              &quot;http://www.google.lv&quot;,              &quot;http://google.com&quot;,      };      @Test      public void urlSet() throws MalformedURLException {          Set<URL> favorites = new HashSet<URL>();          for(String name: URL_NAMES) {              favorites.add( new URL(name));          }          assertEquals( 3 ,favorites.size());      } What is size, 3 ? 
  • 12. What is size [2] ?       final String[] URL_NAMES = {              &quot;http://www.google.com&quot;,              &quot;http://www.google.lv&quot;,              &quot;http://google.com&quot;,      };      @Test      public void urlSet() throws MalformedURLException {          Set<URL> favorites = new HashSet<URL>();          for(String name: URL_NAMES) {              favorites.add( new URL(name));          }          assertEquals( 3 ,favorites.size());      } Size is 1 . Why???
  • 13. Evil class DB {    private static final DB db = new DB();    public static DB getDB(){ return db; }     private static final String URL=System.getProperty(&quot;url&quot;);     private static final String USR=System.getProperty(&quot;usr&quot;);     private static final String PSW=System.getProperty(&quot;psw&quot;);    private DB(){        this.connection = URL+&quot;:&quot;+USR+&quot;:&quot;+PSW;    }    private String connection;    public String getConnection() {        return connection;    } } DB db = DB.getDB(); System.out.println(db.getConnection()); What is result?
  • 14. Evil class DB {    private static final DB db = new DB();    public static DB getDB(){ return db; }     private static final String URL=System.getProperty(&quot;url&quot;);     private static final String USR=System.getProperty(&quot;usr&quot;);     private static final String PSW=System.getProperty(&quot;psw&quot;);    private DB(){        this.connection = URL+&quot;:&quot;+USR+&quot;:&quot;+PSW;    }    private String connection;    public String getConnection() {        return connection;    } } DB db = DB.getDB(); System.out.println(db.getConnection()); null:null:null
  • 15. &quot;Hamlet&quot;      @Test      public void hamlet(){          Random rnd = new Random();          boolean toBe = rnd.nextBoolean();          Number result = (toBe || !toBe) ?                  new Integer(3): new Float(1);          System.out.println(result);      } (a)     3 (b)     1.0 (c)     Throws exception (d)     None of the above
  • 16. &quot;Hamlet&quot;      @Test      public void hamlet(){          Random rnd = new Random();          boolean toBe = rnd.nextBoolean();          Number result = (toBe || !toBe) ?                  new Integer(3): new Float(1);          System.out.println(result);      } (a)     3 (b)     1.0 (c)     Throws exception (d)     None of the above    3.0 , Why???
  • 17. &quot;Hamlet&quot;      @Test      public void hamlet(){          Random rnd = new Random();          boolean toBe = rnd.nextBoolean();          Integer i = new Integer(3);          Float f = new Float(1);          Number result = (toBe || !toBe) ? i : f;          System.out.println( result == i);      } (a)     true (b)     false (c)     Throws exception (d)     None of the above  
  • 18. &quot;Hamlet&quot;      @Test      public void hamlet(){          Random rnd = new Random();          boolean toBe = rnd.nextBoolean();          Integer i = new Integer(3);          Float f = new Float(1);          Number result = (toBe || !toBe) ? i : f;          System.out.println( result == i);      } (a)     true (b)     false (c)     Throws exception (d)     None of the above  
  • 19. The type of a conditional expression is determined as follows: If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression. If one of the second and third operands is of type boolean and the type of the other is of type Boolean, then the type of the conditional expression is boolean. If one of the second and third operands is of the null type and the type of the other is a reference type, then the type of the conditional expression is that reference type. Otherwise, if the second and third operands have types that are convertible  (§5.1.8)  to numeric types, then there are several cases: If one of the operands is of type byte or Byte and the other is of type short or Short, then the type of the conditional expression is short. If one of the operands is of type  T  where  T  is byte, short, or char, and the other operand is a constant expression of type int whose value is representable in type  T , then the type of the conditional expression is  T . If one of the operands is of type Byte and the other operand is a constant expression of type int whose value is representable in type byte, then the type of the conditional expression is byte. If one of the operands is of type Short and the other operand is a constant expression of type int whose value is representable in type short, then the type of the conditional expression is short. If one of the operands is of type; Character and the other operand is a constant expression of type int whose value is representable in type char, then the type of the conditional expression is char. Otherwise, binary numeric promotion  (§5.6.2)  is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands. Note that binary numeric promotion performs unboxing conversion (§5.1.8)  and value set conversion  (§5.1.13) . Otherwise, the second and third operands are of types  S1  and  S2  respectively. Let  T1  be the type that results from applying boxing conversion to  S1 , and let  T2  be the type that results from applying boxing conversion to  S2 . The type of the conditional expression is the result of applying capture conversion  (§5.1.10)  to  lub(T1, T2)   (§15.12.2.7) . Java Language Spesification 15.25