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

List of applications using GWT

In my initial days of GWT programming, with so many features why Google is not using GWT in it's own web applications. 

Later I found the below list of applications from Google which using GWT as their framework.


AdWords http://google.com/adwords

AdSense http://google.com/adsense


Flights http://flights.google.com


Hotel Finder http://www.google.com/hotelfinder


Offers https://www.google.com/offers


Wallet http://wallet.google.com


The New Blogger http://www.blogger.com/


Chrome Webstore https://chrome.google.com/webstore  


Product Search http://www.google.com/prdhp?hl=en&tab=mf


Public Data http://www.google.com/publicdata/home


New Google Groups http://groups.google.com


Orkut http://www.orkut.com


It seems there are many companies and famous websites also built with GWT. Will be back with complete list soon. 

Share it GWT lovers.

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.