Senin, 28 Juli 2014

10 Java Exception and Error Interview Questions Answers




You will always see some interview questions from Exception and Error
handling in core Java Interviews. Exception handling is an important aspect of
Java application development and its key to writing robust, stable Java programs,
which makes it natural favorites on interviews. Questions from Error and
Exception in Java mostly based on concept of Exception and Error in Java, How
to handle Exception , best
practices to follow during Exception handling
etc. Though multithreading,
garbage collection, JVM concepts and questions from object oriented design
rules these interviews, you should always expect and prepare some questions on
effective error handling. Some Interviewer also  test debugging skill of programmers, as
resolving Exceptions quickly is another trait of solid Java programming
knowledge. If programmer is familiar with infamous and dodgy ClassNotFoundException
or OutOfMemoryError,
there is a good chance that he has some good practical experience under his
belt. In this article we will see some Java Error and Exception interview
questions asked to fresher, experienced and senior Java developers in Java J2EE
interviews.







Java Exception and Error Interview Questions



Java Exception and Error Interview Question AnswersHere is my list of frequently asked questions from Java Error and
Exception topics in various programming interviews to Java and J2EE
developers.  I have also shared my
answers for these questions for quick revision, and provided source for more in depth understanding. I have tried to include questions of various difficulty
level, including simplest of simple for freshers and some tricky questions for
senior Java developers. If you think, there is a good question, which is not
included in this list, please feel free to share it via comment. You can also
share error handling questions asked to you on interviews or any question, for
which you don’t know the answer.








1) What
is Exception in Java?


This is always been first interview question on Exception and mostly
asked on fresher level interviews. I haven't seen anybody asking about what is
Exception in senior and experienced level interviews, but this is quite popular
at entry level. In simple word Exception is Java’s way to convey both system
and programming errors. In Java Exception feature is implemented by using class
like
Throwable, Exception, RuntimeException and
keywords like
throw, throws, try, catch and finally. All
Exception are derived form
Throwable class.
Throwable further divides errors in too category one is
java.lang.Exception and other
is
java.lang.Error.  java.lang.Error deals with
system errors like
java.lang.StackOverFlowError or Java.lang.OutOfMemoryError
while Exception is mostly used to deal with programming mistakes, non
availability of requested resource etc.





2) What
is difference between Checked and Unchecked Exception in Java ?


This is another popular Java Exception interview question appears in
almost all level of Java interviews. Main difference between Checked and
Unchecked Exception lies in there handling. Checked Exception requires to be
handled at compile time using
try, catch and finally keywords
or else compiler will flag error. This is not a requirement for Unchecked
Exceptions. Also all exceptions derived from
java.lang.Exception classes
are checked exception, exception those which extends
RuntimeException,
these are known as unchecked exception in Java. You can also check next
article for more
differences between Checked and Unchecked Exception
.





3) What
is similarity between NullPointerException and ArrayIndexOutOfBoundException in
Java?


This is Java Exception interview question was not very popular, but
appears in various fresher level interviews, to see whether candidate is
familiar with concept of checked and unchecked exception or not. By the way
answer of this interview question is both of them are example of unchecked
exception and derived form
RuntimeException. This
question also opens door for difference of array in Java and C programming
language, as arrays in C are unbounded and never throw
ArrayIndexOutOfBoundException.





4) What
best practices you follow while doing Exception handling in Java ?


This Exception interview question in Java is very popular while hiring
senior java developer of Technical Lead. Since exception handling is crucial
part of project design and good knowledge of this is desirable. There are lot
of best practices, which can help to make your code robust and flexible at same
time, here are few of them:





1) Returning boolean instead of returning null to avoid
NullPointerException at callers end. Since NPE is most infamous of all Java exceptions,
there are lot of techniques and coding
best practices to minimize NullPointerException
. You can check that link
for some specific examples.





2) Non empty catch blocks. Empty catch blocks  are considered as one of the bad practices in
Exception handling because they just ate Exception without any clue, at bare
minimum print stack trace but you should do alternative operation which make
sense or defined by requirements.





3) Prefer Unchecked exception over checked until you have a very good
reason of not to do so. it improves readability of


code by removing boiler plate exception handling code


.


4) Never let your database Exception flowing till client error. since
most of application deal with database and SQLException
is a checked Exception in Java you should consider handling any database
related errors in DAO layer of your application and only returning alternative
value or something meaningful
RuntimeException which
client can understand and take action.





5) calling close() methods for connections,
statements, and streams on finally block in Java.





I have already shared lot of these in my post Top
10 Java exception handling best practices
, you can also refer that for more
knowledge on this topic.





5) Why do
you think Checked Exception exists in Java, since we can also convey error
using RuntimeException ?


This is a controversial question and you need to be careful while
answering this interview question. Though they will definitely like to hear
your opinion, what they are mostly interested in convincing reason. One of the
reason I see is that its a design decision, which is influenced by experience
in programming language prior to Java e.g. C++. Most of checked exceptions are
in
java.io package, which make sense because if you request any system resource and
its not available, than a robust program must be able to handle that situation
gracefully. By declaring
IOException as checked Exception, Java ensures
that your provide that gracefully exception handling. Another possible reason
could be to ensuring that system resources like file descriptors, which are
limited in numbers, should be released as soon as you are done with that using
catch or finally block. Effective Java book from Joshua Bloch has couple of items in this topic, which is again
worth reading.





6) What
is difference between throw and throws keyword in Java?


One more Java Exception interview questions from beginners kitty. throw and throws keyword
may look quite similar, especially if you are new to Java programming and
haven't seen much of it. Though they are similar in terms that both are used in
Exception handling, they are different on how and where they are used in code.
throws keyword is
used in method signature to declare which checked exception method can throw,
you can also declare unchecked exception, but that is not mandatory by compiler.
This signifies lot of things like method is not going to handle Exception
instead its throwing it, if method throws checked Exception then caller should
provide compile time exception handling etc. On the other hand
throw keyword is
actually used to throw any Exception. Syntactically you can throw any
Throwable (i.e. Throwable or any
class derived from
Throwable) , throw  keyword transfers control of execution to
caller so it can be used in place of return keyword. Most common example of
using throw in place of return is throwing
UnSupportedOperationException from an
empty method as shown below :





private static void show() {


    throw new
UnsupportedOperationException("Not yet implemented");


}





See this
article
for more differences between these two keywords in Java.





7) What
is Exception chaining in Java?


Exception chaining is a popular exception handling concept in Java, where
another exception is thrown in response of an exception and creating a chain of
Exceptions. This technique mostly used to wrap a checked exception into an
unchecked or
RuntimeException. By the way if you are
throwing new exception due to another exception then always include original
exception so that handler code can access root cause by using methods like
getCause() and initCause().





8) Have
you written your own custom Exception in Java? How do you do that?


Ofcourse most of us has written custom or business Exceptions like AccountNotFoundExcepiton. Main
purpose of asking this Java Exception interview question is to find out how you
use this feature. This can be used for sophisticated and precise exception
handling with tweak involved in whether you would choose a checked or unchecked
exception. By creating a specific exception for specific case, you also gives
lot of options to caller to deal with them elegantly. I always prefer to have a
precise exception than a general exception. Though creating lots of specific
exceptions quickly increase number of classes in your project, maintaining a
practical balance between specific and general exceptions are key to success.








9) What
changes has been introduced in JDK7 related to Exception handling in Java ?


A relatively new and recent Exception interview question in Java. JDK7
has introduced two major feature which is related to Error and Exception
handling,  one is ability to handle multiple
exception in one catch block
, popularly known as multi cache block and
other is ARM
blocks in Java 7
for automatic resource management, also known as try with
resource. Both of these feature can certainly help to reduce boiler plate code
required for handling checked exceptions in Java and significantly improves
readability of code. Knowledge of this feature, not only helps to write better error and exception code in Java, but also helps to do well during interviews. I
also recommend reading Java 7 Recipes
book to get more insight on useful features introduced in Java 7, including
these two.





10) Have
you faced OutOfMemoryError in Java? How did you solved that?


This Java Error interview questions is mostly asked on senior level Java
interviews and here interviewer is interested on your approach to tackle
dangerous
OutOfMemoryError. Admit it we always face this
error no matter which kind of project you are working so if you say no it
doesn't go very well with interviewer. I suggest even if you are not familiar
or not faced it in reality but have 3 to 4 years of experience in Java, be
prepare for it. At the same time, this is also a chance to impress interviewer
by showing your advanced technical knowledge related to finding memory leaks,
profiling and debugging. I have noticed that these skills almost always creates
a positive impression. You can also see my post on how
to fix java.lang.OutOfMemoryError
for more detail on this topic.





11) Does
code form finally executes if method returns before finally block or JVM exits
?


This Java exception interview question can also be asked in code format,
where given a code with
System.exit() in try block and something in
finally block. It’s worth knowing that, finally block in Java executes even
when return keyword is used in try block. Only time they don’t execute is when you
call JVM to exit by executing
System.exit(0)from try
block in Java.








12) What
is difference in final, finalize and finally keyword in Java?


Another classic interview question in core Java, this was asked to one of
my friend on his telephonic interview for core Java developer with Morgan
Stanley.
final and finally are
keyword, while
finalize is method. final keyword is very
useful for creating ad Immutable
class in Java
By making a class final, we prevent it from being extended,
similarly by making a method final, we prevent it from being overridden,. On
the other hand,
finalize() method is called  by garbage collector, before that object is
collected, but this is not guaranteed by Java specification.
finally keyword is
the only one which is related to error and exception handling and you should
always have finally block in production code for closing connection and
resources. See here
for more detailed answer of this question.











13) What
is wrong with following code :





 public static void start() throws IOException, RuntimeException{


   
throw new RuntimeException("Not able to Start");


 }





 public static void main(String args[]) {


   
try {


          start();


   
}
catch (Exception ex) {


            ex.printStackTrace();


   
}
catch (RuntimeException re) {


            re.printStackTrace();


   
}


 }









This code will throw compiler error on line where RuntimeException  variable “re” is written
on catch block. since Exception is super class of
RuntimeException, all RuntimeException thrown by start() method
will be captured by first catch block and code will never reach second catch
block and that's the reason compiler will flag error as  “exception
java.lang.RuntimeException has already been caught".








14) What
is wrong with following code in Java:






public class SuperClass
{  


   
public void
start() throws IOException{


        throw new IOException("Not able
to open file"
);


   
}


}





public class SubClass
extends SuperClass{  


   
public void
start() throws Exception{


        throw new Exception("Not able
to start"
);


   
}


}






In this code compiler will complain on sub class where start() method
gets overridden. As per rules
of method overriding in Java
, an overridden method can not throw Checked
Exception which is higher in hierarchy than original method. Since here
start() is
throwing
IOException in super class, start() in sub
class can only throw either
IOException or any sub
class of IOException but not super class of
IOException e.g.
Exception.





15) What
is wrong with following Java Exception code:






public static void start(){


  
System.
out.println("Java Exception interivew question Answers for
Programmers"
);


}





public static void main(String args[]) {


  
try{


      start();


  
}
catch(IOException ioe){


      ioe.printStackTrace();


  
}


}



  


In this Java Exception example code, compiler will complain on line where
we are handling
IOException, since IOException is a
checked Exception and
start() method doesn't throw IOException, so
compiler will flag error as "
exception
java.io.IOException is never thrown in body of corresponding try statement
", but
if you change
IOException to Exception compiler error will
disappear because Exception can be used to catch all
RuntimeException which
doesn't require declaration in throws clause. I like this little tricky Java
Exception interview question because its not easy to figure out result by chaining
IOException to Exception. You can
also check Java Puzzlers by Joshua Bloch and Neil Gafter for some tricky questions based
on Java Errors and Exceptions.





These are some of Java Error and Exception interview questions, I have
mostly seen in both fresher and experienced level of Java interviews. There are
a lot more questions on Exception which I haven't included and if you think you
have a good question missed out than let me know and I will make effort to
include it on this list of java exceptions question and answers. One last
question of Java Exception I am leaving for you guys is
"Why
Java Exception considered to be better alternative of returning error codes
" ,
let me know what is your thought on this list of Java Exception interview
questions and answers.









Recommended Books in this article





Effective Java
By Joshua Bloch


Java 7Recipes: A Problem-Solution Approach By Josh Juneau, Carl Dea, Freddy Guime
and John O'Conner


Java Puzzlers
by Joshua a Bloch and Neil Gafter































Source:http://javarevisited.blogspot.com/2013/06/10-java-exception-and-error-interview-questions-answers-programming.html

Documents Reveal Widespread Email Surveillance by US Government for Past Decade

A few years ago, actually, even just a few weeks ago, anyone who suggested that email correspondence and internet traffic were being monitored by the government would have been labeled a nut or conspiracy theorist.  But they would have been right.  From The Guardian:
The Obama administration for more than two years permitted the National Security Agency to continue collecting vast amounts of records detailing the email and internet usage of Americans, according to secret documents obtained by the Guardian.

The documents indicate that under the program, launched in 2001, a federal judge sitting on the secret surveillance panel called the Fisa court would approve a bulk collection order for internet metadata "every 90 days". A senior administration official confirmed the program, stating that it ended in 2011.

The collection of these records began under the Bush administration's wide-ranging warrantless surveillance program, collectively known by the NSA codename Stellar Wind.

Source:http://blog.agupieware.com/2013/06/documents-reveal-widespread-email.html

Automatically set Everyplace start center for mobile users

Maximo Everyplace is the easiest solution to go mobile with Maximo however there is one little thing that always annoys me (and mobile users).

After having created mobile versions of the Maximo apps, the administrator has to define a mobile start center with a Favorite Applications portlet to access them. Unfortunately, there is no way to set this as a 'mobile' Start Center so each user have to click on the Display Settings link and select the Is Mobile check box for the specific start center.

In the real world this means that after having set up Maximo Everyplace I have to send an email to all the mobile users with the instructions about how to setup their mobile start center.

Here is a simple escalation to automatically set the Is Mobile checkbox for the designated start center for all the users.

First of all we need an Action to set the flag:
  • Action: SETMSC
  • Description: Set Mobile Start Center
  • Object: SCCONFIG
  • Type: Set Value
  • Attribute: ISMOBILE
  • Value: 1
  • Accessible From: ESCALATION

Then we can define the Escalation to run the action:
  • Name: SETMSC
  • Description: Set Mobile Start Cente
  • Condition: groupname in ('[EVGROUP]') and ismobile=0
  • Schedule: hourly
  • Create Successful Execution Entry?: No
  • Escalation point: Empty
  • Action: SETMSC

The [EVGROUP] should match the name of your Security Group(s) with the mobile start center assigned.


Source:http://maximodev.blogspot.com/2013/06/set-maximo-everyplace-start-center-mobile.html

5 must read books to learn Object Oriented and Java Design patterns - Best of lot



Knowledge of Object oriented design principle and various design pattern
is must for any Java developer. As I said earlier on 10 OOPS and SOLID design principles,
co
ding without knowing these principles are like trying to learn language
without knowing alphabets. By the way there are several books written on Object
oriented design principles, design patterns and best practices, but only few of
them provides what they claim. There are two things here, design principles and
design patterns, one is basic and other is best practice built on that basic.
One should first learn Object oriented principles and then learn design pattern
to see how those principles are used to solve day to day problems. Keeping this
in mind, I have collected following list of 5 books to learn Object oriented basics
and design patterns in Java. These books are ordered from a beginners to
advanced perspective. J2EE design patterns are little different than core Java
design patterns but equally important for a Java developer, core J2EE patterns
books is a good choice to learn that.








Top 5 books on Java design patterns



Here is
my list of books to learn object oriented and Java design patterns. Design
patterns are tried and tested way to solve a problem in a context. These patterns are discovered while solving similar problems multiple times over the year and they address some of the most common task in object oriented application development e.g. creating object, structuring code,  dynamic behavior based on context and object etc. Following five books are great resource to learn Java design patterns, which is equally applicable to any other object-oriented programming language. If you know any other book on design patterns, which is worth reading, then please share with us.







Head
First Design Patterns by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy
Sierra, Elisabeth Robson




This was the first book, I read on head first series and design pattern
as well, prior to that I have no idea, when to use abstract class or interface
or Why composition is better than
Inheritance
. I usually code each feature and requirement as they
come and end of doing more changes, more testing and introducing more bugs in
first few years of software development. Thanks to my appetite of learning and
reading, I discovered Head First design pattern and
after reading it's first chapter, I was thrilled. Now I can say that was basics
but it's easier to get to know about advance stuff than basics, and there, this
books scores. It's a must read book on Object oriented design patterns for any
Java developer, including experienced and senior developers. I would even suggest to
start learning design pattern from this book. It not only explains concepts in
clear way, but also gives lots of diagram, exercise, quizzes and real life
examples to make you think and learn. I am a big fan of head first books, be it
Head First Java or this book. Head first
design patterns is great example of active learning and anyone who
wants' to know about Object oriented basics like Inheritance, Encapsulation,
Polymorphism and Abstraction, must read this book. There chapter on Decorator
design pattern and Observer design pattern is also great piece of work.








Design
Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard
Helm, Ralph Johnson, John Vlissides


This is the classic Gang of Four (GOF) design pattern book,
which
became source and motivation for many object oriented design pattern
books written and published so far. Any list of must read books on design
patterns in Java is incomplete, without including this book. After almost 20
years, this book is still relevant on Object oriented and Java design
patterns.  This book has a case study
chapter on designing Document Editor
and then explains various design patterns e.g. Creational patterns, Structural
and Behavioral patterns. IMHO, this is one of the best book in design pattern
and must read for any Java developer, along with Java concurrency in Practice
and Effective Java.
You can buy
this book from amazon, it’s available as both hardcover, paperback edition and
as multimedia CD.








Design
Patterns Explained: A New Perspective on Object-Oriented Design (2nd Edition)
by Alan Shalloway, James R. Trott


Like multithreading and concurrency, design patterns are also not easy to
understand. What is most difficult part is understanding enough to identify
real world scenarios, where you can apply these design patterns. That's why
sometime it's better to use multiple books to learn design patterns in Java,
it's worth doing it. Main reason for that is, different style of writing and
explaining stuffs. Some programmer find a particular author more readable than
others, I guess only exception is Joshua Bloch which really connects to most of
Java developer. Design Patterns Explained: A New Perspective on Object-Oriented Design, is that alternate way of
learning Object oriented design pattern. Though it also explains same set of
OOPS principles, UML and design patterns like decorator, factory or observer,
the way it explains may be easier to understand for many beginners. Examples
given this design pattern books is also good and non trivial.










Software
Architecture Design Patterns in Java by Partha Kuchana


This is a another good book on Object oriented and Java design patterns, it
not only covers basic Object-oriented principles like
Class, Object, Inheritance, Polymorphism, Abstraction and Encapsulation, but also
covers details which is quite practical but not obvious e.g. private methods, getter and
setters, Immutable objects, i
nterface
and monitor. This book also provide extensive and comprehensive coverage of
whole lot of design patterns e.g. Creational patterns, Collection patterns,
Structural patterns, Behavioral patterns, and Concurrency patterns. It's
coverage on Factory design pattern and Singleton pattern is really
int
eresting to read. Another thing, which I like in this book is practice
questions and UML diagrams, which not only helps to understand topic well but
also ensures that you practice application part, which is most important to
learn any design pattern. Finally they have a case study of designing software
solution for a web hosting company, which gives you a real chance of
identifying and applying design patterns in a real world scenario. In short, Software Architecture Design Patterns in Java has almost everything you need to know about Java design
patterns.    










Core J2EE
Patterns: Best Practices and Design Strategies (2nd Edition) by Deepak Alur,
Dan Malks, and John Crupi


J2EE platform is most popular way of using Java programming language, and
since it's mainly focus on web and enterprise solution, it has it's own set of
problems and requirements. Core J2EE patterns explains
some of the most useful design patterns from J2EE world e.g. Intercepting
Filters, Front Controller, Model View Controller or MVC pattern, Data Access
Object or DAO pattern, View Helper or View Resolver pattern, Service Locator
patterns etc. This book divides design pattern based upon there functional area
e.g. Presentation tier design patterns, business tier design pattern etc. This
is a must read book for any Java J2EE developer, who is responsible for coding
web application and enterprise application. Though modern day framework like
Spring, ensures you follow these J2EE design pattern at framework level e.g.
MVC is enforced by Spring MVC, similarly it also uses Front Controller in form
of
DispatcherServlet and ViewResolver. Spring framework, also let you
use dependency Injection and IOC at container level. Having said that, whether
you use Spring MVC, Struts or any other web framework, knowledge of these J2EE
patterns will help you to understand legacy code as well as to create solution
which is easier to maintain.







Apart from these 5 books you can also look on Effective Java 2nd Edition by Joshua Bloch and Head first object oriented analysis and design for getting some good idea about object oriented design
principles and how it has used in Java. Effective Java is must read for any
Java programmer, as it explained lot of practical design advices used in Java
library itself.



























Source:http://javarevisited.blogspot.com/2013/06/5-must-read-books-to-learn-object.html

Minggu, 27 Juli 2014

Embed Maximo user interface in a web page


This was a tough week but I have learned many things. I have been two days in Florence and other two days in Montebelluna near Venice. Now I am in the train going back home for a well deserved vacation at the beach.

Today I have discovered a nice way to embed Maximo UI in a custom web portal. The customer wants to provide a very simple self service center in its own intranet web site.
The trick to achieve this is to use an undocumented parameter called portalmode. Let's see how to do it.


Download the sample mymx.html file. This HTML file is a simple web page that has a very classical structure. A title bar at the top, a left navigation portfolio and a content page on the right. Open mymx1.html with a text editor and update the two URLs with your Maximo server hostname to match your environment. Note how the portalmode parameter is passed in the URLs and how the IFRAME element is used to embed the frame in the web page.
Save the file, open it with a web browser. If you click on one of the two links on the left you will be prompted with the Maximo login page and then taken to your SR application. Here is how it will look like.



You can see some good and bad things.
  1. The Go To menu, graphics and other stuff on the top bar are hidden (good)
  2. Playing with URLs you can easily define shortcusts to Maximo apps (good)
  3. The buttons are somewhat scrambled on the right side (bad)
  4. The application is truncated on the righ side (bad)
  5. The login page is displayed (bad)

Now we have to keep the good things and avoid the bad ones. Issues 3 and 4 can be solved customizing the SR app. Issue 5 can be solved implementing SSO.

Simplify the SR application

Open the Application designer and create a new Power App based on SR object.
  • Application: MYSR
  • Description: Simple SR app for the Intranet
  • Main Object: SR
  • Key Attribute: TICKETID
  • Module Name: SD

Remove unneeded fields from the MYSR app. Remove the pageHeader, pageFooter and menubar rows in the XML file to remove the headers and footers. Import back the MYSR app and test it. The simplified app will not allow any navigation but that's exactly what we are looking for.
For your convenience, here is my streamlined MYSR app definition.


Avoid the login page


In your intranet portal you probably already have your login page and it is not fair nor elegant to ask the users to login again into Maximo.
Here you need to implement SSO (Single Sign On). It's not the goal of this article to explain how to implement SSO between a web site and Maximo so we will simulate it. If you need more details about implementing SSO for Maximo you look at this forum thread.
As decribed in this article, login credentials can be passed in the URL so all you have to do to do the trick is to pass those credentials in the links.



Putting all together

Change the link in the HTML file to load the new MYSR app and pass the user credentials as described above. You will have links like this:
http://[MXHOST]/maximo/ui/maximo.jsp?event=loadapp&value=mysr&additionalevent=insert&portalmode=true&login=true&username=adams&password=adams


And here is the final result!




Source:http://maximodev.blogspot.com/2013/06/embed-maximo-user-interface-in-web-page.html

How to Add Two Integer Numbers without using Plus + or ++ Arithmetic Operator in Java - Recursion example




In this article, we will take a look on another interview question about
adding two numbers, but without using + or ++ operator. Interview starts with a
simple statement, Can you write a function to add two numbers (integers)
without using + or plus arithmetic operator in Java? If you are good in maths,
it wouldn’t take more than a second to say that, we can use subtraction or -
operator to add two numbers because
a-(-b)== a+b. Well
that’s correct, but real question starts when interviewer quickly points out
that, you can not use any arithmetic operator including
+,-,*,/++
or --
. Programming and Coding questions are integral part of any Java
interview. You should always expect couple of questions like this, e.g. swapping
two numbers without using temp variable
. If you have been giving interviews, then
you know that, it will eventually comes downs to bitwise operator in Java. Yes,
we can add two numbers by using bitwise and bitshift operators, which is not
arithmetic. Interviewer, will be happy by hearing bitwise operator, but he
would like to see the code. Well, if you know binary arithmetic or how to add
numbers in binary format, you may be familiar with fact than sum of two numbers
can be obtained by using XOR operation and carry, by using AND operation. This
is the fact, you must remember to solve this question or add two integers
without using any arithmetic operator e.g. plus, minus etc. Sometime
interviewer, may ask you to write both iterative and recursive solution of same
question, Since recursion is another confusing programming technique, it's favored more during interviews. In this Java tutorial, we will see both
recursive and iterative version of our add method, which calculate sum of two
numbers without using arithmetic operator, but using bitshift
and bitwise operators in Java
.







Iterative Solution



How to add two integers without using plus arithmetic operator in JavaIterative solution uses any kind of loop, e.g. for, while or do-while. As
I said, sum of two integer can be obtained by XOR bitwise operator and carry
can be obtained but AND bitwise operator. We also need to use signed left shift
Java operator to add carry into sum. Here is code for iterative method to add
two integers without using plus or minus operator :





 public static int addIterative(int a, int b){  


        while (b != 0){


            int carry = (a & b) ; //CARRY is AND
of two bits


          


            a = a ^b; //SUM of two
bits is A XOR B


          


            b = carry << 1; //shifts carry
to 1 bit to calculate sum


        }


        return a;


 }






Code is self explanatory, we are calculating carry and keeping it in a
separate variable, than we are storing sum of two numbers into variable a, and
shifts carry to 1 bit by using signed left shift operator, In order to add into
sum.





Recursive Solution



Following method uses recursion
programming technique
to calculate sum of two numbers without arithmetic
operator e.g. +, - etc. It's recursive version of our earlier iterative
solution. Just like in loop, we are testing for
b=0, here also
we are doing same thing. We have just combined
& bitwise
and
<< signed left shift operator calculating and shifting
carry.






public static int add(int a, int
b){


        if(b == 0) return a;


        int sum = a ^ b; //SUM of two
integer is A XOR B


        int carry = (a & b) << 1;  //CARRY of two integer is A AND B


        return add(sum, carry);


 }






How to add two integers without arithmetic
operator Java Example



Here is complete code example, which includes both iterative and
recursive method along with a simple JUnit
test
. I have tested both add methods for couple of edge cases e.g. adding
negative numbers,
Integer.MAX_VALUE, adding zero etc.






/**


 * Java program to calculate sum of two number
without using addition or subtraction


 * operator in Java. This solution, use bitwise
and bitshift operator instead of maths operator.


 * @author Javin Paul


 */


public class AddTwoNumbersJava
{


  


   
public static void
main(String args[]) {


      


       System.out.println(" Sum of
110 add 200 is : "
+ add(110, 200));


       System.out.println(" Sum of 0
and 0 is : "
+ add(0, 0));


       System.out.println(" Sum of
-10 and +10 is : "
+ add(-10, 10));


       System.out.println(" Sum of
-10 + 200 is : "
+ add(-10, 200));


       System.out.println(" Sum of 0
+ 200 is : "
+ add(0, 200));


     


   
}  


  


   
/*


     * Adding two number without using + or
plus arithmetic operator using


     * recursion in Java. This method uses XOR
and AND bitwise operator to


     * calculate sum of two numbers;


     */


   
public static int
add(int a, int b){


        if(b == 0) return a;


        int sum = a ^ b; //SUM of two
integer is A XOR B


        int carry = (a & b) << 1;  //CARRY of two integer is A AND B


        return add(sum, carry);


   
}


 


   
/*


     * Adding two integers without any
arithmetic operator and using recursion.


     * This solution also uses XOR and AND
bitwise and << left shift bitshift


     * operator


     */


   
public static int
addIterative(int a, int b){ 


        while (b != 0){


            int carry = (a & b) ; //CARRY is AND
of two bits


          


            a = a ^b; //SUM of two
bits is A XOR B


          


            b = carry << 1; //shifts carry
to 1 bit to calculate sum


        }


        return a;


   
}


 


}





Output:


Sum of 110 add 200 is : 310


Sum of 0 and 0 is : 0


Sum of -10 and +10 is : 0


Sum of -10 + 200 is : 190


Sum of 0 + 200 is : 200






And here is JUnit test case to test add() and addIterative() method, If
you notice carefully, I have used static
import feature of Java 1.5
, to import various assert methods like
assertEquals(expected,
actual)
. By the way, I just realized that I made an error here, which won't
affect the result but it's a mistake. If you can point it out then let me know
:






import org.junit.Test;


import static
org.junit.Assert.*;


import static
test.AddTwoNumbersJava.*;





/**


 * JUnit tests for addition without using maths
operator in Java.


 * @author


 */


public class AddTwoNumbersJavaTest
{  





   
/**


     * Test of add method, of class
AddTwoNumbersJava.


     */


   
@Test


   
public void
testAdd() {


        assertEquals(add(0, 0), (0 + 0));


        assertEquals(add(100, 210), (100 + 210));


        assertEquals(add(-10, 10), (-10 + 10));


        assertEquals(add(0, 200), (0 + 200));


        assertEquals(add(10, 0), (10 + 0));


        assertEquals(add(Integer.MAX_VALUE, 10), (Integer.MAX_VALUE + 10));


   
}





   
/**


     * Test of addIterative method, of class
AddTwoNumbersJava.


     */


   
@Test


   
public void
testAddIterative() {


        assertEquals(addIterative(0, 0), (0 + 0));


        assertEquals(addIterative(100, 210), (100 + 210));


        assertEquals(addIterative(-10, 10), (-10 + 10));


        assertEquals(addIterative(0, 200), (0 + 200));


       
assertEquals(addIterative(
10, 0), (10 + 0));


        assertEquals(addIterative(Integer.MAX_VALUE, 10), (Integer.MAX_VALUE + 10));


   
}


}









That's all on How to add two numbers without using plus + arithmetic
operator in Java
. As I said, you need to remember that sum of two integers
in binary is equal to XOR of two numbers and carry is equal to AND operation of
two numbers. By using bitwise and bitshift operator in Java, you can easily calculate
sum of two numbers without any arithmetic operator.






Further Reading on Bit Twiddling


Bitwise and bitshift
operator are quite extensively used in programming interviews, and many
problems like above can be solved by there usages. Hackers delight is one of the greatest book on writing code using bit twiddling and
bit manipulation and in fact Java library uses many bit twiddling techniques
from this book.





The Art of Computer Programming by Donald E. Knuth


Cracking the Coding Interview: 150 Programming Questions and Solutions


Hacker's Delight (2nd Edition) By Henry S. Warren































Source:http://javarevisited.blogspot.com/2013/06/how-to-add-two-integer-numbers-without-plus-arithmetic-operator-java-example.html