Saturday, February 27, 2016

What happens if a class doesn't implement all the methods defined in the interface?


A class must implement all methods of the interface, unless the class is declared as abstract. There are only two choices:
  • 1.Implement every method defined by the interface.
  • 2.Declare the class as an abstract class, as a result, forces you to subclass the class (and implement the missing methods) before you can create any objects. 

The only case the class do not need to implement all methods in the interface is when any class in its inheritance tree has already provided concrete (i.e., non-abstract) method implementations then the subclass is under no obligation to re-implement those methods. The supclass may not implement the interface at all and just method signature is matched. For example,
interface MyInterface {  
  void m() throws NullPointerException;
} 

class SuperClass {
//NOTE : SuperClass class doesn't implements MyInterface interface 
  public void m() {
    System.out.println("Inside SuperClass m()");
  }
}

class SubClass extends SuperClass implements MyInterface {
}

public class Program {  
  public static void main(String args[]) {
    SubClass s = new SubClass();
    s.m();
  }
}


SimpleDateFormat and DateFormat

SimpleDateFormat is a class used to format and parsing dates in a locale sensitive manner. It is used to format date into text and parse text into date.
SimpleDateFormat is extends DateFormat class which is an abstract class for date/time formatting subclasses and provides many class methods for obtaining date/time matters based on any given locale. package com.lea.oops;

import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Date date = new Date();
       
        String str = date.toString();
        System.out.println(str);
       
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
        System.out.println(dateFormat.format(date));
    }

}

Abstraction in Java

What is abstraction? Abstraction is the concept of segregate the implementation of interface. It will focus only on essential details instead of showing the full implementation details. Abstraction can be applied through abstract class and interface.
Abstract class is something which is incomplete and provide common information for the subclasses. You cannot create instance for abstract class. If you want to use it you need to make it complete or concrete by extending it.
When do you use abstraction? When you know something needs to be there but not sure how exactly it should like.
Abstraction key points
  • Use abstraction if you know something needs to be in class but implementation of that varies. 
  • You cannot create instance of abstract class using new operator. 
  •  Abstract class can have constructor 
  •  A class automatically become abstract class when any of its method declared as abstract. 
  •  Abstract method does not have method body 
  •  Variable cannot be made abstract. Its only for class and methods 
  •  If a class extends an abstract class or interface it has to provide implementation to all its abstract method to be concrete class.

Friday, February 26, 2016

Why abstract class can have constructor in Java?

The main reason is, when any class extend abstract class, constructor of sub class will invoke constructor of super class either implicitly or explicitly.

Write a program to find the first non repeated character in a String?

package com.lea.oops;

import java.util.HashMap;
import java.util.Scanner;

public class FirstNonRepeatedCharacter {

    /**
     * @param args
     */
    public static void main(String[] args) {
       
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
       
        char c = firstNonRepeatedCharacter(s);
       
        System.out.println(c);
       
    }

    public static Character firstNonRepeatedCharacter(String str){
       
        HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
       
        int i, length;
        Character c;
       
        length = str.length();
       
        for (int j = 0; j < length; j++) {
            c = str.charAt(j);
           
            if (hashMap.containsKey(c)) {
                hashMap.put(c, hashMap.get(c)+1);
            }else{
                hashMap.put(c, 1);
            }
        }
       
        for (int j = 0; j < length; j++) {
            c = str.charAt(j);
            if (hashMap.get(c) == 1) {
                return c;
            }
        }
       
        return null;
    }
}

Wednesday, February 24, 2016

Java Timer and TimerTask Tutorials

java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals.
java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.

Timer class is thread safe and multiple threads can share a single Timer object without need for external synchronization. Timer class uses java.util.TaskQueue to add tasks at given regular interval and at any time there can be only one thread running the TimerTask, for example if you are creating a Timer to run every 10 seconds but single thread execution takes 20 seconds, then Timer object will keep adding tasks to the queue and as soon as one thread is finished, it will notify the queue and another thread will start executing.

Timer class uses Object wait and notify methods to schedule the tasks. TimerTask is an abstract class and we inherit it to provide concrete implementation. TimerTask class implements Runnable interface so it is a thread and hence your implementation of TimerTask is also a thread.

Example to print a repeated task for 5 times.
package com.lea.oops;

import java.util.Timer;
import java.util.TimerTask;

public class TimerTaskExample {

    Timer timer;
   
    public TimerTaskExample() {
        timer = new Timer();
        timer.schedule(new MyReminder(),  0, 1 * 1000);
    }
   
    class MyReminder extends TimerTask{
        int loop = 5;
      
        @Override
        public void run() {
            if (loop > 0) {
                System.out.println("Message "+loop+ "..!\n");
                loop--;
            } else {
                System.out.println("\nThat's it.. Done..!");
                timer.cancel();
            }
           }
      
    }
   
    /**
     * @param args
     */
    public static void main(String[] args) {
        new TimerTaskExample();
        System.out.println("Task scheduled..");
    }

}

Friday, February 19, 2016

How to use static fields within Spring XML Configuration

When configuring Spring through XML, you can use static fields in a similar way you use instances defined in the same XML or elsewhere. This is possible by using the util namespace as highlighted below.

<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-3.1.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">

  <bean id="myObject" class="com.javacreed.examples.howto.spring.StaticInXml">
    <constructor-arg>
      <list>
        <util:constant static-field="com.javacreed.examples.howto.spring.MyFields.OBJECT_1" />
      </list>
    </constructor-arg>
  </bean>

</beans>

How to make @RequestParam Optional?

A @RequestParam can be set as optional, by simply providing a default value to it as shown in the following example

@Controller
public class MyController {

  @RequestMapping(value = "/myApp", method = { RequestMethod.POST, RequestMethod.GET })
  public String doSomething(@RequestParam(value = "name", defaultValue = "anonymous") final String name) {
  // Do something with the variable: name
  return "viewName";
  }

}

How to get Auto-Generated Key with JdbcTemplate

Spring provides GeneratedKeyHolder class which can be used to retrieve the auto generated values.

The following class shows how to retrieve the auto generated key after a new value is added to the table.

package com.javarewind.examples.spring;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

public class ExampleDao {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  public long addNew(final String name) {
    final PreparedStatementCreator psc = new PreparedStatementCreator() {
      @Override
      public PreparedStatement createPreparedStatement(final Connection connection) throws SQLException {
        final PreparedStatement ps = connection.prepareStatement("INSERT INTO `names` (`name`) VALUES (?)",
            Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, name);
        return ps;
      }
    };

    // The newly generated key will be saved in this object
    KeyHolder holder = new GeneratedKeyHolder();

    jdbcTemplate.update(psc, holder);

    long newNameId = holder.getKey().longValue();
    return newNameId;
  }
}

Thursday, February 18, 2016

OOPs Concepts


Abstaractions, Encapsulation, Inheritance, Polymorphism and Composition are the important concepts for the object oriented programming/designs.

Abstraction:

Abstraction focuses only on outside view of an object. Helps us to identify which information should be visible and which information should be hidden.

Encapsulation:

Its a mechanism to hide the data, internal structure, and implementation details of an object.

All interaction with the object is through a public interface of operations.

Encapsulation means any kind of hiding:

-- Data Hiding
-- Implementation of Hiding
-- Class Hiding (Behind abstarct class or interface)
-- Design Hiding
-- Instantiation hiding

       Data Hiding: Use private members and appropriate accessors and mutators when possible.

       For example:
      • Replace
                 public float accuracy;
      • With
               private float accuracy;
               public float getAccuracy ( ) {
                  return (accuracy);
              }
              public void setAccuracy (float acc) {
                  accuracy = acc;
             }

                   
Inheritance [IS-A Reletionship]:

Method of reuse in which new functionality is obtained by extending the implementation of an existing object.
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another.
The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).

Polymorphism:

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic. 

Composition [HAS-A Relationship]:

Method of reuse in which new functionality is obtained by creating an object composed of other objects.

When we say “one object is composed with another object” we mean that they are related by a HAS-A
relationship.


The new functionality is obtained by delegating functionality to one of the objects being composed.
 

Composition encapsulates several objects inside another one.


 

Wednesday, February 3, 2016

What are checked and unchecked exceptions?

1) Checked Exception is required to be handled by compile time while Unchecked Exception doesn't.
2) Checked Exception is direct sub-Class of Exception while Unchecked Exception are of RuntimeException.
3) Checked Exception represent scenario with higher failure rate while Unchecked Exception are mostly programming mistakes.

Example of checked Exception 

IOException
DataAccessException
ClassNotFoundException
InvocationTargetException 

Example of unchecked Exception

NullPointerException
ArrayIndexOutOfBound
IllegalArgumentException
IllegalStateException

Why synchronized method is throwing error in interface?

Interface methods are abstract and will not have implementation details but synchronization is part of the implementation. So that its throwing compile time error while declaring synchronized methods in interface.