Archiv der Kategorie: Java

Java techdocs

Deadly Diamond of Death

Deadly Diamond of Death

Hearty welcome from Java Code Online. Today’s topic is DDD, that is Deadly Diamond of Death. As promised in my earlier post, and as asked by some of my friends in their comments, I will pick this topic to clarify all the myths and doubts. Though the name is Deadly, the topic is not so Deadly, since it is avoided in Java. Java as we all know is a very powerful language. It has all the good features, and avoids all the bad features including the one which will be discussed today.

Java does not support multiple Inheritance. Though it is supported in C++, Java avoids it. The reason for avoiding multiple Inheritance is the Deadly Diamond of Death. Actually the class diagram that is formed in this scenario, is that of a diamond, and it is like a no solution output, so the code gets locked, so it is called Deadly Diamond of death. Thus the Java language do support multiple implementations, but not multiple Inheritance. So a class can implement many Interfaces, but can not extend more than one class.

I will explain the issue by taking an example. Suppose that Java supports multiple inheritance (though it does not, but still we will assume it to understand the current concept). Just go through the following points for a clearer understanding:-

1. Suppose that we have an abstract super class, with an abstract method in it.

2. Now two concrete class extend this abstract super class, and provides the implementation of the abstract method in the super class, in two different ways.

3. Now a fourth class comes into picture which extends the above two concrete classes. So now by the principle of inheritance it inherits all the methods of the parent class, but we have a common method in the two concrete classes but with different implementations, so which implementation will be used for the last child class which inherits both these classes?

Actually no one has got the answer to the above question, and so to avoid this sort of critical issue, Java banned multiple inheritance. The class diagram which is formed above is like that of a diamond, but with no solution or outcome, and so it is called Deadly Diamond of Death.

I will try to make it more clear, by taking an example. Take this:-

// This is our top most abstract class.
class AbstractSuperClass{
 abstract void do();
// These are the two concrete sub classes which extend the above super class
class ConcreteOne extends AbstractSuperClass{
 void do(){
  System.out.println("I am going to test multiple Inheritance");
class ConcreteTwo extends AbstractSuperClass{
 void do(){
  System.out.println("I will cause the Deadly Diamond of Death");
// This is our last class which extends both of the above concrete classes
class DiamondEffect extends ConcreteOne, ConcreteTwo{
 //Some methods of this class

Now what do you think will happen, when an Object of class DiamondEffect is made, and the do method is called?

Since the DiamondEffect class extends both the ConcreteOne and ConcreteTwo classes, it inherits the „do“ method from both of them, but the DiamondEffect class does not know which one to use when the method is called on it. The structure of class diagram here is like a diamond. This is the Deadly Diamond of Death.

I hope I was able to make my point clear. If you have any doubts or issues, then do write a comment for me, and I will try my best to answer you. You may leave a comment if you like the article. Java Code Online will see you later in the next post.


via Java Tutorial Online: Deadly Diamond of Death.

Compile, Run And Develop Java in the Console, Setup for TDD with JUnit

When you want to learn Java it is good to know about the basics.


  1. Text editor
  2. Java installed

check if java is installed.

java -version

Should be displayed something like that:

java version "1.6.0_24"
Java(TM) SE Runtime Environment (build 1.6.0_24-b07-348-9M3406a)
Java HotSpot(TM) 64-Bit Server VM (build 19.1-b02-348, mixed mode)

Creating Development Structure

expected we want to create a project folder and in it an src,bin,lib,test folder.
src = here you create source files (packages)
bin = Output folder
lib = for Libraries e.g. JUnit.jar
test = mirroed the package structure from src, here you develop your tests.

mkdir project
cd project
mkdir src
mkdir bin
mkdir lib
mkdir test

Write a first very simple program

cd src

type the following:

public class Main{
 public static void main(String[] args){
  System.out.println("Hello User");

Back to console compile! Just to see it runs. (You are still in folder src)


You should see now 2 Files and Main.class
To run the program just type

java Main

You should see

Hello User

Now delete the Main.class file.

Use Packages

It is recommend to use packages.
create a package (mkdir mypackage)
Java conventions says package names is always lowercase and have no special characters.
move into the package

mv mypackage/

Now compile (you are still in src)

javac mypackage/

You can run the program with 2 Ways

cd mypackage
java Main

Or back in folder src we have to set the classpath (-cp)

java -cp mypackage Main

Set output folder

delete mypackage/Main.class

javac -d ../bin mypackage/

Now the Main.class file should be in bin folder.
Run the program

cd ../bin
java Main

Or go to project folder and call the Main with classpath

cd ..
java -cp bin Main


Programmers are lazy so set the classpath.
To view the classpath type


If the output is Nothing then the variable isn’t set.
ensure that you are in project folder

export CLASSPATH=./bin

Now you can start the program from here with

java Main

Install JUnit

Download newest version from
Copy the download junit.jar file to your lib folder.
Add the jar to CLASSPATH

export CLASSPATH=$CLASSPATH:./lib/junit-4.9b2.jar

Test wether you reach the JUnitCore class

java org.junit.runner.JUnitCore

You should see something like this.

JUnit version 4.9b2
Time: 0,001
OK (0 tests)

For more information take a look at

Write a Simple Test

Go to test folder and create a Class SimpleTest with the following content

import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;
public class SimpleTest{
    public void testEmptyCollection(){
        Collection collection = new ArrayList();

Go back to project folder, compile and run the test.

cd ..
javac -d bin test/
java org.junit.runner.JUnitCore SimpleTest

Should be output

JUnit version 4.9b2
Time: 0,006
OK (1 test)


The example is taken from

The Cost of Testing or You don’t Know what You are Missing

The Cost of Testing or You don’t Know what You are Missing

Twice this week people challenged my belief in automated testing and Test Driven Development. The argument that was brought forward was simply: Unit tests are too expensive.

I actually believe the opposite is true. Let me tell you about a little dialog that happened in my development team after two developer where working on a feature for about an hour or two.

First Developer: “I think we got everything. Lets start the application and see if it works.” (starts the application)

Second Developer: “Hmm, doesn’t work.”

First: “Oh, I know, we forget to actually invoke the new feature” (fixes that and restarts the application)

Second: “Looks great. It works. Lets commit it to SVN”

What’s so special about this? They didn’t start the application a single time during the development process for over an hour. Can you do that without writing tests? Of course you can and you will spend restarting the application during the rest of the day until you fixed all the bugs. How long does your application need to restart? Including the time you need to navigate to the state where you can test your application. How long does that take?

Not having to do that. Or at least not very often is a huge time saver. And it’s not only the direct cost of restarting the application. Waiting for the application is often an interruption of your concentration. Do you really think about the next aspect of the feature to implement? Or do you check mail? Get a coffee? In my experience going Test Driven in Pairs is a way more concentrated type of working.

And that is not even considering that your tests will run over and over again, making sure later changes don’t break anything. This alone saved my butt a couple of times.

If you reached that level of TDD it will save money for you and your team. I promise.

But I’ll admit, I didn’t believed that a couple of years ago. I was using tests only when implementing rather abstract stuff. And I thought it wouldn’t be possible to efficiently automate tests for most of the code we wrote. I had to learn a lot. Testing isn’t easy. Most of the code we produce isn’t fizz buzz, but is concerned with GUIs and databases, both make testing hard and expensive. But these problems can be solved, so you can gain the benefit of TDD even for these cases.

And as a side effect you will have to come up with a really nice and clean design of your code in order to test it. This in itself will make future changes more easy and cheap.

Therefore I urge you: Start learning how to test today. If you don’t you will never know what you are missing.

And if promises don’t motivate you: I’m convinced that in a couple of years from now the places where you can just puke code into your IDE will get rare. So if you still have a couple of years to cover until retirement: Beef up your testing skills. It’s one of the best investments you can make in your own future as a software developer.

via Schauderhaft » The Cost of Testing or You don’t Know what You are Missing.

Gegen Schnittstellen, NICHT gegen Implementierungen programmieren

Wenn Sie gegen eine Schnittstelle programmieren, schreiben Sie bspw. List list = new ArrayList(); anstelle von ArrayList list = new ArrayList();, oder definieren als Parameter und Attribute Ihrer Methoden und Klassen keine konkreten Implementierungen, sondern lediglich die Interfaces List, Set, Map, Collection, …. Dies hat den Vorteil der höheren Generalisierung und Kompatibilität, aber auch den Nachteil von fehlenden Methoden und Funktionsweisen konkreter Klassen.

via :

The main reason to do this is to decouple your code from a specific implementation of the interface. By writing your code like this:
Map data = new HashMap();
then the rest of your code only knows that data is a Map, which is good, because it you can now easily change to a different implementation of interface Map if necessary. You’d only need to change that one line of code, for example to:
Map data = new TreeMap();
For the rest of your program, nothing changes – data is still a Map.
If you would have written:
HashMap data = new HashMap();
then changing it would have been much harder, because the rest of your code might have used methods that are specific to HashMap.

via: JavaRanch

Java: Constructors


When you create a new instance (a new object) of a class using the new keyword, a constructor for that class is called. Constructors are used to initialize the instance variables (fields) of an object. Constructors are similar to methods, but with some important differences.

  • Constructor name is class name. A constructors must have the same name as the class its in.
  • Default constructor. If you don’t define a constructor for a class, a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans).
  • Default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created.
  • Differences between methods and constructors.
    • There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value.
    • There is no return statement in the body of the constructor.
    • The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.

    These differences in syntax between a constructor and method are sometimes hard to see when looking at the source. It would have been better to have had a keyword to clearly mark constructors as some languages do.

  • this(...) – Calls another constructor in same class. Often a constructor with few parameters will call a constructor with more parameters, giving default values for the missing parameters. Use this to call other constructors in the same class.
  • super(...). Use super to call a constructor in a parent class. Calling the constructor for the superclass must be the first statement in the body of a constructor. If you are satisfied with the default constructor in the superclass, there is no need to make a call to it because it will be supplied automatically.

via Java: Constructors.

Good Logging Practice

Here are some useful thoughts about logging. Thanks to Jens Schauder.
Take a look at the link at the end to view the orginal post.

Good Logging Practices

Nearly everybody does some kind of logging in their application, but few do it in a well structured way. I’d like to point out some practices that I consider helpful in order to get the most out of your logging. This post will also work as a handout for my talk about logging at the herbstcampus conference. So here we go:

  1. Know your audience. If you look at the log files of many applications you quickly realize who the intended audience is: Developers. The log is full with technical detail, but not much of it makes sense to anybody else. The groups you probably should have on your list are: Developers on the search for bugs, performance issues, Administrators trying to install, start or shutdown your application and Support personal trying to detect and analyze problems or trying to verify that a problem did not occur. Once you realize there are different audiences you’ll understand what kind of information is helpfull in the logs.
  2. Use a framework. The major options are: Log4j, SLF4J, JUL, Commons Logging or Logback. Each one has it’s pros and cons, but they are all better then System.out.println. They allow you to configure at deploy or runtime, what gets logged where and in what format. If you don’t want to do any research, and don’t have special requirements, use SLF4J.
  3. Logging must be rock solid. If a logging causes problems. Throw it out. Don’t do experiments like remote logging, if you can avoid it.
  4. Define rules, when to use which Log Level: I propose the following:
    • DEBUG: Not important, except if you are researching a very specific problem.
    • INFO: General information like startup, shutdown, version and configuration of an application. Information about important decisions in the code or changes in the configuration.
    • WARN: Things that are fishy, but don’t represent a problem in themself, but might indicate a problem when appearing very often. E.g. a failed log in attempt is such a candidate. If it happens sometime it is not a problem, but if it happens a lot somebody might want to look into that.
    • ERROR: This should only be used when a problem occurs that somebody needs to look into. Typically but not necessarily relating to an exception in the code. Use this when only a limited part of the application is affected.
    • FATAL: If something goes completely wrong, rendering the application unable to recover this log level is appropriate, very likely accompanied by a shutdown of the application or the session.

    Of course your rules need some tayloring for your context, but absolutely need rules, and every developer must know and understand those.

  5. Log everything you log exactly once: When analyzing log files I often see log messages that always come in groups. This happens often when exceptions get caught, logged, and rethrown. Don’t do that. Log at the place where you actually do handle the exception. This is the only way to log an exception exactly once and also being able to decide which log level to use.
  6. Include useful information and data: The information should typically include answers to the following questions
    • Why are you logging this, typically the root cause of an exception.
    • What is the affected use case? Did it happen during creation of an order or when importing product data from a remote site?
    • What effect has it on the use case that was executing? Does the user need to repeat the action, or did it succeed? Did the complete batch fail, or just a single step?
    • What instance of the use case was effected? For example an order id.

    In order to make all this information available to your logs MDC (Mapped Diagnostic Context) is tremendously helpful. If you don’t know MDC, follow the link and read about it NOW. MDC exists also in SLF4J and Log4J and should be easy to port for other frameworks as well.

  7. Use more then one logging hierachy: The link contains more information about why. The simple idea is, that you can seperate different aspects you want to log by using different prefixes. This becomes especially usefull when adhering to the following points
  8. Log the time needed for stuff which might be intersting for tuning: Of course this includes the time used for access to remote resources (e.g. webservices or databases) and execution of complex algorithms, but possibly also the time spend in the various layers in the application. You can use different log level for three categories, a separate logging hierarchy for separating performance logging from other stuff. Performance problems a notorious difficult to hunt down, especially when they appear over time. You’ll love this logs, when performance becomes an issue.
  9. Log stuff that worked, not only what failed: Distributed systems become common place more and more. When debugging distributed system one often has the situation that requests just disappear, and it can be extremely challenging to decide which component failed. After all not everybody does such a fine logging as us, right? So I recommend the following log events:
    • RECEIVED: The application received a request through the UI, a Webservice or any kind of interface offered.
    • SEND: The application send a request to some other component.
    • GOT ANSWER:  The application got a reply to a request it send.
    • ANSWERED: The application answered to a request it received.
  • Log how often stuff happens: One possible reason for decreasing performance is a changed usage pattern. So logging how often per day, hour or minute a certain kind of use case is triggered can help tremendously.
  • via Schauderhaft |

    Überlegungen zum Logging

    Logging (z.B. in eine .log-Datei oder in eine SQL-Datenbank) ist eine große Hilfe sowohl während der Entwicklungszeit als auch später zur Fehlersuche beim Kunden.

    Logger erlauben das selektive Ein- und Ausschalten bestimmter oder aller Log-Meldungen zur Laufzeit über eine einfache textbasierte Steuerdatei.

    Bewährt haben sich folgende Vorschläge:

    • Verlassen Sie sich nicht auf das sehr rudimentäre und nur für bestimmte Exceptions durchgeführte Logging des Application Servers (normalerweise nur für unchecked RuntimeExceptions, die bis zum EJB-Container gelangen).
    • Verwenden Sie kein Logging per ‚System.out.println(„…“);‘, die Konsole ist nicht immer sichtbar und solche Ausgaben sind nicht zur Laufzeit konfigurierbar.
    • Verwendung von Log4j.
    • Alle unerwarteten Exceptions sollten zu einem Logging-Eintrag führen.
    • Zusätzlich können Auslastungs- und Performancekennzahlen sinnvoll sein.
    • Umlaute (ä, ö, ü) und deutsche Sonderzeichen (ß, §, €) sollten vermieden werden.
    • Falls Ausgabe in Datei: Jede Meldung produziert genau eine Zeile, damit ‚grep‘ verwendet werden kann (Ausnahme: StackTrace).
    • Wichtig ist eine einheitliche Struktur der Logging-Meldungen, damit sie mit Tools ausgewertet werden können.
    • Definition stets zu verwendender ‚Rubriken‘: Bei Ausgabe in SQL-Datenbank entsprechen die Rubriken den Tabellenspalten, bei Ausgabe in Datei werden Rubriken durch Semikolons getrennt (.csv-Datei, kann direkt z.B. in Excel bearbeitet werden).
    • Die Rubriken können zum Beispiel sein (in Application-Server-Umgebung): Zeitstempel; Anwendungsname; Thread-Name; Log-Level; Exception-ID; Fehlercode; Meldetext.
    • Der Zeitstempel (Timestamp) formatiert nach ISO 8601 (EN 28601, DIN 5008), also beginnend mit dem Jahr (z.B. ‚yyyy-MM-dd HH:mm:ss.SSS‘), damit einheitlich mit Tools ausgewertet werden kann und damit nach Datum sortiert werden kann.
    • Damit in mehrschichtigen Multithreading-Umgebungen zusammengehörende Exceptions identifiziert werden können, kann eine ‚Exception-ID‘ (automatisch) generiert werden. Auch sollte doppeltes Logging vermieden werden. Siehe hierzu: ‚‘.
    • Fehler, die möglicherweise zum Beispiel vom System-Operator bearbeitet werden müssen, sollten eindeutige Fehlercode-Nummern erhalten, zu denen in einer Dokumentation das weitere Vorgehen beschrieben ist.
    • Falls Fehlermeldungen oder Logging-Meldungen mehrsprachig sein sollen, verwenden Sie statt der Meldetexte Fehlernummern, die dann über .properties-ResourceBundles aufgelöst werden.

    via Exception Handling und Logging.

    global variables in Java

    There are no global variables in Java in the meaning of variables which would be valid in the whole program.

    There are

    • class variables: These are most similar to what are called „global“ variables in other languages. They are declared inside a class with the static keyword. There is only one variable for the whole class. (If the class would be loaded again with another classloader, this new class would have new variables, of course.)

      They should be used prefixed with the class: MyClass.varName. Inside of the class you also can let the prefix away, and you also could use them prefixed with an object of that type (but this is discouraged).

    • instance (or object) variables: These are what you have in your example: anything declared inside a class (and outside of any method/constructor/block) without the static keyword is a instance variable. For each object of the containing class (which includes objects of any subclasses of this class) there is exactly one variable. (From the „state“ view, one could say an object consists of all its instance variables + an identity.)

      They are used prefixed by an object (of the right type): myObject.varName. Inside of non-static methods of this class you can use them unprefixed (this is then referring to the variables of the current object).

    • local variables: These are all variables declared inside of a method or a constructor (or block). They exist once for each invocation of this method, and cease to exist after the method finished. They can only be accessed from inside this method, not from methods called from there.

      Special cases of these are method/constructor parameters and catch-block-parameters.

    • array elements: Every element of an array is a variable of the same type. They can be used everywhere where one has a reference to this array (often in one of the other types of variables).

    via: Java only allowing global variables to be static? – Stack Overflow.

    How to validate email address with regular expression

    How to validate email address with regular expression.


    Whole combination is means, email address must start with “_A-Za-z0-9-” , optional follow by “.[_A-Za-z0-9-]“, and end with a “@” symbol. The email’s domain name must start with “A-Za-z0-9″, follow by first level Tld (.com, .net) “.[A-Za-z0-9]” and optional follow by a second level Tld (, “\\.[A-Za-z]{2,}”, where second level Tld must start with a dot “.” and length must equal or more than 2 characters.

    API – Blog von Jens Franke » Flash

    Ich will niemandem den Spaß am Spielen mit den APIs nehmen, aber schreitet als Entwickler ein, wenn Dritte API-Demos zu einem Konzept zaubern. Verwendet ihr APIs von Dritten, dann solltet ihr immer ausreichend Buffer einkalkulieren.

    Nicht selten kommt man in Grenzbereiche der API, wo man sich entweder tief in die API einarbeiten muss, um sein Ziel zu erreichen oder einfach in der Abhängigkeit gefangen ist und warten muss bis die API-Entwickler einen erhören und dann auch noch das Richtige veröffentlichen.

    Eine Gradwanderung, die viel Feingefühl und einen kühlen Kopf benötigt.

    Blog von Jens Franke » Flash.