Showing posts with label puzzle. Show all posts
Showing posts with label puzzle. Show all posts

Saturday, July 4, 2009

String puzzle

A short, but interesting puzzle.

Question
What does the following program print:



Answer
When you run the code, you get the answer: 2.

Why?
The compiler translates Unicode escapes into the characters they represent before it parses the program into tokens, such as strings literals. As you see, NetBeans IDE doesn't know it, it present the code like a string with a length() method.

Monday, February 2, 2009

Protected Access Modifier Facts

I show an interesting example to the protected access modifier.



Our first file, Animal.java in package world:
01. package world;
02. public class Animal {
03. protected int age;
04. }


Our second file, Animal.java in package africa:
01. package africa;
02. import world.Animal;
03. public class Zebra extends Animal {
04. public void sayAge() {
05. System.out.println("My age is "+age); //Works well, age is protected;
06. }
07. public void sayFriendAge() {
08. Animal friend = new Animal();
09. System.out.println("My fried's age is " + friend.age ); //Compile error, age is accessible
10. // through inheritance
11. }
12. }


Our third file, Lion.java in package africa:
01. package africa;
02. public class Lion {
03. public void sayZebraAge() {
04. Zebra zebra = new Zebra();
05. System.out.println("Zebra's age is " + zebra.age ) ; //Compile error, Zebra and Lion are
06. // in the same package, but age is protected and only available using inheritance, Lion
07. // can't see it.
08. }
09. }

Sunday, June 29, 2008

Java Puzzles

Puzzle 1
Given the following code:
public class Puzzle 1 {
public static void main(String[] args) {
boolean b = false;
System.out.println("Output - " + ( b ? 1.66 : 2 ));
}
}

What is the output?
If you think, the output is "Output - 2" then you're wrong.
The right output is "Output - 2.0" because 1.66 is double, 2 is int so 2 is converted to double.

Puzzle 2
Given the following code:
public class Puzzle2 {
public static void main(String[] args) {
int i = Integer.valueOf("2*3");
System.out.println("Output - " + i );
}
}

What is the output?
java.lang.NumberFormatException is caused, because the parser methods accepts only literals in the String parameter.

Puzzle 3
Given the following code:
public class NullReference {

public static void doStuff() {
System.out.println("Hello");
}

public static void main(String[] args) {
((NullReference) null ).doStuff();

}

}

What is the output?
The output is:
Hello

because when we call a static method through an instance then the compiler determine the class and replace the instance reference to class reference.

SCJP Exam - Objective 1.1

Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).

Java Source File
Sample Java source file:



You can download source code here.
  1. If the class is part of a package, the package statement must be the first in the source code file.
  2. The import statements must be after the package statement (if there is one) and must be before the class declaration.
  3. There can be only one public class per source code file.
  4. If there is a public class in a file, the name of the file must match the name of the public class.
  5. A source file can have more than one nonpublic class.
  6. Files with no public classes can have a name that does not match any of the classes in the file.
Static import

The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members, either individually:

import static java.lang.Math.PI;
or:
import static java.lang.Math.*;
Once the static members have been imported, they may be used without qualification:
double r = cos(PI * theta);
The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.

Class declaration
Class declaration looks like this:
<Class modifier> class <ClassName> {
//...
}
Modifiers
Access modifiers
  1. A class can be declared as public and default access.
  2. A class never can be declared as private or protected, except the inner classes.
Non-access modifiers
  1. abstract
  2. final
  3. strictfp

Non-access modifier: abstract
An abstract class can never be instantiated. If you try it, you get Compilation fails. The abstract classes are to extend them.

If we have some classes with the same methods, but some method implementation are different then abstract class is a perfect choice:
Make an abstract class, write the methods, that will be same in the subclasses.
Mark the methods, that will have different implementations as abstract. Abstract methods end in a semicolon rather than curly braces.

Example for abstract class and its concrete classes:

You can download source code here.


Non-access modifier: final
When used in a class declaration, the final keyword means the class can't be subclassed. In other words, no other class can ever extend a final class, and any attempts to do so will give you a compiler error.

Many classes in the Java core libraries are final. For example, the string class. So notice, you never ever can extend the String class.

Example for final class and the Compilation fails when try to extend the class, marked final:

You can download source code here.


Non-access modifier: strictfp
Marking a class as strictfp means that any method code in the class will conform to the IEEE 754 standard rules for floating points. Without that modifier, floating points used in the methods might behave in a platform-dependent way.

Notice,
  • an abstract class never ever can be instantiated
  • abstract class can have constructor and it can be called from subclasses constructors trough super()
  • a final class never ever can be extended
  • a class never ever can be marked as both abstract and final
Declaring nested classes
The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here:
class OuterClass {
//...
class NestedClass {
//...
}
}
Type of nested classes:
  1. static nested class
  2. inner (non-static) class
  3. local class
  4. anonymous class
Static nested class
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
Inner class
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {
//...
class InnerClass {
//...
}
}

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Local inner class
You can declare an inner class within the body of a method. Such a class is known as a local inner class:
class OuterClass {
public void someMethod() {
class InnerClass {
//..
}
}
}
Notice,
  1. a local inner class can be instantiated only within the method where the inner class is defined
  2. a local inner class can not access to the method's local variables
  3. a local inner class can access to the method's local variables, marked as final

Anonymous class
Anonymous classes extends an exists class or implements an interface, with creating a new class without name:
class Tree {
public void grow() {
//Some tree specific code
}
}

interface Door {
void closeDoor();
}

public class MyClass {
public void doStuff() {
Tree oak = new Tree {
public void grow() {
//Some oakvspecific code
}
}

Door door = new Door {
public void closeDoor() {
//Close door method
}
}
}
}



Interface declaration

Interface declaration looks like this:
<Class modifier> interface <InterfaceName> {
//...
}
Notice,
  • all interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract
  • all variables defined in an interface must be public, static, and final—in other words, interfaces can declare only constants, not instance variables

  • interface methods must not be static

  • because interface methods are abstract, they cannot be marked final, strictfp, or native

  • an interface can extend one or more other interfaces

  • an interface cannot extend anything but another interface

  • an interface cannot implement another interface or class

  • an interface must be declared with the keyword interface

  • interface types can be used polymorphically

Puzzle 1
Given the following code:
interface Tree {
void grow();
}

public class Oak implements Tree {
void grow() {
//Some oak specific code here...
}
}
What is the result?
The result is: the code does not compile, it causes Compilation fails, because methods in interface declaration are implicitly public and the accession of grow() method in Oak class is default.

Puzzle 2
Given the following code:
interface MyInterface {
int x = 67;
}

class MyClass implements MyInterface {
public void setter() {
x = 100;
}
}
What is the result?
The result is: the code does not compile, it causes Compilation fails, because variables, declared in interfaces are implicitly final and static, and you can not assign a new value to a final variable.

Declaring Enums
Using enums can help reduce the bugs in your code.

Example for declaring enumerations:

You can download source code here.

Wednesday, June 25, 2008

Java Inner Class Expert

Puzzle 1
Given the following code:

1. class MyOuter {
2. private int x = 7;
3. class MyInner {
4. public void seeOuter() {
5. System.out.println("Outer x is " + x);
6. }
7. }
8. }


What is happening when we try compile the code?
If you think, the output is Compilation fails then you're wrong. Line 5 looks interesting, because a private member is accessed from an inner class.

Is it possible?
Yes, it is. Remember, inner classes can access the outer class members.
So the right answer is: the code compiles without error.

Puzzle 2
Given the following code:

01. class MyOuter {
02. private int x = 7;
03. public void makeInner() {
04. MyInner in = new MyInner();
05. in.seeOuter();
06. }
07. class MyInner {
08. public void seeOuter() {
09. System.out.println("Outer x is " + x);
10. System.out.println("Inner class ref is " + this);
11. System.out.println("Outer class ref is " + MyOuter.this);
12. }
13. }
14. public static void main (String[] args) {
15. MyOuter.MyInner inner = new MyOuter().new MyInner();
16. inner.seeOuter();
17. }
18. }

What is happening when we try compile the code?
Line 11 and line 15 can be strange, but both are absolutely correct.
See the line 11 first:
11. System.out.println("Outer class ref is " + MyOuter.this);

To reference the “outer this” (the outer class instance) from within the inner
class code, we can use .this.

Line 15:
15. MyOuter.MyInner inner = new MyOuter().new MyInner();


To access the inner class, we must have an outer class instance. If we have one then the <OuterClassInstance>. new <InnerClassConstructorglt; create a new inner class instance.
So the right answer is: the code compiles without error.

Puzzle 3
Given the following code:

01. class MyOuter {
02. private String x = "Outer";
03. void doStuff() {
04. String z = "local variable";
05. class MyInner {
06. public void seeOuter() {
07. System.out.println("Outer x is " + x);
08. System.out.println("Local variable z is " + z);
09. }
10. }
11. }
12. }

What is happening when we try compile the code?

The result is Compilation fails. The problem is with the line 8:
MyInner is a Method-Local Inner class and the Method-Local Inner classes can not access the local variables.

Of course, there is an exception:
If the local variable is marked as final then it can be accessed from a Method-Local Inner class.

Tuesday, June 24, 2008

Java Wrapper Classes, Autoboxing

Puzzle 1
Given the following code:

...
Integer i = new Integer( 1 );
System.out.println( ++i );
...

What is the output?
The output is:
2
This is surprising: How is it possible use ++ operator to objects? The answer is the autoboxing, what is available java 5 and above.

What's happening in the
System.out.println( ++i );

line?

Java unboxes, increments, reboxes the variable i, this is a good sample to autoboxing.

Puzzle 2
Given the following code:

class Boxing {
static Integer x;
public static void main(String [] args) {
doStuff(x);
}
static void doStuff(int z) {
int z2 = 5;
System.out.println(z2 + z);
}
}

What is the output?
The output is NullPointerException.

Why?
Variable x refers to null so the doStuff() method called with null parameter and at the z2 + z expression NullPointerException is trowed.

Saturday, June 21, 2008

Java Primitives Expert

Puzzle 1
Given the following code:

1. public class Example1 {
2. public static void main(String[] args) {
3. byte b = 1;
4. b = b + 1;
5. System.out.println("b: " + b );
6. }
7. }


What is the result?
The result is: Compilation fails.

Why?
The problem is in the line 4: possible loss of precision.
Decimal literals are implicit integers. So the type of literal 1 is integer. Before b + 1 expression computed, b is implicit converted to integer, and the type of b + 1 expression will be integer too.
We try assign an integer value (b + 1) to a byte variable, and it can be cause loss of precision so the compiler does not compile it.

Solution 1
Replace the line 4 to: b += 1; and auto cast will be work.

Solution 2
We can cast the (b + 1) expression explicit to byte: b = (byte) (b + 1);. We must use the brackets around the b + 1 expression, otherwise we cast just the variable b to byte, not the b + 1 expression.

Puzzle 2
Given the following code:

1. public class Example2 {
2. public static void main(String[] args) {
3. float f = 3.0;
5. System.out.println("f: " + f );
6. }
7. }


What is the result?
The result is: Compilation fails.

Why?
The problem is in the line 3: possible loss of precision.
Floating point literals are implicit double.

Solution 1
Cast explicit the 3.0 to float: f = (float) 3.0;.

Solution 2
Declare the 3.0 literal as float literal: f = 3.0f;

Puzzle 3
Giving the following expression:
( p <= q ) && ( q <= p ) && ( p != q )

Can this expression be true (If yes, when?).
Yes, it can.

How?
The answer is simply, autoboxing:
Declare the variables p and q as the following:

Integer p = new Integer(1000);

Integer q = new Integer(1000);

In this case our expression will be true, because
  • in the ( p <= q ) and ( q <= p ) expression p and q behave as primitive types so the expressions are true (because 1000 = 1000),
  • in the ( p != q ) expression p and q behave as objects, so we compare two object references and this references refer two different object, this expression is true.
  • ( p <= q ) is true, ( q <= p ) is true, ( p != q) is true, so ( p <= q ) && ( q <= p ) && ( p != q ) is true.
Puzzle 4 (my favorite)
Given the following code:

01. public class Example3 {
02. public static void main(String[] args) {
03. Integer i1 = 3;
04. Integer i2 = 3;
05. Integer i3 = 1000;
06. Integer i4 = 1000;
07. System.out.println("i1 == i2: " + (i1==i2) );
08. System.out.println("i3 == i4: " + (i3==i4) );
09. }
10. }


What is the output?
The output is:

i1 == i2: true
i3 == i4: false

Why?
First look the output is surprising.
The lines 3 - 6 are strange, but correct, because the autoboxing is worked.

We know the == operator compare object references. Variable i1 and i2 are object so we wait the i1 == i2 expressions will be false, but it's true!

And to top it all the i3 == i4 expression is false. How is it possible?

The answer is simply: Constant pool. JAVA use this pool (among other things) to store the decimal literals:

boolean:
  • true, false
char:
  • '\u0000' ... '\u007F'
byte:
  • -128...127
short
  • -128...127
int:
  • -128...127
long:
  • -128...127
When we use the new keyword then two, different object is constructed, and the == operator return with false:
  • Integer i1 = new Integer(2); Integer i2 = new Integer(2);
But when we don't use the new keyword, then the JAVA search the literal from Constant pool, and assign it to the references, then no object created:
  • Integer i1 = 2; Integer i2 = 2;
But remember, this works only type and range, given above!