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.

Friday, June 27, 2008

SCJP Exam - Introduction

Sun Certified Programmer for the Java Platform, Standard Edition 6 (CX-310-065)
As I promised, I begin my series about the Sun Certified Java Programmer Exam. In my first post I write about the exam and the objectives. The next SCJP posts review the interesting and the dodgy part of the required knowledge to exam.



Exam objectives - What should I know?
Source: http://www.sun.com/training/catalog/courses/CX-310-065.xml

Sun divides the objectives to seven sections:

Section 1: Declarations, Initialization and Scoping

Section 2: Flow Control
  • Develop code that implements an if or switch statement; and identify legal argument types for these statements.
  • Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.
  • Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.
  • Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.
  • Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error.
  • Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.

Section 3: API Contents
  • Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.
  • Given a scenario involving navigating file systems, reading from files, writing to files, or interacting with the user, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader, BufferedWriter, File, FileReader, FileWriter, PrintWriter, and Console.
  • Develop code that serializes and/or de-serializes objects using the following APIs from java.io: DataInputStream, DataOutputStream, FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream and Serializable.
  • Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.
  • Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.
Section 4: Concurrency
  • Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.
  • Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.
  • Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.
  • Given a scenario, write code that makes appropriate use of wait, notify, or notifyAll.
Section 5: OO Concepts
  • Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.
  • Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.
  • Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.
  • Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, or overloaded constructors.
  • Develop code that implements "is-a" and/or "has-a" relationships.
Section 6: Collections / Generics
  • Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.
  • Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.
  • Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions. Write code that uses the NavigableSet and NavigableMap interfaces.
  • Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.
  • Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the "natural ordering" of primitive wrapper classes and java.lang.String on sorting.
Section 7: Fundamentals
  • Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.
  • Given an example of a class and a command-line, determine the expected runtime behavior.
  • Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.
  • Given a code example, recognize the point at which an object becomes eligible for garbage collection, determine what is and is not guaranteed by the garbage collection system, and recognize the behaviors of the Object.finalize() method.
  • Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully.
  • Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.
About the exam
Other exams/assignments required for this certification: None
Exam type: Multiple choice and drag and drop
Number of questions: 72
Pass score: 65% (47 of 72 questions)
Time limit: 210 minutes

Pop-up Window with Return Value

Trick
In this post a trick is presented: possibility to return object from a pop-up dialog.

It can be useful to
  • select and return an element of list from a pop-up dialog
  • create a new object in a pop-up dialog and return it
  • edit an object in a pop-up dialog and return it
Participants
Caller - the place, where the pop-up window is opened and the returned data is processed.
Dialog - this is the pop-up window, what produces the return object.

Step 1: Creating the dialog
Create a GUI window, what extends the javax.swing.JDialog class, like this:



My sample dialog creates and returns a String instance from a TextField.

Step 2: Extend the dialog code
First add a new class member to the created dialog class:

private <ReturnObjectClass> returnValue;

where the <ReturnObjectClass> is the class of the object, what our pop-up window returns, in my case:

private String returnValue;

Now write the actions to the buttons.
Cancel button close the window and return null:

returnValue =null;
dispose();

Return button close the window and return the new String:

returnValue = jTextField1.getText();
dispose();

At least construct the method, what return the created object:

public String getValue() {
this.setVisible(true);
return returnValue;
}

Step 3: Creating the caller
Create a class, named Main, and put the following code:

public static void main(String[] args) {
String s = new GetStringDialog(null, true).getValue();
System.out.println("Dialog returned with: " + s);
}

After you run this program, the pop-up dialog is showed and after clicking the Return button the typed string is written to the console.

Downloads
You can download sample code here as NetBeans project.

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 Keywords or Not?

Puzzle
The question is that, are the
  • null
  • true
  • false
words keywords in Java or not?

The answer is:
  • no, there are not.
The null, true and false words are literals, not keywords in Java.

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.

Monday, June 23, 2008

Mediator Design Patter

I present this post an useful adaptation of Mediator Design Pattern. We need often create GUI forms and of course we want to process the information given by users.

Participants of Mediator Design Patter
(based on Wikipedia)

Mediator - defines the interface for communication between Colleague objects.

ConcreteMediator - implements the Mediator interface and coordinates communication between Colleague objects. It is aware of all the Colleagues and their purpose with regards to inter communication.

ConcreteColleague - communicates with other Colleagues through its Mediator



Step 1: Create the Mediator interface
In the 1rst step we create the mediator interface:

1. public interface Mediator {
2. void setData( HashMap<String, Object> data );
3. HashMap<String, Object> getData();
4. }

Import the required classes and our Mediator is done.
Object will communicate over this interface with each other.


Step 2: Create the form
We create a simple GUI frame with two JTextField and two JButton, like this:



Step 3: Create the ConcreteMediator
To create the ConcreteMediator, implement the Mediator interface with our GUI Frame.
Change the
public class MediatorExample extends javax.swing.JFrame {

line to
public class MediatorExample extends javax.swing.JFrame imlements Mediator {

and implement the required methods, declared in Mediator interface:
public void setData(HashMap data) {
textfield_info1.setText((String) data.get("info1"));
textfield_info2.setText((String) data.get("info2"));
}
and
public HashMap getData() {
HashMap data = new HashMap();
data.put("info1", textfield_info1.getText());
data.put("info2", textfield_info2.getText());
return data;
}

Import the required classes and our ConcreteMediator is done (textfield_info1 and textfield_info2 are the name of two JTextField instance variable).


Step 4: Create the ConcreteColleague
In our example the ConcreteColleague has two function:
it can open a new Frame and fill it with initial data throught the Mediator interface
it can process form data throught Mediator interface.
My code:
public class ImportantDataProcessor {

public void showImportantDataDialog() {
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("info1", "This information is very important!");
data.put("info2", "And Top Secret!");

MediatorExample frame = new MediatorExample();
frame.setData(data);
frame.setVisible(true);

}

public void processImportantData(Mediator mediator) {
HashMap<String,Object> data = mediator.getData();

String info1 = (String) data.get("info1");
String info2 = (String) data.get("info2");

JOptionPane.showMessageDialog(null, info1 + "\n" + info2, "Important Information",
JOptionPane.INFORMATION_MESSAGE);
}
}

Import the required classes and our ConcreteColleague is done .


Step 5: Process the form
Now we write the onClick() events of the two buttons.
Exit button will close the application:
this.dispose();
and the Process... button will start the form processing:
new ImportantDataProcessor().processImportantData(this);
The "this" word refer to the GUI frame itself, what implements the Mediator interface.


Step 6: Start the application
Create a class, named Main, and put the following code:
public static void main(String[] args) {
new ImportantDataProcessor().showImportantDataDialog();
}


Downloads
You can download sample code here as NetBeans project.

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!