Image Image Image

Sunday, December 6, 2015

Java Interview questions - Beginner level - 1


What is a final variable and effectively final variable in Java ? And give an example ?


final variable :  A variable or parameter whose value is never changed after it is initialized is final.

effectively  final variable : A variable or parameter is not declared as final and still the whose value is never changed after it is initialized is effectively final.


Why is the below program never generate a NullPointerException even the instance is null ? 

  Test t = null;
  t.someMethod();


   public static void someMethod() {
    ...
  }



There is no need for an instance while invoking static member or method.

Since static members belongs to class rather than instance.

A null reference may be used to access a class (static) variable without causing an exception.



What is the output of the below lines of codes ? 

System.out.println(null+"code");
System.out.println(2+3+"code");
System.out.println("test"+2+3+"code");


nullcode
5code
test23code



Why you are not allowed to extends more than one class in Java where as you are allowed to implement multiple inheritance?


In case of extends Ambiguity problems may raise where as in case of interfaces, single method implementation in one class servers for both the interfaces.




 int a = 1L; Won't compile and int b = 0; b += 1L; compiles fine. Why ? 

When you do += that's a compound statement and Compiler internally casts it. Where as in first case the compiler straight way shouted at you since it is a direct statement.


Why it is printing true in the second and false in the first case?? 


public class Test
{
    public static void main(String[] args)
    {
        Integer a = 1000, b = 1000;
        System.out.println(a == b);

        Integer c = 100, d = 100;
        System.out.println(c == d);
    }
}

output:

false
true

The second output is true though we are comparing the references, because the JVM tries to save memory, when the Integer falls in a range (from -128 to 127). At point 2 no new reference of type Integer is created for 'd'. Instead of creating new object for the Integer type reference variable 'd', it only assigned with previously created object referenced by 'c'. All of these are done by JVM.



What is the access level of default modifier in Java 

Default access modifier is package-private - visible only from the same package



Write a Program to check below the given 2 Strings are Anagrams or Not ?
For ex, below 2 strings are anagrams
String s1="home";
String s2="mohe";


Write program to reverse String("Java Programming")without using Iteration and Recursion?

Give me a real world example, where I have to choose ArrayList and Where I have to choose a LinkedList ?

What is the difference between a Iterator and a ListIterator ? 


What is the advantage of generic collection?

When can an object reference be cast to an interface reference?







Friday, September 18, 2015

Initialize byte array in Java and converting byte array to String


Just like any other Array, Byte array also have  the same syntax.

Below is  just an example to initialize a byte array.


byte[] bytes = [69, 121, 101, 45, 62, 118, 101, 114, 61, 101, 98];

But when you try to initialize your byte array, you will get compile time errors some times for bigger values.

For ex :


byte[] bytes = [69, 121, 101, 45, 62, 118, 101, 114, 196, 195, 61, 101, 98];


That code won't compile and you'll see a compile time error at the numbers, 196,195. The reason is that, Byte can hold up to the values  -128 to 127 only since it is 8 bits. Values greater or lesser than that should explicitly cast to byte so that they become bytes and not int's.

Hence here is the array after the  cast from int to  byte.



byte[] bytes = {69, 121, 101, 45, 62, 118, 101, 114, (byte) 196, (byte) 195, 61, 101, 98};


If you see, we casted the int values to bytes so that they sit in place of bytes.



Converting byte array to String : -



 Here is a small example to convert out byte array to a String in required charset format.


  String data = new String(bytes, StandardCharsets.UTF_8); 



Tuesday, September 15, 2015

Orphaned case error in Java Switch case

Orphaned Case Error in Java is one of the rarest errors you can see in Java. You can see this error  in cases like


  • When you write your case statements outside your switch statement. 

 switch (var) {  
       case 1:  
       //some code here....  
       break;   
 }  
   case 2:  
       //some code here....  
       break;


  • If by mistake if you terminated your switch testaments unexpectedly 


 switch (var); { <--- statement terminated by ;   
     case 1:   
     //some code here....   
     break;    
  }  

And in another case  where a case statement doesn't belong to switch and became orphan.


Note : Errors like this won't be seen if you are using an IDE since they compile your code on the fly and show the error message immediately, only traditional compilers will show this error, when you compile through your command line.






Wednesday, September 9, 2015

Contacting server with GWT. And complete example of RPC call.

There are couple of  possibilities to hit the database with GWT like RequestFactory and RPC.

Before getting started with server calls please go through,

 - GWT RPC (Which makes server calls Asynchronously)

 - RequestFactory (Alternative to GWT-RPC  which use proxies in between).

In this perticular post, let see the complete example of GWT RPC call to server.

Simple RPC structure can show  as below :

 GWT Code <===> InterfaceAsync <===> Interface (Synchronous)<===> Server Code 


Ok, Let's write code for small RPC, which is a PingPong. Client just says Ping to server and server responds with Pong.

ASynchronous Interface PingPongRPCInterfaceAsync , which we can able to access on client side.

     import com.google.gwt.user.client.rpc.AsyncCallback;  
     public interface PingPongRPCInterfaceAsync {  
     public void PingPongRPC (String message, AsyncCallback callback);  
     } 

The Synchronous Interface PingPongRPCInterface

   import com.google.gwt.user.client.rpc.RemoteService;  
   public interface PingPongRPCInterface extends RemoteService {  
     public String PingPongRPC(String message);  
   } 

Here is the  Service layer class which is equals to Servlet in J2EE and which implements our server side interface PingPongRPCInterface.

    public class PingPongRPCImpl extends  RemoteServiceServlet implements PingPongRPCInterface {  
     private static final long serialVersionUID = 1L;  
     public String pingPongRPC(Sting message)  
     {  
       // Hey I received a message here from client   
             // And sending response to client back   
       System.out.println("Message from client" + message);       
       String serverResponse= "Pong";  
       return serverResponse;              
     }  
   } 


Map the above server impl class in your web.xml;

     <servlet>  
     <servlet-name>beanrpc</servlet-name>  
     <servlet-class>com.server.pingPongRPCImpl</servlet-class>  
    </servlet>  
    <servlet-mapping>  
     <servlet-name>pingpongrpc</servlet-name>  
     <url-pattern>/pingpongrpc</url-pattern>  
    </servlet-mapping>


We all done with implementation part and let see how we can use this service call in our client side.

       private final pingPongRPCInterfaceAsync beanService =  
       GWT.create(pingPongRPCInterface.class);  
       ServiceDefTarget endpoint = (ServiceDefTarget) service;  
       endpoint.setServiceEntryPoint('pingpongrpc');  


Once you register your service you can just invoke the method from your client interface as
   

String message = "Ping to server";  
   beanService.pingPongRPC(message, callback);  
    AsyncCallback callback = new AsyncCallback()  
     {  
       public void onFailure(Throwable caught)  
       {  
         //Do on fail  
       }  
       public void onSuccess(String result)  
       {  
         //Process successfully done with result  
       }  
     };


And please note down the below package structures:

PingPongRPCInterfaceAsync ,pingPongRPCInterface should be in client* package
PingPongRPCImpl   should be in  server package.

That's a complete example of RPC. Please post in comments if you have any doubt or exception in middle of RPC.




  


Thursday, September 3, 2015

LinkedList in Java- Implementation, difference with array list, pros cons and example with time complexity

Linked list in Java


Another powerful weapon in Java's Collection API is LinkedList which is Doubly-linked list implementation of the List and Deque interfaces.

There are N number of Collection containers in the whole framework (List, Map, Etc ...), but choosing the right container for your data is the toughest job than operating it.


Here are the reason's to choose LinkedList over other containers 


1) When you want to add or remove the elements from the container over the time. This is the case when you don't exactly know the number of elements before in hand. You can choose ArrayList also as it also accepts the no of elements overtime but you don't see the performance differences under the hood.

2) If you are sure that you are not going to access the elements with Random index which costs O(n) [read big O notation to understand what is O(n)]. That means you are getting the elements only in sequential order all the time.

3) When you want overtime iterations, Linked lists are really cheap to do that.



LinkedList implementation type 


Java used doubly linked list implementation where the consumer have a choice to move and backward direction. If it is Singly linked list implementation you cannot have a choice of iterate over the list is reverse. 

In Doubly Linked list implementation each Node of data consists the information of it's next and previous Nodes. If you remove any Node in between, the previous and next will gets updates as required. Look at source of Linked List implementation.



Example to LinkedList 


public static void main(String args[]) {  
      List<String> linkedlist = new LinkedList<String>(); 
      //adding elements to LinkedList 
      linkedlist.add("string1");  
      linkedlist.add("string2");  
      linkedlist.add("string3");  
      //Adding First and Last Elements  in LinkedList
      linkedlist.addFirst("FirstString");  
      linkedlist.addLast("LastString"); 
      //This is how to get with index  
      linkedlist.get(1);  
      //This is how to set with index  in LinkedList
      linkedlist.set(1, "NewFirstString");  
      // Removing first and last elements from LinkedList  
      linkedlist.removeFirst();  
      linkedlist.removeLast();  
     // Removing elements from LinkedList with index  
      linkedlist.remove(2);  
    }

Pro's of LinkedList


LinkedList class can contain duplicate elements.
Java LinkedList class maintains insertion order.
Java LinkedList class is non synchronized.
In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
ava LinkedList class can be used as list, stack or queue.


Con's of LinkedList:


LinkedList cannot be accessed Randomly
Extra storage space for a pointer is required in case of linked lists
Reverse Traversing is difficult (If singly LinkedList)
Access time for Individual Element is O(n) whereas in Array it is O(1).



Thursday, August 20, 2015

Spring - What exactly Dependency Injection is ?

Image



Dependency Injection (DI):


The whole  Spring framework roam around the concept of  Dependency Injection (DI)  which is an implementation of  Inversion of Control. The Inversion of Control (IoC) is a software architect, which goes against the traditional procedural programming.

From wiki  of procedural programming is identified as 

In traditional programming, the custom code that expresses the purpose of the program calls into reusable libraries to take care of generic tasks, but with inversion of control, it is the reusable code that calls into the custom, or task-specific, code.


When writing a complex Java application, traditional programming makes an application tightly coupled between the connection points and make the code almost disqualifies to reuse. And then the term Inversion of Control coined.


With Inversion of Control (IoC) a drastic change happened in software architect and complex applications became a bunch of modules. With IoC, modularity of the application increases and thus extensibility as well. 


Coming to Dependency Injection -What is dependency injection exactly?  Dependency Injection is a methodology which implements IoC. This term really became a jargon and puzzling many minds for years. The simplest definition I found for the term DI is by James Shore 


Dependency injection means giving an object its instance variables. Really. That's it. 

Imagine Class Y is dependent on Class X. When ever there is a need of  Class X for Class Y, X will be injected to Y. That is all. There are several ways of Injections like Constructor Injunction, Setter Injection, Interface Injection. All these type are injection do the same but the ways are different. Main goal is to inject the dependency to it's receiver. 




Sunday, November 23, 2014

String comparison in Java. == vs equals method.

Just not to make everything Object oriented, primitives has been retained in Java. To resolve performance issues and to keep it as simple as it is, primitives has been introduced in most using OOP language till date. Lets just not discuss all the primitive concepts and sticking to the heading of this articles lets discuss about our favourite and peculiar Object, STRING.

Thursday, November 20, 2014

Identifiers and limit on Identifier length in Java (maximum length of Class,interface, package, method, variable names).

Fun time.

Though it is not a big thing to consider, yet out of curiosity one can interested to know about the limit on Class names, Interface names, Package names, Variables names, Method names etc.

Before going to start with that let me introduce the term identifier . What is it? The above all names so far we mentioned (Class, Interface, Package, Method, Variable names) are identifiers. Do not confuse with the terms literal and identifier and literal. Definition given by Oracle for Identifier is

Tuesday, November 4, 2014

Covariant, Contravariant and Invariant (class invariant) in Java

Type variance is another feature which defines the flexibility in code writing every of programming language. Let me show you some of the variant type jargon's which explains the type variance.

When ever we are talking about type variance,

Monday, October 13, 2014

Programming with interface and programming to interface

Another good habit that every programmer adopt is programming to interfaces, rather than programming to implementations. It is clearly not about using interfaces in your application, though you are using interfaces at design level, it is very hard to make coders to get benefit out it. There is a very big difference between programming with interfaces and programming to interfaces. The main difference is that

Wednesday, October 8, 2014

NoSuchMethodException vs NoSuchMethodError in Java

As we all know that there is a clear difference between Exception and Error. You can recover from an Exception but cannot from an Error. That's the basic difference. Coming to our actual problem which related to NoSuchMethod, we have NoSuchMethodException and NoSuchMethodException.

Tuesday, September 23, 2014

IOException : tmpFile renameTo classFile failed in JSP.

While coding with JSP I get random meaning less exceptions quite a time. Today when I run the Jsp suddenly ran in to the below exception.

HTTP ERROR: 500  
 tmpFile.renameTo(classFile) failed  
 RequestURI=/Index.jsp  
 Caused by:  

Friday, September 19, 2014

Constructor inheritance(ovveriding) and reasons behind restricting constructor inheritance in Java.

Inheritance is one the key concept of OOP. Being object oriented language, Java supports it. With inheritance every Child becomes a Parent. You can access the properties of Parent from a Child once you inherit Parent (using extends keyword). Here is a key point to note that, though you can access the members of Parent you cannot inherit/ or override constructor in Java.

Friday, August 29, 2014

Reason - Why Object as super class in Java ?

The Object class is the base for Java Language and we all reading the below sentences from day one of our Java Programming.

Every class is a Child of the Object class.
Every class in Java extends Object class.
Object class is the super class of every Java Class.

Monday, August 25, 2014

Creating a file from ByteArrayOutputStream in Java.

When we are dealing with data over the line, our option is bytes and one of the handy Class in Java to deal with bytes and streams together is ByteArrayOutputStream. When ever you want to write some bytes to specific file while receiving the data you just need to use the method writeTo().  

Thursday, August 7, 2014

Method without return statement in Java. Breaking method signature contract..

Caution : I'm just playing with java compiler and having fun. The below code demonstration is just for fun and do not try that in your Enterprise level code, so that you won't loose your job :P

*********************************************************************************

Have you ever tried to write a java method which has a return type and with out a return statement in implementation?? Let see a normal java method.

Monday, August 4, 2014

How to debug JSP with help of compiled Java files in Eclipse

When I'm trying to access my jsp page, some of my code causing the problem and  it ran into some exception :P. But I know there is something wrong and want to resolve the issue and I'm not sure on how to debug a jsp file in eclipse while it is executing. I'm seeing the exception after the execution and only clue is this stacktrace. So this is the exception i'm facing.

Friday, August 1, 2014

Compiler version : How String concatenation works in java.

The designers of Java decided to retain primitive types in an object - oriented language, instead of making everything an object. String class is one of them.String is the one of the most using(also confusing) class in Java. It is the class most used since to convey something(content), we need Information which is in the form of String.If someone showing / sending some information or passing some username / password to some system, what not most of the business depends on String only.

Monday, July 28, 2014

Difference between final and effectively final in Java.

While reading about Local classes, observed a brand new word called effectively final. The statement I read goes like "However, starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final." So started to find the exact difference between them.

Thursday, July 24, 2014

Multiple Inheritance in Interfaces supports in Java.

We all know that Java won't support multiple inheritance to avoid diamond problem. So there is no way of extending multiple classes in java. That ends the discussion about multiple inheritance in classes. But still Java allows multiple inheritance in Interfaces. That raises the question about the same diamond problem in Interface as well right?