Monday, December 31, 2012

Inner classes and static nested classes

Terminology
Nested classes are divided into two categories:
  • static. They are simply called static nested classes.
  • non-static. They are called inner classes. 
Ideology
Reasons for using nested classes:
  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • Nested classes can lead to more readable and maintainable code.

Notes
  1. Access modifiers (private/public/protected) have no effect on inner classes - independant of the modifier, the classes are public.
  2. Inner classes could access members of outer class, no meter of their access modifier.
Usage out of the outer class

Sunday, December 30, 2012

Passing method arguments - by value or by reference. Theory and examples

When Java passes method arguments (parameters) by value and when by reference?
Here we put the major cases and below you will get an working example of it.

Rules:
  • primitive types are passed by value (example in swapPrimitives function);
  • arrays data is passed by reference (example in swapInArray function);
  • reassigning the argument inside the method does not affect the variable in the caller function;
  • all methods called on the arguments are called on the real object (argument variable could be changed);
We will describe the rules with swap function. Some of the methods are wrong and do not swap its arguments. After the code is the output of the program.

Code example:

Thursday, December 20, 2012

Java tests

Question 1: You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
  1. ArrayList
  2. LinkedList
   
Question 2: Inner classes can be defined within methods.

SQL tests

Example data 1:
==============================
|FirstName      |LastName    |
==============================
|'Peter'        |'Hansen'    |
|'Peter'        |'Jackson'   |
|'John'         |'Nilsen'    |
|'David'        |'Jackson'   |
==============================


Question 1: Lets have Example data 1;
How much rows will return this query:

SELECT * FROM Persons A, Persons B WHERE
(A.FirstName = B.FirstName Or  A.LastName = B.LastName) AND NOT
(A.FirstName = B.FirstName AND A.LastName = B.LastName)

Thursday, December 13, 2012

SQL GROUP BY and HAVING in examples

Here we show you the usage HAVING and GROUP BY. As an advance, we have an example with GROUP BY multiple columns.
In first section you have got the data schema. Later you have some tasks on it. After that you have the solutions for the tasks.

Singleton design pattern in examples

The singleton is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

There are different ways of implementation.

Lazy Singleton aka Singleton with double-checked locking

Wednesday, December 12, 2012

Kickstarting WebServices with REST

Here is an another nice tutorial for web services in Java. This time, the protocol used is REST, so we get RESTful services. There is a how-to to create server application for webservice. The build system is Maven.

TODO - to be tested!

hashCode() and equals()

Rule 1: The connection between hashCode() and equals():
If x.equals(y), then x.hashCode() must be same as y.hashCode().

Rule 2: Overwriting hashCode() or equals():
If you overwrite one of these functions, you have to overwrite the second too.

When you need to overwrite equals?

Tuesday, December 11, 2012

Stateless and stateful protocols

A stateless protocol is a communications protocol that treats each request as an independent transaction that is unrelated to any previous request so that the communication consists of independent pairs of requests and responses. A stateless protocol does not require the server to retain session information or status about each communications partner for the duration of multiple requests. In contrast, a protocol which requires the keeping of internal state is known as a stateful protocol.


Examples of statefull and stateless protocols

Saturday, December 8, 2012

Friday, December 7, 2012

having syntax in SQL

sql HAVING example:
SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000



sql HAVING Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value



Here is a nice example with having.

Could we have memory leaks in Java?

Yes, here it is explained why.

Unused references

Code that keep useless references to objects that will never use again, and at the same time never drop those references; one may say those cases are not "true" memory leaks because there are still references to those objects around, but if the program never use those references again and also never drop them, it is completely equivalent to (and as bad as) a "true memory leak".

Java Native Interface

While implementing JNI functionality, you could

Tuesday, December 4, 2012

Defining dependency projects in Maven

The problem: You have 2 projects and one relies on the second. How to realize that with maven?

Solution: Make the inner one. And define it as dependency in the another. Use the same groupId and artifactId. Easy one!

But if project Z depends on projects A and project B. And A and B use different versions of a library. Which version will be used in calling project?

Here is the code of this situation:

Differences between ear, jar and war files

Lets see the similarities and differences between ear, jar and war files.
All these files are simply zipped files using java jar tool, but they are created for different purposes.

JAR files
The .jar files contain the libraries, resources and accessories files like property files. JAR file could have an optional Manifest file, which contains package and extension related data.

Friday, November 30, 2012

Uncategorized questions

Which two method you need to implement for key Object in HashMap?
In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java. Read How HashMap works in Java for detailed explanation on how equals and hashcode method is used to put and get object from HashMap. You can also see my post 5 tips to correctly override equals in Java to learn more about equals.

What are the ways in Java for indication an error in a method?
Return value;
Throwing an exception.
Changing the object state in a parameter of the method. The method has t o be passed by reference;


Other sources of Java information


http://javarevisited.blogspot.com

Strings in Java

Differences between creating String as new() and literal assigning?
Described as code, the question transforms in this:
String a = "abc";
String c = new String("abc");


Just a note, which is basic for all comments below – String in Java is immutable.
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

Lets look some functionality differences:

Thursday, November 29, 2012

Immutable objects

Immutable objects
Immutable objects are objects whose state cannot change after construction. Examples of immutable objects from the JDK include String and Integer. (String methods, such as String.replace do not change the instance, but create new Strings)

Requirements for immutable classes:
•    ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private;
•    make fields private and final;
•    force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setter methods
•    do not provide any methods which can change the state of the object in any way;

Threads in java

Problem 1:
You have thread T1, T2 and T3, how will you ensure that thread T2 start after the end of T1 and thread T3 will start after T2 end?
Solution:
By using Thread.join();
     t1.start(); 
     t1.join(); 
     t2.start(); 
     t2.join(); 
     t3.start(); 
//     t3.join();  - not needed


Problem 2:
"You have T1, T2, and T3. T1 and T2 can execute concurrently, but T3 has to wait for both of them before it can run."
Solution:
     t1.start(); 
     t2.start(); 
     t1.join(); 
     t2.join(); 
     t3.start();
 

Compare wait and sleep methods in java
Wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution.

Wait is defined in Object class, where sleep methods are defined in Thread class.

Both could throw InterruptedException.


Collections questions

Differences between Iterator and Enumeration?
Iterator duplicate functionality of Enumeration with one addition of remove() method and both provide navigation functionally on objects of Collection.

Difference between Set and List in Java?
In Set the order of the elements in not saved.Set doesn't allowed duplicate while List does and List maintains insertion order while Set does not. Set uses the method equals() internally, not ==.

How do you Sort objects on collection?
The class Collections has functionality for sorting collections. There are two most used methods for this:
Collections.sort() - called without Comparator. It uses Comparable interface in Java. The order is the default , which is specified by CompareTo method;
Collections.sort(Comparator) will sort objects based on compare() method of Comparator. See Sorting in Java using Comparator and Comparable for more details.


Tuesday, November 27, 2012

Similarities and differences between HashMap, Hashtable, ConcurrentHashMap and synchronizedMap

There are several similarities and differences between HashMap, Hashtable, ConcurrentHashMap and synchronizedMap  in Java. (I name synchronizedMap the object retrieved by Collections.synchronizedMap(map) method.)

Monday, November 26, 2012

Fail-fast vs fail-safe iterators

Fail-fast iterators
"Fail-fast iterator" means that if the collection class is structurally modified at any time after the Iterator is created, in any way except through the Iterator's own remove or add methods, the Iterator will throw a ConcurrentModificationException.

 Throwing ConcurrentModificationException is not granted, so you have NOT to relay on it. ConcurrentModificationException is used to show the developer that his/her classes are not synced.

Most ifiterators in Java are fail-fast, these found in classes:
- LinkedList
- ArrayList
- Vector

Fail-safe iterators
Fail-safe iterator doesn't throw any Exception if Collection is modified structurally.

Advanced view over Concurrent collections

A nice article for java syncronization from IBM developers:
http://www.ibm.com/developerworks/java/library/j-jtp07233/index.html

Friday, November 23, 2012

Waterfall design model

The waterfall model is a sequential design process, often used in software development processes, in which progress is seen as flowing steadily downwards (like a waterfall) through the phases of Conception, Initiation, Analysis, Design, Construction, Testing, Production/Implementation, and Maintenance.

Thursday, November 22, 2012

LinkedList, ArrayList & Vector classes - differences

LinkedList, ArrayList & Vector are tree different implementations of the List interface. LinkedList implements it with a doubly-linked list. ArrayList & Vector classes implement it with a dynamically resizing array.

Fat and thin client architecture

Fat client
A fat client (sometimes called heavy) is a client in client–server architecture that typically provides rich functionality independent of the central server.

MVC or Model–View–Controller

Model–View–Controller (MVC) is an architecture that separates the representation of information from the user's interaction with it.

The model consists is the core of the existing system, where are placed application data and business rules.

The controller mediates input, converting it to commands for the model or view.

A view can be any output representation of data, such as a chart or a diagram. Multiple views of the same data are possible

Wednesday, November 21, 2012

Java "final" modification

In the Java programming language, the final keyword is used in several different contexts to define an entity which cannot later be changed (or reassigned).

Tuesday, November 13, 2012

wait and notify methods in Java

Java includes an elegant inter-process communication mechanism via the wait( ), notify( ), and notifyAll( ) methods. All three methods can be called only from within a synchronized method. Although conceptually advanced from a computer science perspective, the rules for using these methods are actually quite simple:

Monday, November 12, 2012

Software Team Leader Responsibilities

Here are the main responsibilities for a team leader, no matter of language: Java, C++, C#, PHP or whatever.

  • responsible for delivery of working software;
  • prioritize the tasks of team members;
  • to ensure the team is self-organising so that we take collective responsibility for the work we do. It is not my job to tell people what to do but to enable them to do it themselves;
  • responsible for all problems in team;
  • no single responsible for a task. To ensure no one person in my team is solely responsible for any task or activity so that we are able to continue working effectively when any of our team is away
  • monthly one-to-one meetings with team members;


Good practices:
  • buddy assignment to new members

Monday, February 13, 2012

Using the @deprecated Javadoc Tag

You can use the @deprecated tag to make Javadoc show a program element as deprecated. The @deprecated tag must be followed by a space or newline. In the paragraph following the @deprecated tag, explain why the item has been deprecated and suggest what to use instead.

One of the Java language's built-in annotations is the @Deprecated annotation. To use it, you simply precede the class, method, or member declaration with "@Deprecated".

Examples