Monday, December 30, 2013

Iterate Over a Map in Java

Most of the initial developers easily write iteration code  to iterate List and Set using for-each concept. Can we write the same to iterate over a map in java. The answer is yes.

Iterate Over a map.
This is most recommended and simple method to iterate map unlike getting the key set and get each value  from the map by  iterate the key set.

Map<Integer, Integer> map = new HashMap<Integer, Integer>();

for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            System.out.println("Key::"+ entry.getKey()+ "::Value::" + entry.getValue());

}

Wednesday, December 18, 2013

How to make a java class immutable

Most of us know about mutable and  immutable concept and advantages of immutable class in java.
But many of those think we can not make our own java class as immutable  and it is by pre defined. It is not true, we can make our own classes as immutable.
Any way as we discussing immutability concept I want to discuss the advantages of  immutability concept here.

Benefits 
Immutable classes
  1. Are automatically thread-safe and have no synchronization issues
  2. Do not need a copy constructor
  3. Do not need an implementation of clone
  4. Allow hashcode to use lazy initialization, and to cache its return value
  5. Do not need to be copied defensively when used as a field
  6. Make good Map keys  and set elements (these objects must not change state while in the collection)
Making Class as Immutable 
Java Documentation as itself some notes on this concept you can find that here  

1) Don’t provide “setter” methods  
Setter methods are meant to change the state of object and this is what we want to prevent here.
2) Make all fields final and private 
Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them
3) Declare class as final
 Don’t allow subclasses to override methods
4) Attention with mutable instance variables in class
Always remember that you can have either mutable  or immutable instance variables, identify them and return new objects with copied content for all mutable objects. Immutable variables can be returned safely without extra effort.

Example :

Tuesday, December 17, 2013

Abstract Factory Pattern

Abstract Factory patterns works around a super-factory which creates other factories. This factory is also called as Factory of factories. This type of java design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. 
In Abstract Factory pattern an interface is responsible for creating a factory of related objects, without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern.

Implementation of Abstract Factory Pattern

We're going to create a Shape and Color interfaces and concrete classes implementing these interfaces. We creates an abstract factory class AbstractFactory as next step. Factory classesShapeFactory and ColorFactory are defined where each factory extends AbstractFactory. A factory creator/generator class FactoryProducer is created.
AbstractFactoryPatternDemo, our demo class uses FactoryProducer to get a AbstractFactory object. It will pass information (CIRCLE / RECTANGLE / SQUARE for Shape) to AbstractFactory to get the type of object it needs. It also passes information (RED / GREEN / BLUE for Color) to AbstractFactory to get the type of object it needs.

Factory Pattern

Factory pattern is one of most used design pattern in Java. This type of java design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

Implementation of Factory Pattern

We're going to create a Shape interface and concrete classes implementing the Shape interface. A factory class ShapeFactory is defined as a next step.
FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object. It will pass information (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get the type of object it needs.


Friday, December 13, 2013

Proxy Pattern

In Proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern.
In Proxy pattern, we create object having original object to interface its functionality to outer world.
Implementation
We're going to create a Person interface and concrete classes implementing the Person interface.ProxyPerson is a a proxy class to reduce memory footprint of RealPerson object loading.
ProxyPatternDemo, our demo class will use ProxyPerson to get a Person object to load and display  Name as it needs.

Thursday, December 12, 2013

static keyword in java

The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
  1. variable (also known as class variable)
  2. method (also known as class method)
  3. block
  4. nested class

Tuesday, December 10, 2013

Job scheduling with Quartz

 Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs.

Job Scheduling

Jobs are scheduled to run when a given Trigger occurs. Triggers can be created with nearly any combination of the following directives:

Modifiers In Java

It is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers:

  • Access Control Modifiers : default, public, protected, private
  • Non Access Modifiers : static, final, abstract, synchronized

Identifiers in Java

Identifiers are the names of variables, methods, classes, packages and interfaces. Unlike literals they are not the things themselves, just ways of referring to them.
In the HelloWorld program, HelloWorldStringargsmain and println are identifiers.

Monday, December 09, 2013

Difference between length and length() in Java

length - This is a instance variable of array in java. It returns the length of an array, number of elements stored in an array.

length() -  This is a method in java. It is a static method of String class. It returns the length of a string object.

Friday, December 06, 2013

Flyweight Design Pattern

Flyweight pattern is primarily used to reduce the number of objects created, to decrease memory footprint and increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to decrease objects count thus improving application required objects structure.
Flyweight pattern try to reuse already existing similar kind objects by storing them and creates new object when no matching object is found. We'll demonstrate this pattern by drawing 10 Rectangle  of different locations but we'll creating only 2 objects. Only 2 types are available so type property is used to check already existing Rectangle objects.

Thursday, December 05, 2013

What's new in Java 7

I have been reading  about Java 1.7. There are articles about what's new,I have read them and compromised to write the language changes with examples.
So the normal developer can understand the changes easily by examples.Here I am mainly focusing on language  changes  I have taken these language changes from wikipedia https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7_.28July_28.2C_2011.29. You can see all other changes here.

Language Changes 
  • Strings in switch
  • Automatic resource management in try-statement 
  • Improved type inference for generic instance creation, aka the diamond operator <>
  • Language  Support for Collections.
  • Binary integer literals
  • Allowing underscores in numeric literals
  • Catching multiple exception types and re throwing exceptions with improved type checking

There is a list of other features available on the OpenJDK 7 features page.

Creating JSON data in Java


Download JAR file json-rpc-1.0.jar (75 kb)
import org.json.JSONObject;

JSONObject json = new JSONObject();
json.put("city", "Mumbai");
json.put("country", "India");

String output = json.toString();

Java Application without a main method

Can you write a java program which does not have main but it should be executable with out any errors and exception?

Think for a while before read this post....


Yes, You can write a runnable java program which does not have main method at all. This can be done using the static block of the class.

Wednesday, December 04, 2013

Introduction to Scala

   This post gives you the basic introduction to the scala programming language

Topics I am covering in this post are
  1. Classes
  2. Traits
  3. Objects
  4. Packages

Types of Inner Classes in Java

Static Inner Classes:

Syntax for static inner class is as follows:
<access-specifier> class OuterClassName {
    public static class <StaticInnerClassName> {
        . . .
    }
    . . .
}

Hadoop Tutorials

Tuesday, December 03, 2013

JAVA main method

1. You can have more than one method named main(...), as long as they all have different method signatures.

i.e.  Note that the final main(...) method in the demonstration code below will not compile, as a method's return type does not count as part of its signature.

public class ManyMains {
    public static void main(String[ ] args) {  }

    public static void main(String args) {  }

    public void main(String[ ][ ] args) {  }
    // public static String main(String[  ] args)  { return " ";  }          // will not compile: return type doesnt count in signature
}

Constructors

1 You cannot invoke constructors directly except from within other constructors.

2  Constructors invoking each other - by either super( ) or this(...) -  must be the first statement in the constructor code body.  Explicitly calling super( ) is entirely optional.  The JVM will do it anyway.

Converting Strings to int and int to String


int i = 2 ;
String a = String.valueOf(i);   //integer to numeric string
int j = Integer.parseInt(a); //numeric string to an int

Java Inner Classes

Inner classes, also called Nested Classes, are nothing but classes that are defined within other classes. The nesting is a relationship between classes, not objects.
Inner classes have clearly two benefits, name control & access control. In Java, this benefit is not as important because Java packages give the name control.
Java inner classes have feature that makes them richer and more useful. An object of an inner class has an implicit reference to the outer class object that instantiated it. Through this pointer, it gains access to any variable of the outer object. Only static inner classes don’t have this pointer. It is actually invisible when we write the code, but compiler takes care of it. Inner classes are actually a phenomenon of the compiler and not the JVM.

Eclipse “Not Declare Static Final SerialVersionUID” Warning


Whenever you write a Java class in Eclipse which implements java.io.Serializable interface, you’ll get this warning:
The serializable class XXXX does not declare a static final serialVersionUID field of type long

Why do we need serialVersionUID?

DateFormat with Multiple Threads


The DateFormat class is not thread-safe. The javadoc state that "Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally."
The following code shows how you would typically use DateFormat to convert a String to a Date in a single-threaded environment. It is more efficient to get the format as an instance variable and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.

abstract keyword


1  abstract can only appear on three things: a class, a method, or a named member inner class.

2  You cannot put abstract on a variable, a constructor, or an interface definition.

3 abstract can appear on methods inside an interface. But it is not required there.  Unlike the methods in an abstract class, some or all of which can be real, an interface's methods must always all be empty and abstract-like whether or not the keyword abstract actually appears on them..

4 A class must be declared abstract if any of the following three circumstances are true:

       (a) It contains one or more abstract methods, or
       (b) It inherits abstract methods which as yet have no implementations, or
       (c) It implements an interface but does not implement every method in it.

Monday, December 02, 2013

Java Singleton Design Pattern

Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best way to create an object.
This pattern involves a single class which is responsible to creates own object while making sure that only single object get created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

String Immutable

         An immutable object is an object which state is guaranteed to stay identical over its entire lifetime. This is really a good definition. Isn’t it? It means that the state of object once initialized, can never be changed anyhow.
Normally immutability in java is achieved through following steps :
  1. Don’t provide mutator methods for any field
  2. Make all fields final and private
  3. Don’t allow subclasses by declaring the class final itself
  4. Return deep cloned objects with copied content for all mutable fields in class
Please note that while it is possible to implement immutability without "final" keyword, its use makes that purpose explicit, to the human (the software developer) and the machine (the compiler).
           Java also has its share of immutable classes which are primarily String class and wrapper classes. In this post, we will understand the need of immutability for String class.

My First Android Program

Android Hello World


In this tutorial, we show you how to create a simple “hello world” Android project in Eclipse IDE + ADT plugin, and run it with Android Virtual Device (AVD). The Eclipse ADT plugin provided easy Android project creation.

Steps to develop an Android application :
  1. Install Android SDK
  2. Install ADT Eclipse plugin
  3. Create an Android Virtual Device (AVD)
  4. Create Android Project with Eclipse (IDE)
  5. Code it…
  6. Start it in Android Virtual Device (AVD)

Basic setup and installation

Android - Basic setup and installation

Let’s talk about Android development environment. Android development environment is made up of several parts that work together for you to build Android apps.
Let’s take a closer look at each one.

  1. Eclipse Integrated Development Environment
  2. Software Development Kit(SDK)
  3. Android development tool kit
  4. Android packages

Android Version History

Android :
Android is a Linux-based operating system designed primarily for touch screen mobile devices.

It is currently developed by Google in conjunction with the Open Handset Alliance. Initially developed by Android Inc, whom Google financially backed and later purchased in 2005.

Android mobile operating system began with the release of the Android beta in November 2007.

Versions :
Android beta
The Android beta was released on 5 November 2007.

Android 1.0
Android 1.0, the first commercial version of the software, was released on 23 September 2008.

Getting started with Jenkins


          Jenkins is an Open Source leading build server. It is used by many companies and organizations world-wide to build software in several different programming languages.
          It is written in Java, and the only requirements for getting it running are Java and the Jenkins archive, that you can get from jenkins-ci.org.
           Once you've download jenkins.war, you can execute Jenkins by simply type the below command

java -jar jenkins.war 

This should start Jenkins for you at http://localhost:8080.

Sunday, December 01, 2013

Uninstall liferay base portlets

  
     To uninstall(Remove) the liferay base portlets we need to add <include>false</include> to the portlet definition in liferay-portlet.xml file and remove respective display in liferay-display.xml.


    By doing the above we may have some issues with portlets which are using the resources of the removed one.So careful  at the time of removing .


  The best idle approach is : 

         Just clear out the ROOT/WEB-INF/liferay-display.xml file. Taking the portlets out of here will keep them all in Liferay but remove them from a user's ability to place them on a page. It's probably the least impacting way to do this.

Hooks

        Hooks are the most powerful plugin provided by liferay which can be used for customizing Liferay’s core features.
        We can definitely use EXT plugin which can be achieved by Hook plugin but for best practices, we should use hook plugin as it is hot-deployable and also easy for upgradation/migration process.


 Before you start actual development, you should know whether to use Hook or EXT.

Distributed Transactions

What is a distributed transaction?  Transactions that span over multiple physical systems or computers over the network, are simply termed D...