How do you handle error condition while writing stored procedure or accessing stored procedure from java?

When you call a store procedure the store procedure will execute in database server so if there any exception occurs that can be handled in EXCEPTION block in the store proc. If the store procedure it self fails it throws sql exception which can be handled by try/catch block and wrap it to your project specific exception.


example


try {

CallableStatement stmt=con.prepareCall("{call geNamebyId(?)}");

stmt.setInt(1,123);

stmt.execute();

} catch(SQLException e) {

e.printStack();

throw new CustomException(e);//application specific exception

}

What is JCS?

JCS stands for Java Caching System. This is an open source project and released by Apache written in Java.  Like all other caching system JCS  has following features.

1. JCS supports In memory cache.
2. Provide method for add objects in Cache.
3. provide method for retrieve objects from cache
4. provide method for delete objects from cache


apart from this you also can specify how long a object can store in memory.

JCS is used when a object is very costly, say a Composite object which is created by lots of database call and application use it very often. So it is better to put this object in JCS rather than create a new object instance  every time.

So JCS can be used in every application  which has large number of objects which are very costly and use very often.

JCS provide some additional features like
1. Very good memory management
2.Region data separation and configuration
3. Remote synchronization etc.

How to get client machine name and Ip address from Httpservlet?

In HttpServletRequest there are two methods
 a. getRemoteAddr()
 b. getRemoteHost()
 which will provide the necessary information.
 Actually in request header following information is stored.


Ip address of client m/c = request.getRemoteAddr();

Hostname of client =  request.getRemoteHost()

What is difference between include action and include directive in JSP?



Before starting the difference  discussion,  first, we have to understand the JSP life cycle. when a request first comes to a JSP it will translate into servlet then compile and load into web container for further use. Subsequent requests  will serve by this translated servlet.


Let say we have a JSP page called greet.jsp which includes another JSP call  header.jsp. Now it can be included in two ways
 1. by page directive 
 2. by JSP action tag
1. By page directive : syntax is <%@ include file="header.jsp" %>
now when greet.jsp page translated  into a  servlet all the code written in the header.jsp goes to translated servlet's service()(incase of Httpservlet it's //doget() or dopost()) method. so it acts as one servlet which contains two JSP's code ( header.jsp + greet.jsp  ) and ready for serve subsequent requests. Now in mean time suppose  developer change the content of header.jsp, this change will not reflect to translated servlet as it is already compiled and loaded in the web container  . To make this happen you have to restart web container then it will recompile  but some web container smart enough to pick up this changes. so  include page directive is  not a good option for dynamic pages.


2. By JSP action tag: syntax

<jsp:include page="header.jsp">
 Here inclusion is done at request time so it maintains two servlets unlike page directive so it will show updated value each time.  so action tag is the good choice  for dynamic pages.

Benifits of Static methods

Static keywords mean,  methods/variables attached to class, not with objects. So this variables/methods is shared with all objects instances of this class.Following advantages, we can get using static.

1. We can invoke a static method without creating objects. So Utility methods can be static

example

public class DateUtils
{
    public static Date getSystemdate()
{

    return  new Date(System.currenMillsInSecond());
}

  public static Date getPrevousDay()
{
}

//etc


}

.2. If you want to declare a Global value which will share among objects. suppose wants to calculate hit count of a servlet

public class Countservlet extends HttpServlet
{

    private static  int count = 0;

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException
{

     count++;
}

public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException
{

   doGet(request,response);
}



}




3. If you want to make a class level synchronization by synchronizing static you can achieve it.


public class Account
{

private static int min_balance=100;

public synchronize void credit(int amount)
{
  min_balance= amount;
}
}


Now no object can change the state of min_balance  as it is class level synchronization.

Can we have main method tn abstract class?

Yes, you can use the main method in abstract class. The main method is a static method so it is associated with Class, not with object/ instance. The abstract is applicable to the object so there is no problem if it contains the main method. In main method, you can not create an instance of the abstract class but you can instantiate other concrete class.


Here is a sample program


public abstract class TestAbstract {

public static void main(String[] args){

System.out.println("Hello world");

}

}



Can we Instantiate Abstract Class?

The main reason is   abstract class may have abstract methods . An abstract method is like template/contract, according to inheritance rule  every concrete subclass must have to provide a concrete definition of the same. So we can say the abstract method is the only declaration.

 Now for a moment we  assume we can create an instance of abstract class


so,  we have an abstract class name Shape and an abstract method getShape()

Abstract class looks like,
public abstract Shape

{

  public abstract getshape(); //Only declaration

}


Now, next step is to create an Object of abstract shape as we assume we can instantiate the abstract class.

 Shape s =new shape();

and call

 s.getshape();


Think what it will return as it is the only declaration!!!! so JVM functionality will break.


Due to that, we can't instantiate the abstract class.

Can we make constuctor as final

No Constructor can never be Final. Only private,public and protected modifiers can use with the constructor.


We use final in method level because  we don't want subclass inherits that method and overwrite it . But constructor is not a method and it can not be overridden as per java specification .

Let's think in a  different way


For say, constructor supports final now that mean's it can't be inherited but if you think about constructor call hierarchy then you can find the first statement of a constructor is super or this, so if the constructor is  not visible how it  can you call the super class constructor ? so we can't call the super class constructor, call hierarchy is uncompleted  so the object will not be created. For this reason, we can't use final in the constructor.

Why we called Java as Platform Independent?

Before starting why we called Java as platform independent I want to share a simple incident with you and understand the Java compilation process in terms of that story.


Say Narendra Modi our respected PM giving a speech in Hindi, Next day in every news daily irrespective of language(Hindi, English, Bengali) this speech is published. Now the question is Narendra Modi give that speech in Hindi so how it translates to English or Bengali seamlessly.


No surprise right, there are reporters for every newspaper they analysis that speech and transform it to another language like English or Bengali.


So I can say theoretically Modi's speech is Language independent as next day everyone sees it in their respective languages.


Java, Does it the same way, It takes your code as input like Modi's live speech and there is Java interpreter which is platform dependent, for Linux, Java provides Linux interpreter for Windows a Windows interpreter, Whose task it taking that input and transform it to Machine code the language OS understand. SO it is like the reporters who translate Modi's speech to respective language.

Now coming to Technical part. 


Actually, to be specific Java compilation is a two-step process Compile then Run Compiler makes the byte code and JVM inter-prate this to machine specific language Here is the trick  I am taking about , Might you have seen when you download JDK there is OS specific version  one is for Unix one is for windows version why so, because  of JVM implementation JVM takes bytecode as input and provide m/c language as output so Linux specific JVM makes Linux specific machine code, windows do the same but as both take bytecode as input you can easily export Windows compile class  Linux m/c That's why they called Java as a platform independent .

Overriding in Java in context of design.


Overriding in Java in context of design.

 


 While you are going for an Interview for a Lead or Developer role. The interviewer will definitely ask you some questions on Overriding and try to puzzle you.


In this tutorial, I try to cover all topics of Overriding so you feel comfortable and easily answer  whatever questions they ask


Definition of Overriding:
In Java, Overriding is a technique by which parent class delegates responsibility to Child. A child can define child specific behavior which will be executed at run time.

From the above definition, it is clear that to do Overriding Parent class and child class is must need, without Child class, we can't achieve overriding, unlike overloading.

Please remember , The interviewer may ask you-- can it be possible to do overriding without child class?

As I said child specific behavior executed at run-time what I mean by this is the  JVM will decide which  Subclass/Object's method it has to call,  so we call it late binding or Dynamic method dispatch.Because runtime JVM decides what to do not at compile time.

Question: What is late binding/ Dynamic method dispatch in Java

If you don't get my point don't worry follow example will clear the concept.



Before dig down to Overriding details let clear one small thing.


The big power of OOP programming is it supports Polymorphic assignment where a parent class reference can point a Subclass object. It will be heavily used in Design pattern or I can say the Whole Design pattern is based on this small concept.

 

Q: What do you mean by polymorphic assignment and Why it is important?


Let's understand why this is important.


say  Foo is Parent class and Bar is child class so we can do that,


Foo foo = new Bar();//Polymorphic assignment.

By parent reference, we can point child Object. It is logical as child inherited all properties of the parent so whatever in parent must have in the child unless properties are private in a parent.


What is the benefits of polymorphic assignment?
 let see the small code

Class Power
{

private Foo f;

public setFoo(Foo f)
{
this.f = f;

}

public void show()
{
f.print();
}
}

Class Foo has a print() method which is overridden in Bar and Zoo two subclasses of Foo

overridden  in Bar
public void print()
{
Sysout(“Bar”);
}


overridden in Zoo
public void print()
{
sysout(“Zoo”);
}

overriding java


so by the setFoo method in Power class, I can easily set Bar or Zoo instance at run time based on some business logic .so when it calls show method based on the subclass it prints Bar or Z

So I can easily change the behavior of the Power class on the fly based on strategy. It is the crux of Strategy design pattern.

But remember, As SetFoo method takes parent reference what ever method are in parent class  you can call those, all Association condition applied here. So if any new method added in subclass that is not visible by parent reference.

Qustion : expect a coding snippet here where interviewr add a method in child and try to call it by polymorphic refrence.

To make it visible you need to do down-casting.

Tip: Always use @Override annotation if you are using Java 5 or more to make sure if maintains all rules of overriding.


To do a perfect overriding we have to follow some rules.

The method which will be overridden must have same data signature also return type will be same

but onwards java 1.5 return type can be subclasses of parent type we say it Co-variant return.
 Q: What is covarient return?


Please follow the following contracts and burn it into the head as in Interview or in Exam you can found various types of combination and you have to find the perfect overridden method.
1. The argument list must exactly match that of the overridden method. If they
don't match, you can end up with an overloaded method .


2. The return type must be the same as, or a subtype of, the return type declared
in the original overridden method in the superclass. we say it covariant return


3. The access level can't be more restrictive than the overridden methods.
The access level CAN be less restrictive than that of the overridden method.
Instance methods can be overridden only if they are inherited by the subclass.
A subclass within the same package as the instance's superclass can override
any superclass method that is not marked private or final. A subclass in a
different package can override only those non-final methods marked public
or protected (since protected methods are inherited by the subclass).

4. The overriding method CAN throw any unchecked (runtime) exception,
regardless of whether the overridden method declares the exception.

5. The overriding method must NOT throw checked exceptions that are new
or broader than those declared by the overridden method. For example, a
the method that declares a FileNotFoundException cannot be overridden by a
the method that declares an SQLException, Exception, or any other non-runtime
exception unless it's a subclass of FileNotFoundException.

6. The overriding method can throw narrower or fewer exceptions.