Thursday, April 30, 2009

Puzzle 20 - Fill in the code

Language – Java | Type – Concept | Last date 03-May-2009 12:00 p.m. IST | Points 2

Just simply fill in the missing code ...
package com.twisters;
class Base {
public int a;

public int getA(){
return a;
}
}
public class Child extends Base{
private int a;

Child(
int value){
/* Code goes here */
}

public static void main(String[] args) {
Base b
= new Child(10);
System.out.println(b.getA());
//This should print 10
}
}

Got an answer? Why don’t you leave it here.


Wednesday, April 29, 2009

Puzzle 19 - Solution

If you are a Java programmer the only solution that I know of is to use ‘recursion’.
So you would have code
class Infinite{
public static void infinite(){
System.out.println(
1);
infinite();
}
public static void main(String args[]){
infinite();
}
}

If you are a C/C++ programmer there is one more way to generate a true infinite loop using the infamous ‘Goto’. So you can code

public static void infinite(){
cout<<1;
infinite();
}
public static void main(int argc char * argv[]){
infinite();
}
Congrats to
1. Bernardomen
2. Chanti
3. Joe Smith
for getting the answer right.

Sunday, April 26, 2009

Puzzle 19 - Loop de grace

Language – Java/C++ | Type – Puzzle | Last date 29-Apr-2009 9:00 p.m. IST | Points 5

One of the original twister puzzles !!!

Write a program to print 1 infinitely.
Twist: Do not use for, do-While or While loops.
(Assume Infinite memory if necessary!)

Got an answer? Why don’t you leave it here.



P.S - You can leave a link to your website or blog which gets published if you give the right answer. If you make it to the leader board your link gets added there!

Puzzle 18 – Solution

Puzzle 18 was a bit of a trick question. The key to the puzzle is 'Dynamic polymorphism comes into play only at run time. At compile time its the reference that matters!'

Output – Compilation Error at line number 16 - base.test()

Reason – The compiler identifies base.test() as a Base class method which throws an exception that has not been handled in the main method. (The compiler does not know or care what object the reference base will point to at run time).

Congrats to
1. Bernardomen
for getting the reason spot on!

Wednesday, April 22, 2009

Puzzle 18 – Exceptional Performance

Language – Java/C++ | Type – Concept | Last date 26-Apr-2009 12:00 p.m. IST | Points 2

Here is another simple Puzzle – what will be the output of this code? Looks simple? But looks can be deceiving ...

package com.twisters;
class Base {
public void test() throws Exception {
System.out.println(
"Base Exception");
throw new Exception("Base Exception");
}
}

public class Child extends Base{
public void test() {
System.out.println(
"Child has no Exception");
}

public static void main(String [] args) {
Base base
= new Child();
base.test();

Child child
= new Child ();
child.test();
}
}

Got an answer? Why don’t you leave it here.

Puzzle 17 – Solution

This is a pretty straight puzzle and evaluation takes place as follows,

Step 1 – j = 5 + i++;
Step 2 – value of i incremented: i = 6
Step 3 – j = 5 + 6 == 11
Step 4 – value of i incremented: i = 7

Output –
Value of i : 7
Value of j : 11

Congrats to
1. Turki
2. Minocha
3. Kannan
4. Doughty Dan
for getting the answer right.

Sunday, April 19, 2009

Puzzle 17 – YAAP (Yet Another Arithmetic Puzzle)

Language – Java/C++ | Type – Concept | Last date 22-Apr-2009 9:00 p.m. IST | Points 2

Coding is easy; it’s maintaining other people’s code that really gets on my nerve. Just the other day I came across something that made me laugh in anguish! As usual looking for your help!

package com.twister;

public class TooMuchAdd {
public static void main(String[] args) {
int i = 5, j;
j
= i++ + i++;
System.out.println(
"Value of i : " + i);
System.out.println(
"Value of j : " + j);
}
}

Got an answer? Why don’t you leave it here.

Puzzle 16 – Solution

The key to today’s solution is ‘boolean assignment’.

In Java, unlike C/C++ an if statement can only take a boolean condition. However the assignment operator ‘=’ can be used to assign a boolean value inside an if. Thus the statements,
boolean bool;
if (bool = true){
System.out.println(
"Worked!");
}

is legal and evaluates to true inside the if statement.

Congrats to
1. Scott Vachalek
2. Alex R
3. Rama Krishna
4. Anonymous - Sorry but no listing in the leader board for Anonymous entries!

for getting the right answer.

Wednesday, April 15, 2009

Puzzle 16 – The ‘=’ puzzle

Language – Java/C++ | Type – Problem (Code) | Last date 19-Apr-2009 12:00 p.m. IST | Points 5

I was attending a session the other day and the instructor was adamant that the Java language is pretty cool (which it is – I just love it). To illustrate his point he referred to the fact that we cannot use a ‘=’ sign in a ‘if condition’ causing problems like it did in C/C++.

"Of course you can use a single = to in a 'if condition'. I have seen that happen so many times" I blurred out. "No way" he challenged. Care to take up this challenge for me?

Got an answer? Why don’t you leave it here.

Puzzle 15 - Solution

The key to the last puzzle is ‘when using classes with same names, use fully qualified class
names’.

The statement public static void main(String[] args) is legal as far as the compiler is
concerned. It resolves to String to com.twisters.String and is legally used in a method
called main().

However at run time the class loader looks for a main method having java.lang.String[] as
parameter. Since it does not find one it gives an Exception in thread "main"
java.lang.NoSuchMethodError.

The solution to the problem is to use the fully qualified class name while declaring the
main method public static void main(java.lang.String[] args)

Congrats to
1. Eugene Kuleshov
2. Kasunh s
3. Lokedhs
4. TimTowTdi
5. Kai
6. TioDuke
7. Grr
8. James Barrow
for getting the correct answer.

Leader Board will be updated with the next post...

Sunday, April 12, 2009

Puzzle 15 – Package and My String.

Language – Java | Type – Concept | Last date 15-Apr-2009 12:00 p.m. IST | Points 2

Someone told me that I could not write a class called ‘String’ as it is sacred class. Writing a class called ‘String’ would cause the java compiler to complain louder than hell. All rubbish of course!

So to prove Mr. Someone wrong I quickly wiped up a String class in my own package. I also threw in a Demo class – though everything compiles fine, I can’t run Demo anymore. Any help out here?

package com.twisters;

class String{}

public class Demo {
public static void main(String[] args) {
System.out.println(
"Challenge Success!!!");
}
}

Got an answer? Why don’t you leave it here.

Puzzle 14 – Solution

The key to today’s solution is ‘operator precedence’.

The multiplication operator (*) has higher precedence that the addition operator (+). Hence a statement like x = x*5+2 evaluates by multiplying x with 5 and adding 2 to the result and storing the result in ‘x’.

The shorthand assignment operators (+=, *= etc) have a lower precedence than the addition operator (+). Hence a statement like x *= 5+2 evaluates by first adding 5 and 2 and then multiplying the result (7) with x and storing the result in ‘x’.

The answer to last weeks puzzle is Value of X is : 35

Sorry no correct solutions this week!

Wednesday, April 8, 2009

Puzzle 14 – Multiplication or Addition.

Language – Java Type – Concept Last date 12-Apr-2009 12:00 p.m. IST Points 2

Mathematical rules dictate that multiplication takes precedence over addition. It’s called BODMAS. Somehow the Java folks don’t seem to agree. But then maybe you could give me a better explanation for this anomaly?

package com.twisters;

public class MulOrAdd {
public static void main(String[] args) {
int x=5;
x
*= 5+2;
System.out.println(
"Value of X is : "+x);
}
}



Got an answer? Why don’t you leave it here.

Puzzle 13 - Solution

class Pattern{

void printPattern(int number){
//The trival case
if (number == 1){
System.out.print(number);
return;
}

printPattern(number
-1);
System.out.print(number);
printPattern(number
-1);
}

public static void main(String args[]){
int number = Integer.parseInt(args[0]);
Pattern pattern
= new Pattern();
pattern.printPattern(number);
}
}


Sorry no correct solutions this week!

Sunday, April 5, 2009

Puzzle 13 – Recursion

Language – Java | Type – Problem (Code) | Last date 08-Apr-2009 9:00 p.m. IST | Points 5

My little brother (a charming character usually) came to me the other day and said, “Don’t you think this pattern is amazing. I bet you computer folks could never make something like this”. “Ha” I scoffed “that’s simple recursion”. Simple recursion – was I out of my mind – when did recursion become simple? So here I am folks stuck on another problem. Any help?

When n = 1; output 1
When n = 2; output 121
When n = 3; output 1213121
When n = 4; output 121312141213121
Program must work for all positive integers ‘n’

Got an answer? Why don’t you leave it here.

Puzzle 12 – Solution

The key here is that ‘Integer objects are cached. 256 Integer objects are created in the range of -128 to 127 which are all stored in an Integer array’

You use auto-boxing, when you say,
Integer first = 100;

This is automatically translated by the Java compiler to the following:

Integer first = Integer.valueOf(100);

So, when you use autoboxing, you are really implicitly calling the method Integer.valueOf(int i).

Now, the method Integer.valueOf(int i) contains an optimization. It has a cache containing Integer objects for all the values between -128 and 127. If you call the method with an int that is in this range, then the method does not create a new Integer object; instead, it returns one of the existing Integer objects in the cache. Creating a new object is relatively expensive, so using a cache like this makes programs run more efficiently.


That means that if you do something like this:

Integer first = 100;
Integer second = 100;
You are calling Integer.valueOf(int i) two times, with the same value 100, which is in the cache - so the method will return the same Integer object from the cache for both first and second.

Since ==, when used on objects, checks if the two expressions on both sides of the == are the same object, the comparison first == second will return true.

Note that for numbers not in the range -128 to 127, Integer.valueOf(int i) will return a new Integer object.


The solution to this problem is based on an original post by Jesper Young at Java-Ranch.

Sorry no correct answers this week!

Wednesday, April 1, 2009

Puzzle-12 Object or Value

Language – Java | Type – Concept | Last date 05-Apr-2009 12:00 p.m. IST | Points 2

We all know that ‘==’ operator check for Object reference equality. It’s not supposed to compare values. That is why I was bugged when I tried the code below and got the ‘impossible output’. Can you tell me why?
package com.twisters;
class IntegerEquality{

public static void main(String args[]){
Integer first
= 100;
Integer second
= 100;
if(first == second)
System.out.println(“This is impossible
!!”)
else
System.out.println(“Everything is as expected out here.”)
}
}
Got an answer? Why don't you leave it here.

Puzzle 11 – Solution

The key to the solution is 'Character is treated as Int while doing arithmetic operations.'

When line 5 x=x+1; gets executed, the Ascii Value of 'x' is added to 1 and the result is an integer.
An integer value cannot be assigned to a char without explicit down casting so the correct way to increment the value of 'x' would be,

x=char (x+1);

Congrats to
1. Joe Smith
for getting the correct answer.