Tuesday, December 10, 2019

How To Swap 2 Integers Without Using Temporary Variable Inwards Java?

One of the oldest flim-flam interrogation from programming interview is, How create y'all swap 2 integers without using temp variable? This was start asked to me on a C, C++ interview together with and thus several times on diverse Java interviews. Beauty of this interrogation lies both on flim-flam to think near how y'all tin swap 2 numbers alongside out tertiary variable, precisely also problems associated alongside each approach. If a programmer tin think near integer overflow together with consider that inwards its solution together with thus it creates a real skillful impression inwards the oculus of interviewers. Ok, thus let's come upward to the point, suppose y'all receive got tow integers i = 10 together with j = 20, how volition y'all swap them without using whatsoever variable thus that j = 10 together with i = 20? Though this is mag occupation together with solution operate to a greater extent than or less inwards every other programming language, y'all demand to create this using Java programming constructs. You tin swap numbers past times performing some mathematical operations e.g. add-on together with subtraction together with multiplication together with division, precisely they confront occupation of integer overflow.


There is a bang-up flim-flam of swapping number using XOR bitwise operator which proves to live on ultimate solution. We volition explore together with sympathize each of these iii solutions inwards particular here, together with if y'all are hungry for to a greater extent than programming questions together with solutions, y'all tin e'er accept a await at Cracking the Coding Interview: 150 Programming Questions together with Solutions, i of the best majority to create for programming undertaking interviews.




Solution 1 - Using Addition together with Subtraction

You tin use + together with - operator inwards Java to swap 2 integers equally shown below :
a = a + b; b = a - b;   // genuinely (a + b) - (b), thus at i time b is equal to a a = a - b;   // (a + b) -(a), at i time a is equal to b

You tin come across that its genuinely prissy flim-flam together with start fourth dimension it took sometime to think near this approach. I was genuinely happy to fifty-fifty think near this solution because its neat, precisely happiness was brusque lived because interviewer said that it volition non operate inwards all conditions. He said that integer volition overflow if add-on is to a greater extent than than maximum value of int primitive equally defined past times Integer.MAX_VALUE together with if subtraction is less than minimum value i.e. Integer.MIN_VALUE.

It confused me together with I conceded alone to abide by that the code is absolutely fine together with operate perfectly inwards Java, because overflows are clearly defined. Ofcourse same solution volition non operate inwards C or C++ precisely it volition operate absolutely fine inwards Java. Don't believe me? hither is the proof :

a = Integer.MAX_VALUE; b = 10;  System.out.printf("Before swap 'a': %d, 'b': %d %n", a, b);  a = (a + b) - (b = a);  System.out.printf("After swapping, 'a': %d, 'b': %d %n", a, b);  Output : Before swap 'a': 2147483647, 'b': 10  After swapping, 'a': 10, 'b': 2147483647 

Here add-on of 2 numbers volition overflow, Integer.MAX_VALUE + 10 = -2147483639, but nosotros are also doing subtraction, which volition compensate this value, because b is at i time Integer.MAX_VALUE together with -2147483639 - 2147483647 volition i time again overflow to laissez passer on y'all 10 equally output.


Solution 2 - Using XOR trick

Second solution to swap 2 integer numbers inwards Java without using temp variable is widely recognized equally the best solution, equally it volition also operate inwards linguistic communication which doesn't grip integer overflow similar Java e.g. C together with C++. Java provides several bitwise together with bitshift operator, i of them is XOR which is denoted past times ^.

If y'all recollect XOR truth tabular array together with thus y'all know that Influenza A virus subtype H5N1 XOR B volition render 1 if Influenza A virus subtype H5N1 together with B are dissimilar together with 0 if Influenza A virus subtype H5N1 together with B are same. This holding gives nascency to next code, popularly know equally XOR trick:

x = x ^ y; y = x ^ y;   // at i time y = x x = x ^ y;  // at i time x = y

Let's come across these examples inwards activeness past times writing a elementary Java program, equally shown below.





Progarm to Swap Two Integers without tempoarry variable inwards Java 

In this Java program, I volition present y'all twain of ways to swap 2 integers without using whatsoever temporary or tertiary variable, together with what are problems comes alongside each approach together with which i volition operate inwards all conditions. Actually the 2 pop solution plant perfectly fine inwards Java precisely candidates, peculiarly those coming from C together with C++ background oftentimes think that start solution is broken together with volition neglect on integer boundaries, precisely that's non true. Integer overflows are clearly define inwards Java e.g. Integer.MAX_VALUE + 1 volition resultant inwards Integer.MIN_VALUE, which agency if y'all create both add-on together with subtraction inwards alongside same railroad train of numbers, your resultant volition live on fine, equally seen inwards higher upward example.

/** * Java programme to swap 2 integers without using temp variable * * @author java67 */ public class Problem {      public static void main(String args[]) {         int a = 10;         int b = 20;          // i way using arithmetics operator e.g. + or -         // won't operate if amount overflows         System.out.println("One way to swap 2 numbers without temp variable");         System.out.printf("Before swap 'a': %d, 'b': %d %n", a, b);         a = a + b;         b = a - b; // genuinely (a + b) - (b), thus at i time b is equal to a         a = a - b; // (a + b) -(a), at i time a is equal to b          System.out.printf("After swapping, 'a': %d, 'b': %d %n", a, b);          // some other example         a = Integer.MIN_VALUE;         b = Integer.MAX_VALUE;          System.out.printf("Before swap 'a': %d, 'b': %d %n", a, b);          a = (a + b) - (b = a);          System.out.printf("After swapping, 'a': %d, 'b': %d %n", a, b);          // Another way to swap integers without using temp variable is         // past times using XOR bitwise operator         // Known equally XOR trick         System.out.println("Swap 2 integers without tertiary variable                              using XOR bitwise Operator");          int x = 30;         int y = 60;          System.out.printf("Before swap 'x': %d, 'y': %d %n", x, y);         x = x ^ y;         y = x ^ y;         x = x ^ y;          System.out.printf("After swapping, 'x': %d, 'y': %d %n", x, y);     }  }  Output One way to swap 2 numbers without temp variable Before swap 'a': 10, 'b': 20 After swapping, 'a': 20, 'b': 10 Before swap 'a': -2147483648, 'b': 2147483647 After swapping, 'a': 2147483647, 'b': -2147483648 Swap 2 integers without tertiary variable using XOR bitwise Operator Before swap 'x': 30, 'y': 60 After swapping, 'x': 60, 'y': 30

That's all near how to swap 2 integers without using temporary variable inwards Java. Unlike pop belief that start solution volition non operate on integer boundaries i.e. approximately maximum together with minimum values, which is also truthful for languages similar C together with C++, it operate perfectly fine inwards Java. Why? because overflow is clearly define together with add-on together with subtraction together negate the number of overflow. There is no incertitude near minute solution equally it is the best solution together with non dependent area to whatsoever sign or overflow problem. It is also believed to live on fasted way to swap 2 numbers without using temp variable inwards Java.

together with how near this meme :)


If y'all are interested inwards solving some elementary together with some tricky programming questions, I advise y'all to accept a await at next railroad train of programming problems :
  • Top thirty Array based programming problems for Java programmers? [problems]
  • Top xx String based coding problems for Java programmers? [problems]
  • Top 10 Programming together with Coding exercises for Java programmers? [problems]
  • How to abide by overstep 2 numbers from integer array? [solution]
  • How to abide by duplicate characters inwards Java String? [solution]
  • How to abide by foursquare beginning of a number inwards Java? [solution]
  • How to impress Fibonacci serial inwards Java without using recursion? [solution]

If y'all are preparing for programming undertaking interviews together with looking for some skillful resources, together with thus y'all tin also accept aid from next books, 2 of the best resources of programming questions :
  • Programming Interviews Exposed: Secrets to Landing Your Next Job [see here]
  • Cracking the Coding Interview: 150 Programming Questions together with Solutions [see here]

Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures together with Algorithms: Deep Dive Using Java
Algorithms together with Data Structures - Part 1 together with 2

Caused By: Java.Lang.Noclassdeffounderror: Org/Apache/Log4j/Logger Inwards Java

Problem : You are getting Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger fault inward your Java application, which is using Log4j Logger either straight or indirectly via about pop Java framework similar Spring, Struts or Hibernate.


Cause : Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger fault indicates that JVM is non able to establish org.apache.log4j.Logger degree inward your application's CLASSPATH. Simplest argue of this fault is missing log4j.jar file. Since org.apache.log4j.Logger class belongs to this JAR file, if its non available at run-time in addition to thus your plan volition fail. Similar effect is java.lang.NoClassDefFoundError org.apache.log4j.Appender, which too comes due to missing log4j.jar inward CLASSPATH. You tin flaming banking concern tally that org.apache.log4j.Appender too belongs to log4j.jar file. If y'all don't know how in addition to thus allow me say y'all a quick tip. If y'all convey your projection setup in addition to thus y'all tin flaming exactly type Ctrl + T in addition to refer of degree e.g. org.apache.log4j.Logger and Eclipse volition demo all the degree file alongside same name along alongside the JAR file on which they are packaged. I oftentimes purpose this play tricks to discovery out whether a detail degree is introduce inward CLASSPATH or not.





Solution: If employment is caused due to missing log4j.jar file in addition to thus y'all tin flaming produce it past times adding relevant  version of log4j.jar into your CLASSPATH. Now, which version of JAR file y'all should add together volition depend upon your application in addition to library y'all are using but at safer side y'all tin flaming e'er add together latest one. BTW, its worth remembering that at that spot is huge divergence betwixt Log4j in addition to Log4j2, which too provides asynchronous logging, thus brand certain y'all add together correct version of log4j library into your application's classpath.

You tin flaming download log4j.jar file either from Maven cardinal repository or straight from Apache Log4j website http://logging.apache.org/log4j/1.2/download.html. If y'all are using log4j ii e.g. for asynchronous logging in addition to thus y'all tin flaming download log4j2.jar from here. It exists inward same website but at dissimilar location.

j Logger either straight or indirectly via about pop Java framework similar Spring Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger inward Java
If y'all are using Maven in addition to thus y'all tin flaming too add together next dependency inward your pom.xml file to download Log4j.jar
<dependency>    <groupId>log4j</groupId>    <artifactId>log4j</artifactId>    <version>1.2.15</version> </dependency>
If y'all are using log4j version ii in addition to thus y'all tin flaming add together next Maven dependency :
<dependency>     <groupId>org.apache.logging.log4j</groupId>     <artifactId>log4j-api</artifactId>     <version>2.3</version> </dependency>


That's all well-nigh how to produce Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger fault inward Java application. In most of the cases, this effect volition acquire away every bit presently every bit y'all add together log4j.jar file but if it withal persist in addition to thus y'all postulate to carefully banking concern tally your CLASSPATH setting. You tin flaming run into hither to larn to a greater extent than well-nigh how to bargain alongside CLASSPATH intricacies inward Java.

Further Learning
Complete Java Masterclass
solution]
  • How to solve java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject [solution]
  • Could non produce the Java virtual machine Invalid maximum heap size: -Xmx [solution]
  • How to produce java.lang.unsupportedclassversionerror unsupported major.minor version 49.0 50.0 [fix]
  • How to bargain alongside java.lang.ClassNotFoundException: com.mysql.jdbc.Driver inward Java [solution]
  • How to solve java.lang.classnotfoundexception oracle.jdbc.driver.oracledrive inward JDBC [solution]
  • How to produce java.lang.NoClassDefFoundError: org/dom4j/DocumentException inward Apache POI [fix]
  • How to solve java.lang.ClassNotFoundException: org.Springframework.Web.Context.ContextLoaderListener inward Spring [solution]
  • Solution of java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver Error inward JDBC [solution]
  • Solution of java.lang.ClassNotFoundException: org.postgresql.Driver fault inward Java? [solution]

  • 19 Coffee Method Overloading As Well As Overriding Interview Questions As Well As Answers

    Method overloading as well as overriding is i of the tricky concept to original as well as that's why its i of the most pop theme inwards Java Interviews. You volition often come across questions similar what is deviation betwixt overloading as well as overriding? or can yous overload method inwards same class? during start few rounds of interview, mostly at telephonic round. Since its purpose of object oriented fundamentals its also practiced to know equally much close these concepts equally possible. In this article, I am sharing simply about of the basic but oft asked questions which are alone based upon overloading as well as overriding concept as well as their implementation inwards Java programming language. By going through these questions, You volition non only create good on interviews but also it volition improve your agreement of Java as well as OOP fundamentals. BTW, if yous are seriously preparing for Java interviews, simply preparing this theme volition non travel plenty as well as yous demand to fix other of import topics equally good e.g. Java Collection framework, multi-threading, JVM internals as well as garbage collections etc. If yous are inwards hurry, I would advise yous to convey a hold off at Java Programming Interview Exposed yesteryear Wrox publication, i of the meliorate mass on Java interviews.



    Overloading as well as Overriding Interview Questions

    Ok, let's start on questions. Here is my listing of 17 method overloading as well as overriding interview inquiry which covers basics equally good equally simply about tricky purpose of overloading as well as overriding. You tin also write simply about code to bear witness the concept as well as come across when compiler gives mistake as well as which method is acquire called at run-time.



    1) What is method overloading inwards Java?
    If yous receive got 2 method which does same matter its meliorate they receive got same name, but 2 method cannot receive got same cite until yous overload them. So overloading is a procedure of declaring 2 methods alongside same cite but dissimilar method signature e.g. System.out which is object of PrintStream aeroplane has several println() method to impress dissimilar information types e.g. byte, short, int, char, float as well as double. All of them are called overloaded method. Overloaded method calls are resolved during compile fourth dimension inwards Java as well as they must receive got dissimilar method signatures. See here to acquire to a greater extent than close method overloading inwards Java.


    2) What is method overriding inwards Java?
    Method overriding is simply about other way to define method alongside same cite but dissimilar code but it must travel inwards sub class. Overriding is based upon run-time Polymorphism equally method calls are resolved at run-time depending upon actual object.  For instance if a variable of type Parent holds an object of Child aeroplane as well as then method invoked volition travel from tiddler aeroplane as well as non bring upwards class, provides its overridden. In guild to override a method, yous must follow rules of method overriding which agency declaring method alongside same signature inwards sub class. See here to acquire to a greater extent than close method overriding inwards Java.


    3) What is method hiding inwards Java?
    static method cannot travel overriding inwards Java because their method calls are resolved at compile fourth dimension but it didn't foreclose yous from declaring method alongside same cite inwards sub class. In this instance nosotros say that method inwards sub aeroplane has hided static method from bring upwards class. If yous receive got a instance where variable of Parent aeroplane is pointing to object of Child aeroplane as well as then also static method from Parent aeroplane is called because overloading is resolved at compile time. See here to acquire to a greater extent than close method hiding inwards Java.


    4) What are rules of overloading a method inwards Java?
    One as well as only dominion of method overloading inwards Java is that method signature of all overloaded method must travel different. Method signature is changed yesteryear changing either seat out of method arguments, or type of method arguments e.g. System.out.println() method is overloaded to convey dissimilar primitive types similar int, short, byte, float etc. They all convey simply i declaration but their type is different. You tin also alter method signature yesteryear changing guild of method declaration but that often leads to ambiguous code so meliorate to travel avoided. See here for amount listing of rules.


    5) Difference betwixt method overloading as well as overriding?
    Fundamental deviation betwixt overloading as well as overriding is that old took house during compile fourth dimension piece after took house during run-time. Due to this reason, its only possible to overload virtual methods inwards Java. You cannot overload methods which are resolved during compile fourth dimension e.g. private, static as well as in conclusion method cannot travel overridden inwards Java. Also, rules of method overloading as well as overriding are different, for instance inwards guild to overload a method its method signature must travel dissimilar but for overriding method it must travel same. See this image to acquire to a greater extent than deviation betwixt overriding as well as overloading inwards Java.

     Method overloading as well as overriding is i of the tricky concept to original as well as that nineteen Java Method Overloading as well as Overriding Interview Questions as well as Answers


    6) Can nosotros overload static method inwards Java?
    Yes, its possible to overload static method inwards Java. You tin declare equally many static method alongside same cite equally yous desire until all of them receive got dissimilar method signature. Remember, render type is non purpose of method signature, so they must receive got either dissimilar seat out of arguments, or dissimilar type of argument. There is a 3rd alternative also which changes guild of declaration but I advise non to create that because it often resultant inwards ambiguous method call. It's real of import to follow these best practices piece overloading a static method inwards Java.


    7) Can nosotros override static method inwards Java?
    No, yous cannot override static method inwards Java because they are resolved as well as bonded during compile time. Since overriding is a run-time activeness as well as if a method telephone telephone is already resolved at compile fourth dimension as well as then it volition non convey house as well as that's why its non possible to override static method inwards Java. But, yous tin define simply about other static method of same signature inwards sub class, this is known equally method hiding. Actual method called volition depends upon the type of aeroplane as well as non on type of object equally its the instance alongside overriding. See here to acquire to a greater extent than close why yous cannot override static method inwards Java.


    8) Can yous foreclose overriding a method without using in conclusion modifier?
    Yes, in that place are simply about funky ways to foreclose method overriding inwards Java. Though in conclusion modifier is only for that purpose yous tin job someone keyword to foreclose method overriding. How? If yous recollect correctly, inwards guild to override a method, the aeroplane must travel extensible. If yous brand the constructor of bring upwards aeroplane someone as well as then its non possible to extend that aeroplane because its constructor volition non travel accessible inwards sub class, which is automatically invoked yesteryear sub aeroplane constructor, thus its non possible to override whatever method from that class. This technique is used inwards Singleton pattern pattern, where constructor is purposefully made someone as well as a static getInstance() method is provided to access singleton instance. See here to acquire to a greater extent than techniques to foreclose method overriding inwards Java.


    9) Can nosotros override a someone method inwards Java?
    No, yous cannot override someone method inwards Java. Since someone methods are non visible exterior the class, they are non available inwards sub-class thus they cannot travel overridden. By the way, how close overriding a someone method within an Inner class? Is it possible? See here to acquire to a greater extent than why yous cannot override someone method inwards Java.


    10) What is co-variant method overriding?
    One of the dominion of method overriding is that render type of overriding method must travel same equally overridden method but this restriction is relaxed footling fleck from Java 1.5 as well as straight off overridden method tin render sub aeroplane of render type of original method. This relaxation is known equally co-variant method overriding as well as it allows yous to withdraw casting at customer end. One of the best instance of this comes when yous override clone() method. Original Object.clone() method returns Object which needs to cast, but alongside co-variant method overriding yous tin direct render relevant type e.g. Date aeroplane returns object of java.util.Date instead of java.lang.Object. See hither to acquire to a greater extent than close co-variant method overriding inwards Java.


    11) Can nosotros alter declaration listing of overridden method?
    No, yous cannot alter the declaration listing of overridden method inwards Java. An overriding method must receive got same signature equally original method. Only render type tin travel changed that to only to sub type of render type of original method.


    12) Can nosotros alter render type of method inwards subclass piece overriding?
    No, yous cannot alter the render type of method during overriding. It would travel violation of rules of overriding. Though from Java five onward yous tin supersede the render type alongside sub type e.g. if original method has render type equally java.lang.Object as well as then yous tin alter render type of overridden method equally whatever type e.g. clone() method. This is also known equally co-variant method overriding inwards Java.


    13) Can nosotros override a method which throws run-time exception without throws clause?
    Yes, yous can. There is no restriction on throwing RuntimeException from overriding method. So if your original method throws NullPointerException than its non necessary to throw NPE from overriding method equally well.


    14) How create yous telephone telephone super aeroplane version of an overriding method inwards sub class?
    You tin telephone telephone it using super keyword. For instance if yous receive got a method calculate() inwards both bring upwards as well as tiddler aeroplane as well as then from tiddler aeroplane yous tin invoke bring upwards aeroplane method calculate() equally super.calculate(). It's real similar to calling super aeroplane constructor from sub aeroplane equally shown here.


    15) What are rules of method overriding inwards Java?
    Some rules of method overriding are next :
    • Overriding method cannot throw higher exception than overridden one, but that's only truthful for checked exception.
    • Overriding method cannot limit access of overridden method e.g. if original method is world as well as then overriding method must travel public, but it tin expand access e.g. if original method is protected than overriding method tin travel protected or public.
    See here for amount listing of rules of method overriding inwards Java.


    16) Can nosotros override a non-static method equally static inwards Java?
    No, its non possible to define a non-static method of same cite equally static method inwards bring upwards class, its compile fourth dimension mistake inwards Java. See hither to acquire to a greater extent than close overriding static method inwards Java.


    17) Can nosotros override constructor inwards Java?
    No, yous cannot override constructor inwards Java because they are non inherited. Remember, nosotros are talking close overriding hither non overloading, yous tin overload create but yous cannot override them. Overriding ever happens at tiddler aeroplane as well as since constructor are non inherited as well as their cite is ever same equally the aeroplane cite its non possible to override them inwards Java, to acquire to a greater extent than close constructor come across here


    18) Can nosotros override in conclusion method inwards Java?
    No, yous cannot override in conclusion method inwards Java. Trying to override in conclusion method inwards subclass volition resultant inwards compile fourth dimension error. Actually making a method in conclusion is signal to all developer that this method is non for inheritance as well as it should travel job inwards its acquaint form. You mostly brand a method in conclusion due to safety reasons, to acquire to a greater extent than come across here.


    19) Can yous overload or override principal method inwards Java?
    Since main() is a static method inwards Java, it follows rules associated alongside static method, which agency yous tin overload principal method but yous cannot override it. By the way, fifty-fifty if yous overload a principal method, JVM volition ever telephone telephone the criterion public static void main(String args[]) method to start your program, if yous desire to telephone telephone your overloaded method yous demand to create it explicitly inwards your code equally shown here.


    That's all close simply about Java interview questions from method overloading as well as overriding concept. I must acknowledge its a tricky concept to master. I receive got seen fifty-fifty experienced developer struggling to solve quiz as well as multiple alternative questions based upon overloading as well as overriding. So, if yous desire to create good on Java Interviews equally good equally wants to write good, powerful as well as flexible code using object oriented programming technique, spare simply about fourth dimension to sympathise overloading as well as overriding inwards Java. It volition assistance yous to leverage Polymorphism better.


    Further Learning
    Data Structures as well as Algorithms: Deep Dive Using Java
    article]
  • 40 Core Java Questions from Phone Interviews [list]
  • 15 Java Enum Interview Questions alongside Answers as well as Explanations [questions]
  • 18 Java Interview Questions based upon GOF Design Patterns as well as OOP [questions]
  • Top 21 Frequently asked Java interview questions for freshers [article]
  • 12 Java Multithreading as well as Concurrency based Interview Questions [see here]
  • JDBC Interview Questions as well as Answers for 2 to iv years experienced developers [see here]
  • 10 Spring Framework based Interview Questions [article]
  • 10 Must know Java Collection framework Interview Questions as well as Answers [read here]
  • 10 Java Web Services based Questions [list]
  • Top 10 Advanced Java Questions for Experienced as well as Senior Programmers [see here]
  • 22 Array concepts based Interview Questions inwards Java? [answers]
  • How To Opposite Integer Inward Coffee - Leetcode Solution

    LeetCode has a occupation to opposite digits of an integer let out without using whatsoever library method similar reverse() method of StringBuffer. In LeetCode, yous tin displace solve this occupation amongst many unlike languages e.g. Java, C, C++, C#, Python, Ruby as well as fifty-fifty JavaScript. BTW, inwards the article, nosotros volition larn how to solve this occupation inwards Java. Before approaching solution let's kickoff read the occupation disceptation :

    Reverse digits of an integer.

    Example 1: x = 123, provide 321
    Example 2: x = -123, provide -321

    The occupation looks unproblematic but it's non unproblematic at that topographic point are many things yous request to consider inwards fellowship to create a solution which is accepted past times LeetCode, which has thousands of assay out cases to assay out your solution.


    For example, yous request to consider non precisely virtually positive integer but equally good virtually negative integer. Remember, a positive integer tin displace equally good live written using + sign, thence yous request to grip that equally well. If the integer's concluding digit is 0, what should the output be? i.e. cases such equally 10, 100.

    If the provide type of method is an integer as well as thence yous tin displace precisely provide 1, it's perfectly Ok, but if the provide type of method is String as well as thence yous may request to provide 001 or 0001. For the role of this solution, nosotros facial expression our method to provide an integer, thence 1 is fine.




    Java Solution : Reverse Integer without library method

    Here is my Java programme to solve this occupation of reversing integer let out without using whatsoever straight library method. The crux of this occupation is how to utilization sectionalization as well as modulo operator inwards Java to acquire the concluding digit of a let out as well as acquire rid of the concluding digit equally well.

    If yous remember, I cause got shared this describe a fast 1 on earlier when I was explaining how to utilization modulo operator inwards Java. This is a actually non bad describe a fast 1 on as well as volition assistance yous to solve many programming problems where yous request to split numbers into private digits. When yous split a let out past times 10, yous acquire rid of the concluding digit, for example, 211/10 volition give yous 21, as well as 21/10 volition give yous 2, thence yous got rid of concluding 2 digits past times dividing your let out past times 10 twice.

    Similarly, yous tin displace utilization let out modulo 10 to acquire the concluding digit of the number, for example, 221%10 volition provide 1, which is the concluding digit as well as 22%10 volition provide 2, which is the concluding digit of 22. You tin displace apply this logic until yous processed the concluding digit. Now the query comes, how attain yous adapt those digits inwards opposite order? Well, yous tin displace utilization precisely opposite i.e. multiplication as well as add-on to creating a novel let out amongst digits of the onetime let out inwards opposite order.  I cause got used next logic to gather digits into opposite fellowship :

    reverse = opposite * 10 + lastDigit;

    You tin displace run into past times multiplying let out past times 10 yous growth let out of digits past times 1 as well as and thence add together concluding digit. For negative numbers, nosotros multiply it past times -1 to kickoff arrive positive as well as and thence apply same logic, piece returning let out nosotros precisely multiply it past times -1 over again to convert the reversed let out into negative.

    import java.util.Scanner;  /**  * Java Program to opposite Integer inwards Java, let out tin displace live negative.  * Example 1:  x = 123, provide 321  * Example 2:  x = -123, provide -321  *  * @author Javin Paul  */  public class ReverseInteger{      public static void main(String args[]) {         int input = 5678;         int output = reverseInteger(5678);         System.out.println("Input : " + input + " Output : " + output);     }      /*      * Java method to opposite an integer value. at that topographic point are duet of corner cases      * which this method doesn't grip e.g. integer overflow.      */     public static int reverseInteger(int number) {         boolean isNegative = let out < 0 ? true : false;         if(isNegative){             let out = let out * -1;         }         int opposite = 0;         int lastDigit = 0;          while (number >= 1) {             lastDigit = let out % 10; // gives yous concluding digit             opposite = opposite * 10 + lastDigit;             let out = let out / 10; // acquire rid of concluding digit         }          return isNegative == true? reverse*-1 : reverse;     }  }  Result : Input : 5678 Output : 8765

    You tin displace run into that output is the precisely opposite of input. The kickoff digit has exchanged seat amongst concluding digit, minute amongst minute concluding as well as thence on.

    By the way, if yous are solving LeetCode problems equally component of your interview grooming as well as thence yous tin displace equally good see Programming Interviews Exposed and Cracking the Coding Interview, 2 of the most useful books for preparing programming chore interviews. You volition larn to a greater extent than inwards a curt time.



    JUnit Tests for Solution of Reverse Integer inwards Java

    Here is my express laid of JUnit tests for checking my solution. It checks for input nada as well as one, a unproblematic positive number, a negative number, a positive let out amongst summation sign as well as let out ending amongst zero. Our solution passes all the tests but it's non enough. If yous submit this solution on LeetCode it exclusively managed to exceed 1028 out of 1032 assay out cases. Yes, yous read it write, they cause got 1032 to assay out this problem, no wonder our solution failed. FYI, it failed for input 1534236469, run into if yous tin displace spot the põrnikas as well as create it.

    import org.junit.*; import static org.junit.Assert.*; /**  * JUnit assay out iv our solution to occupation of opposite Integer inwards Java.  *  * @author WINDOWS 8  *  */ public class ReverseIntegerTest{      @Test     public void testZeroAndOne(){         assertEquals(0, ReverseIntegerTest.reverseInteger(0));         assertEquals(1, ReverseIntegerTest.reverseInteger(1));           }         @Test     public void testSimple(){         assertEquals(4321, ReverseIntegerTest.reverseInteger(1234));         }         @Test     public void testNegative(){         assertEquals(-321, ReverseIntegerTest.reverseInteger(-123));           }         @Test     public void testNumberWithSign(){         assertEquals(321, ReverseIntegerTest.reverseInteger(+123));     }         @Test     public void testNumberEndingWithZero(){         assertEquals(1, ReverseIntegerTest.reverseInteger(1000));         assertEquals(1, ReverseIntegerTest.reverseInteger(10));           }     } 

    as well as hither is the trial of running these JUnit assay out illustration inwards Eclipse :

     LeetCode has a occupation to opposite digits of an integer let out without using whatsoever library m How to opposite Integer inwards Java - LeetCode Solution

    You tin displace run into that lovely greenish bar, which way all 5 tests are passed.

    That's all virtually how to opposite Integer inwards Java. By the way, this solution is prone to integer overflow as well as volition non live expected at Leetcode.  It exclusively managed to exceed 1028 assay out cases out of staggering 1032 tests as well as failed for input 1534236469. Expected solution, inwards that case, is nada but our programme impress something else, run into if yous tin displace spot the põrnikas as well as create it.

    Further Learning
    The Coding Interview Bootcamp: Algorithms + Data Structures
    Data Structures as well as Algorithms: Deep Dive Using Java
    solution)
  • How to swap 2 integers without using a temporary variable? (solution)
  • How to impress Fibonacci serial inwards Java without using Recursion? [solution]
  • How to banking concern fit if an integer is a ability of 2 without using sectionalization or modulo operator?[hint]
  • How to banking concern fit if a String is Palindrome inwards Java? [solution]
  • How to honor the missing let out inwards a sorted array inwards Java? [answer]
  • How to honor all permutation of String inwards Java? [solution]
  • How to remove element from array without using tertiary political party library (check here)
  • How to honor largest as well as smallest let out inwards an array inwards Java (read here)
  • How to honor 2 maximum let out on integer array inwards Java (check here)

  • Hint : Leetcode is OK if your role returns 0 when the reversed integer overflows. Since our code doesn't grip integer overflow similar this, I left this equally an practice for yous guys to fix.

    Difference Betwixt Public, Soul Together With Protected Modifier Inwards Java?

    In Java, you lot conduct maintain got something called access modifier, which specifies accessibility of class, methods too variables. There is iv access modifier inwards Java namely public, private, protected too the default access modifier, likewise known equally package grade modifier. The departure betwixt these access modifier comes inwards their powerfulness to throttle access to a class, method or variables, public is the to the lowest degree restrictive access modifier spell person is the most restrictive access modifier, package too protected lies inwards between. Another cardinal difference betwixt public, protected, packet too person modifier come upward from the indicate where you lot tin apply them, for example, you lot cannot purpose private or protected modifier alongside a transcend grade class but you lot tin purpose populace modifier there.

    The default or packet modifier is picayune flake special, when you lot create non specify whatever of the public, protected too person modifier, which is likewise the keywords, too then Java automatically apply a default modifier (no it doesn't purpose default keyword), which agency the said class, method or fellow member volition alone live accessible inside the package it has declared.

    Any class, which is exterior the said packet cannot access that element. The expert matter virtually these concepts is that departure betwixt public, protected too person inwards Java is likewise ane of the frequently asked Java interview questions.




    Difference betwixt public, packet too person modifier

    Apart from the fact that each access modifier allows members a specific grade of access, at that spot is or thence to a greater extent than subtle departure betwixt them e.g. where precisely tin you lot purpose them. Let's detect out to a greater extent than virtually unlike access modifiers inwards Java.

    1. One of the most of import departure you lot demand to shout back related to access modifier is the grade of accessibility e.g. anything populace is accessible to anywhere too anything person is alone accessible the class they are declared. Similarly, anything default is accessible alone within the packet too anything protected is accessible exterior the packet but alone to tyke classes.

    This means, you lot tin access populace class, method or variable from anywhere inwards Java computer program too that's why cardinal API are ever populace e.g. List interface, ArrayList class etc but you lot powerfulness desire to shroud their implementation too you lot tin create that past times using person access modifier.

    Why create you lot desire to shroud implementation? thence that you lot tin alter it afterwards without whatever worry that it volition interruption whatever client. One of the best examples of hiding implementation is RegularEnumSet too JumboEnumSet classes which implement EnumSet interface.

    EnumSet is populace too these ii classes are hidden at packet level, which allows EnumSet to conduct whatever of these depending upon cardinal size of Enum. If the enum whose constants you lot are storing inwards EnumSet has less than 64 too then it chooses RegularEnumSet which is to a greater extent than efficient.

    If you lot are looking for a Java evolution seat too preparing for ane too then you lot tin likewise accept assist from the wonderful book Java Interview Exposed past times Wrox. It is ane of the rare consummate guides for a Java developer too tells which topic is of import from interview indicate of view.

     you lot conduct maintain got something called access modifier Difference betwixt Public, Private too Protected modifier inwards Java?


    2. Second departure betwixt populace too modifier is that they supply Encapsulation, which is simply contrary of accessibility. Encapsulation says shroud anything which varies too that's why nosotros shroud implementations, populace keyword provides lowest grade of Encapsulation too person modifier provides highest grade of Encapsulation inwards Java.


    3. Third departure betwixt person too populace modifier is that you lot tin purpose populace modifier alongside transcend grade class but you lot cannot brand a transcend grade class person inwards Java. Though both populace too person modifier tin live used alongside class e.g. nested too inner classes. You tin brand an inner class person which agency no ane tin access it exterior enclosing class.

    Here is a overnice tabular array which compares access grade provided past times public, protected, person too default access modifier inwards Java.

     you lot conduct maintain got something called access modifier Difference betwixt Public, Private too Protected modifier inwards Java?











    As I said, purpose populace modifier to define API too purpose person modifier to shroud implementation, but you lot tin likewise brand constants populace e.g. class variable which is likewise marked lastly too static.




    Difference betwixt default too protected modifier inwards Java

    So, instantly you lot know the departure betwixt person too populace modifier inwards Java too empathise when to purpose populace too person inwards Java. Now, its fourth dimension to empathise departure betwixt default or packet grade access too protected modifier inwards Java.

    1) First difference betwixt default too protected access modifier inwards Java is that default is nil but packet grade accessibility i.e. if you lot don't supply whatever access modifier to a class, method or variable too then Java past times default brand them accessible within the package. If you lot cannot brand a fellow member person too then your side past times side best choice is package grade access. That's why its likewise called package-private access. On the other hand, protected modifier provides to a greater extent than accessibility too then default modifier. You tin access a protected fellow member exterior the package, but alone within sub classes.

    For event if a method getVersion() is protected within a class too they are within build packet too class is populace too then this method is accessible to all classes within cook packet but alone to sub classes exterior cook package.

    package build; public class Builder{  protected int getVersion(){    return 1; }  }

    too hither is our sub class :

    package gui; public class Display extends Builder {  public void show(){    System.out.println(getVersion()); //Ok, protected method tin live called from subclass exterior package }  }

    You tin run across that nosotros tin access getVersion() method which is protected, within or thence other packet gui without whatever problem.


    That's all virtually difference betwixt public, person too protected modifier inwards Java. Rule of pollex is to continue things equally much person equally possible because that allows you lot flexibility to alter them later. If you lot cannot brand them person too then at-least continue them package-private, which is likewise the default access grade for class, methods too variables inwards Java. You should likewise continue inwards hear that access modifier tin alone live applied to members e.g. variables too methods which are business office of class, you lot tin non brand a local variable public, person or protected inwards Java.

    If you lot similar give-and-take inwards this interview questions, you lot would likewise similar my explanation of other oft asked Java interview questions equally shown below :
    • Can nosotros override person method inwards Java? (answer)
    • Can nosotros override person method within inner class inwards Java? (answer)
    • What is departure betwixt overloading too overriding inwards Java? (answer)
    • Difference betwixt type-1 too type-2 JDBC driver inwards Java? (answer)
    • Difference betwixt == too equals() inwards Java? (answer)
    • What is departure betwixt String too StringBuffer inwards Java? (answer)

    2 Ways To Parse String To Int Inward Java

    Java provides Integer.parseInt() method to parse a String to an int value, merely that's non the exclusively means to convert a numeric String to int inward Java. There is, inward fact, a amend way, which takes wages of the parsing logic of parseInt() method every bit good every bit caching offered past times Flyweight blueprint pattern, which makes it to a greater extent than efficient together with useful. Yes, you lot guessed it right, I am talking almost Integer.valueOf() method, which implements Flyweight blueprint pattern together with maintains a cached puddle of ofttimes used int values e.g. from -128 to 127. So every fourth dimension you lot overstep a numeric String which is inward the hit of -128 to 127, Integer.valueOf() doesn't create a novel Integer object merely render the same value from cached pool. The exclusively drawback is that Integer.valueOf() returns an Integer object together with non an int primitive value similar parseInt() method, merely given auto-boxing is available inward Java from JDK five onward, which automatically convert an Integer object to int value inward Java.



    2 Examples to Parse String to int inward Java

    Here is our Java programme to convert String to int inward Java. This instance shows how to purpose both Integer.parseInt() together with Integer.valueOf() method to parse a numeric String to an int primitive inward Java. In this program, nosotros inquire the user to travel into a number together with thus nosotros read user input from the console using Scanner cast every bit String. Later nosotros convert that String using both Integer.parseInt() together with Integer.valueOf() method to demo that both methods run together with you lot tin dismiss purpose either of them.




    Java Program to Parse String to Int

    import java.util.Scanner;  /**  * two ways to convert String to int inward Java.  * User enters number, nosotros read it every bit String together with convert it to int using parseInt() method.  *   * @author WINDOWS 8  *  */ public class StringToInt {      public static void main(String args[]) {         System.out.println("Please travel into an integer number");                Scanner scnr = new Scanner(System.in);        String input = scnr.nextLine();                int i = Integer.parseInt(input);                System.out.println("String converted to int : " + i);                System.out.println("Please travel into closed to other integer number");                String str = scnr.nextLine();                int j = Integer.valueOf(str); // tin dismiss render cached value                System.out.println("String to int using valueOf() : " + j);              }       }  Output : Please travel into an integer number 100 String converted to int : 100 Please travel into closed to other integer number 300 String to int using valueOf() : 300

    You tin dismiss come across that both Integer.valueOf() together with Integer.parseInt() method is able to parse a numeric String. You tin dismiss fifty-fifty overstep a numeric String amongst Plus together with Minus sign, both methods are capable of parsing them successfully every bit shown below :
    Please travel into an integer number +201 String converted to int : 201 Please travel into closed to other integer number -203 String to int using valueOf() : -203

    merely if you lot overstep a String which contains anything other than +, - together with digits, you lot volition acquire java.lang.NumberFormatException every bit shown below :
    Please travel into an integer number ++201 Exception in thread "main" java.lang.NumberFormatException: For input string: "++201"     at java.lang.NumberFormatException.forInputString(Unknown Source)     at java.lang.Integer.parseInt(Unknown Source)     at java.lang.Integer.parseInt(Unknown Source)     at dto.ReverseIntegerTest.main(ReverseIntegerTest.java:22)

    You tin dismiss come across fifty-fifty double sign is besides non allowed, let's endeavor an alphanumeric String :
    Please travel into an integer number 2012a44 Exception in thread "main" java.lang.NumberFormatException: For input string: "2012a44"     at java.lang.NumberFormatException.forInputString(Unknown Source)     at java.lang.Integer.parseInt(Unknown Source)     at java.lang.Integer.parseInt(Unknown Source)     at dto.ReverseIntegerTest.main(ReverseIntegerTest.java:22)

    You tin dismiss come across that Integer.parseInt() doesn't similar anything other valid values inward numeric String. You volition acquire same errors fifty-fifty if you lot purpose Integer.valueOf() method because valueOf() method internally calls parseInt() method to parse String to integer inward Java.

    s non the exclusively means to convert a numeric String to int inward Java two ways to parse String to int inward Java

    That's all almost how to parse String to int inward Java. Even though parseInt() is the criterion means to parse String to int, you lot should endeavor to purpose Integer.valueOf() method. It implements Flyweight blueprint pattern together with maintains a puddle of ofttimes used int values e.g. int primitives from -128 to 127 together with that's how it relieve retention together with time.

    Though, you lot bespeak to last careful piece comparison it because if you lot purpose  equality operator (== )then Java compare their references together with render truthful exclusively if both variables are pointing to the same object e.g. ane of the Integer objects returned from a cached pool.

    So you lot mean value that == operator is working merely thus you lot volition come across issues when Integer object is exterior of that range, inward that case, == operator volition non work. In short, you lot receive got created a põrnikas which is difficult to find. See this story to larn to a greater extent than almost this bug.

     BTW, if you lot are learning Java together with desire to master copy fundamentals, I advise you lot receive got a await at Head First Java 2d Edition, they explicate the concept inward the easiest means possible merely besides brings out of import details.



    If you lot are novel to Java together with wants to larn almost how to convert ane type to another, cheque out my next information type conversion tutorials :
    • How to convert String to Double inward Java? (example)
    • How to convert ByteBuffer to String inward Java? (program)
    • How to convert double to Long inward Java? (program)
    • How to convert float to String inward Java? (example)
    • How to convert byte array to String inward Java? (program)
    • How to convert Enum to String inward Java? (example)
    • How to convert String to int inward Java? (example)
    • How to convert Decimal to Binary inward Java? (example)
    • How to convert String to Date inward a thread-safe manner? (example)
    • How to parse String to long inward Java? (answer)

    Further Learning
    Data Structures together with Algorithms: Deep Dive Using Java
    Java Fundamentals: The Java Language
    Complete Java Masterclass