Showing posts sorted by relevance for query classnotfoundexception-in-java-example. Sort by date Show all posts
Showing posts sorted by relevance for query classnotfoundexception-in-java-example. Sort by date Show all posts

Friday, November 22, 2019

Java- Exception Inwards Thread Master Copy Java.Lang.Noclassdeffounderror Movement Too Solution

NoClassDefFoundError inwards Java
The Exception inwards thread "main" java.lang.NoClassDefFoundError is a mutual mistake inwards Java which occurs if a ClassLoader is non able to uncovering a item shape inwards the classpath land trying to charge it. The Exception inwards thread "main" suggests that this mistake has occurred inwards the top dog thread, the thread which is responsible for running Java application. This mistake tin occur to whatsoever thread but if it happens inwards top dog thread in addition to so your plan volition crash. As per Javadoc, NoClassDefFoundError can locomote thrown during linking or loading of the shape file. It's denoted yesteryear java.lang.NoClassDefFoundError in addition to comes when that item shape is introduce during compile fourth dimension but somehow non available during runtime. This could locomote due to missing JAR file, whatsoever permission issue, or wrong classpath on runtime, depending upon your environment.


Java Programmers oft confuse betwixt java.lang.ClassNotFoundException and java.lang.NoClassDefFoundError in Java which is too related to shape loading inwards Java but at that topographic point is a slight deviation betwixt NoClassDefFoundError in addition to ClassNotFoundException inwards Java, The ClassNotFoundException comes when Java tries to charge a shape yesteryear its binary get upwards during runtime in addition to Class is non available at that time. for example, when you lot charge JDBC driver using Class.forName(String classname), you lot volition acquire java.lang.ClassNotFoundException instead of NoClassDefFoundError.

On the other hand, NoClassDefFoundError comes when the shape was available at compile fourth dimension but somehow non available at runtime e.g. if static initializer block of a shape throws an Exception during loading, the shape volition non locomote available for other's to use. If whatsoever shape examine to refer that shape in addition to so the classloader volition throw the java.lang.NoClassDefFoundError. If you lot like, you lot tin read to a greater extent than well-nigh their deviation inwards this article.




5 mutual causes of  Exception inwards thread "main" java.lang.NoClassDefFoundErro in Java

The Exception inwards thread "main" java.lang.NoClassDefFoundError inwards Java tin come upwards due to a multifariousness of reasons inwards Java, But most of the fourth dimension java.lang.NoClassDefFoundError comes due to CLASSPATH errors inwards Java. Influenza A virus subtype H5N1 right agreement of how classpath plant inwards Java is required to troubleshoot in addition to solve the  Exception inwards thread "main" java.lang.NoClassDefFoundError in Java.

Anyway hither are approximately of the mutual argue which has caused  Exception inwards thread "main" java.lang.NoClassDefFoundError in diverse Java application inwards past, your work could good locomote due to whatsoever of these reasons. 

1) Missing JAR file inwards Classpath
The offender shape is non available inwards the classpath of your Java application. For example, if you lot are getting "Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger" mistake inwards your application which agency classloader of your application is non able to uncovering org.apache.log4j.Logger shape inwards its classpath. The simplest reasons of this mistake are the missing log4j.jar file inwards the classpath. As before long every bit you lot add together that JAR into classpath the mistake goes away. See here to larn to a greater extent than well-nigh troubleshooting this item issue.

Similarly, you lot powerfulness convey seen java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject which comes if you lot are using XMLbeans but xmlbeans-2.60.jar is non introduce inwards your classpath (see here).


Another mutual 1 is java.lang.NoClassDefFoundError: org/dom4j/DocumentException, which comes due to missing dom4j.jar file (see here).

In short, the commencement measuring to solving "Exception inwards thread "main" java.lang.NoClassDefFoundError" is to banking concern tally if offender shape is available inwards classpath or not. In Eclipse, you lot tin purpose shortcuts similar search resources (Ctrl + R) or search type (Ctrl + T) to uncovering which JAR file that item shape belongs in addition to and so banking concern tally if that JAR is available inwards classpath or not. See here to larn to a greater extent than useful Eclipse shortcuts for Java developers.


2) Due to Visibility effect betwixt multiple Classloaders
Sometimes inwards complex environments e.g. Java EE container, it's possible that the offender cases is available inwards classpath but non visible to the classLoader which is trying to charge that item class. For example, inwards Java classloader run yesteryear delegation in addition to visibility. Influenza A virus subtype H5N1 shape loading asking is commencement delegated to bring upwards shape loader earlier shaver shape loader attempts to charge it, thence whatsoever shape loaded yesteryear bring upwards shape loader is visible to shaver shape loader but the reverse is non truthful i.e. a shape loaded yesteryear shaver classloader is non visible to bring upwards shape loader.

Suppose a shape is used yesteryear 2 JAR files e.g. WAR in addition to EJB-JAR file but it introduce inwards WAR file in addition to so it volition locomote visible to spider web app classloader but non create the classloader which loads the shape from EJB-JAR file.


3) Missing classpath entry inwards Manifest file
You tin too acquire the "Exception inwards thread "main" java.lang.NoClassDefFoundError" if you lot are running your Java application using java -jar ascendancy in addition to that shape were non defined inwards manifest file's ClassPath attribute. In past, I convey spent hours to figure out which JAR is missing solely to uncovering that Java is using the classpath defined inwards the manifest file in addition to non the classpath surroundings variable.

is a mutual mistake inwards Java which occurs if a Java- Exception inwards thread top dog java.lang.NoClassDefFoundError Cause in addition to Solution

4) Environment Issues 
I convey seen foreign reasons of java.lang.NoClassDefFound mistake land working inwards Java. In 1 instance 1 of the trounce scripts which was starting our Java application was overriding the value of here to larn to a greater extent than well-nigh how to add together multiople JAR files inwards classpath.



5) Error inwards Static Initializer block
One of the most mutual reasons for "Exception inwards thread "main" java.lang.NoClassDefFoundError" is mistake inwards static initializer block.  This is the block of code which is declared using static keyword in addition to executed when a shape is loaded. If suppose shape Influenza A virus subtype H5N1 throw Exception from static initializer block in addition to shape B uses shape A. In that instance when shape B volition locomote loaded it volition throw "Exception inwards thread "main" java.lang.NoClassDefFoundError" because it volition non locomote able to uncovering it's dependency which is shape A. 

So adjacent time, if you lot meet the NoClassDefFound mistake inwards your Java application, brand certain you lot search for static initializer mistake i.e. java.lang.ExceptionInInitializerError inwards your log file. That is the origin crusade of the NoClassDefFoundError you lot were seeing.


That's all on what is NoClassDefFoundError inwards Java in addition to what are the mutual argue which causes Exception inwards thread "main" java.lang.NoClassDefFoundError inwards Java. Most of the fourth dimension it's but a missing JAR file which causes this work but sometimes it tin locomote a nightmare to solve e.g. inwards instance your application is picking classpath from manifest file in addition to you lot are checking classpath entry somewhere else. In companionship to bargain alongside java.lang.NoClassDefFoundError, 2 things which are most of import is cognition of Classpath in addition to ClassLoader inwards Java. So, you lot should invest approximately fourth dimension on it. To start alongside you lot tin read Java Puzzlers yesteryear Joshua Bloch.


Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

Saturday, November 23, 2019

Common Reasons Of Java.Lang.Arrayindexoutofboundsexception Inwards Java

The ArrayIndexOutOfBoundsException, besides known equally java.lang.ArrayIndexOutOfBoundsExcepiton is ane of the most mutual errors inwards Java program. It occurs when Java programme tries to access an invalid index e.g. an index which is non positive or greater than the length of an array. For example, if you lot accept an array of String e.g. String[] cite = {"abc"} in addition to so trying to access name[1] volition grade java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 mistake because index 1 is invalid here. Why? because index inwards Java array starts amongst nix rather than 1, thus inwards an array of simply ane chemical factor the alone valid index is index zero.  This was ane of the most mutual scenarios which motility several 1000000 of ArrayIndexOutOfBoundsException daily. Sometimes it simply a patently programming mistake but sometimes if an array is populated exterior in addition to if at that topographic point is an mistake on feed than besides you lot acquire java.lang.ArrayIndexOutOfBoundsException inwards Java.

In this article, I volition portion amongst you lot around of the mutual reasons of ArrayIndexOutOfBoundsExcpetion in addition to their solution. This volition grade you lot plenty sense to bargain amongst this mistake inwards future.

In guild to solve ArrayIndexOutOfBoundsException, simply think next key details almost array inwards Java:

1) The array index inwards Java starts at nix in addition to goes to length - 1, for instance inwards an integer array int[] primes = novel int[10], the commencement index would live on nix in addition to end index out live on ix (10 -1)

2) Array index cannot live on negative, thus prime[-1] volition throw java.lang.ArrayIndexOutOfBoundsException.

3) The maximum array index tin live on Integer.MAX_VALUE -1 because the information type of index is int inwards Java in addition to the maximum value of int primitive is Integer.MAX_VALUE. See Big Java: Early Objects, fifth edition past times Cay S. Horstmann to larn to a greater extent than almost array information construction inwards Java. 

Now, let's run across around of the mutual examples of ArrayIndexOutOfBoundsException inwards Java




java.lang.ArrayIndexOutOfBoundsException length=0 index=0

This is the classic instance of accessing an empty array. Since length is nix it agency the array is empty in addition to the index is nix agency nosotros are trying to access the first chemical factor of the array. This happens when you lot elbow grease to access an array without checking its length, equally shown below.

public class Test {    public static void main(String[] args) {      int[] array = new int[0];      // bad code     int publish = array[0];      // proficient code     if (array.length > 0) {       publish = array[0];     }   }  }

When you lot run this programme you lot volition acquire next error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Test.main(Main.java:15)

Influenza A virus subtype H5N1 solution to this employment is to ever access array subsequently checking array length, equally shown inwards the proficient code snippet.


ArrayIndexOutOfBoundsExcepiton is ane of the most mutual errors inwards Java programme Common reasons of java.lang.ArrayIndexOutOfBoundsException inwards Java


java.lang.ArrayIndexOutOfBoundsException: length=1; index=1

This the minute most pop argue of ArrayIndexOutOfBoundsException inwards Java. Here you lot are trying to access an array past times its length. If you lot remember, the maximum valid index inwards the array is length -1 but if you lot somehow elbow grease to access index = length in addition to so you lot acquire this error. This ordinarily happens when you lot purpose <= or >= sign inwards for loop piece looping over an array in Java.

public class ABC {    public static void main(String[] args) {      int[] array = new int[10];     int amount = 0;      // bad code     for (int i = 0; i <= array.length; i++) {       amount = amount + array[i];     }      // proficient code     for (int i = 0; i < array.length; i++) {       amount = amount + array[i];     }   }  }

If you lot run this code, you lot volition acquire next mistake :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at ABC.main(Main.java:16)

This is because 10 is non a valid index for an array of length 10. The valid index is alone from 0 to 9. See a proficient information construction mass e.g. Introduction to Algorithm to larn to a greater extent than almost array information construction inwards general.



java.lang.ArrayIndexOutOfBoundsException length=12 index=-1
This is the tertiary mutual reasons of millions of ArrayIndexOutOfBoundsException. In this case, you lot are trying to access the array using a negative index. There could live on dissimilar reasons why index becomes negative but the bottom employment is you lot should non access an array amongst the negative index.


That's all almost 3 examples of ArrayIndexOutOfBoundsException inwards Java. You tin solve this mistake really easily If you lot think the key details almost array implementation inwards Java e.g. array index starting at nix in addition to no negative indexes are allowed. You should besides know that the maximum an index tin boot the bucket upward to Integer.MAX_VALUE value because the information type of index is int inwards Java.


Other Java troubleshooting guides you lot may like:
  • How to compass Unsupported major.minor version 52.0 inwards Java in addition to Eclipse? (fix)
  • General Guide to solve java.lang.ClassNotFoundException inwards Java [guide]
  • How to solve java.lang.ClassNotFoundException:org.Springframework.Web.Context.ContextLoaderListener [solution]
  • Exception inwards thread "main" java.lang.IllegalStateException during Iterator.remove() (fix)
  • How to connect to MySQL database from Java Program [steps]
  • How to solve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver inwards Java MySQL? [solution]
  • How to avoid ConcurrentModificationException inwards Java? (solution)
  • java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory? [solution]
  • How to solve java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver inwards Java? [solution]
  • How to fix java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver inwards Java? [solution]
  • How to compass java.lang.ClassNotFoundException: org.postgresql.Driver mistake inwards Java? [solution]
  • How to compass variable mightiness non accept been initialized mistake inwards Java? (solution)
  • How to fix Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger inwards Java? (fix)
  • java.sql.SQLException: No suitable driver flora for jdbc:jtds:sqlserver (solution)
  • Cause in addition to solution of java.lang.ClassNotFoundException: com.mysql.jdbc.Driver (solution)

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

Sunday, November 24, 2019

Avoid Concurrentmodificationexception Piece Looping Over Coffee Arraylist?

Apart from the NullPointerException in addition to ClassNotFoundException, ConcurrentModificationException is to a greater extent than or less other nightmare for Java developers. What makes this mistake tricky is the give-and-take concurrent, which ever mislead Java programmers that this exception is coming because multiple threads are trying to modify the collection at the same time. Then begins the hunting, they spent countless hours to unwrap the code which has the probability of concurrent modification. While inwards reality ConcurrentModficationException can likewise come upwardly on the unmarried threaded environment. To laissez passer y'all an example, simply loop over a listing using for loop in addition to endeavour to withdraw 1 element, y'all volition acquire the ConcurrentModificatoinExcetpion? Why? because you broke the dominion of non modifying a Collection during iteration.


How does Java knows to throw ConcurrentModificationExeption? It uses a transient variable called modCount, which keeps rails of how many times a listing is modified structurally. Structural modifications are those that alter the size of the list, which may deport on the progress of iteration in addition to may yield wrong results. Both Iterator in addition to ListIterator uses this plain to abide by unexpected change. Other methods of List which structurally modify List likewise uses this method e.g. add(), remove().


Problem: loop over an ArrayList in addition to withdraw selected elements, but remove() is throwing "Exception inwards thread "main" java.util.ConcurrentModificationException".



Cause: The existent elbow grease of ConcurrentModfiicationException is inconsistent modCount. When y'all are iterating over ArrayList in addition to then Iterator's next() method proceed rails of modCount. If y'all modify the collection past times adding or removing chemical constituent in addition to then modCount volition alter in addition to it volition non agree amongst the expected modCount, so Iterator volition throw ConcurrentModificationException.

Here is the code snippet from hasNext() method which shows at that topographic point is cheque for modCount:

public E next() {    checkForComodification();    int i = cursor;    if (i >= size)         throw new NoSuchElementException();     Object[] elementData = ArrayList.this.elementData;     if (i >= elementData.length)         throw new ConcurrentModificationException();     cursor = i + 1;     return (E) elementData[lastRet = i];  }

Now if y'all cheque this checkForComodification() method, y'all volition unwrap what I simply said:

final void checkForComodification() {     if (modCount != expectedModCount)       throw new ConcurrentModificationException(); }


Solution: Use Iterator if y'all are doing it on the unmarried threaded environment, otherwise piece of occupation concurrent collection classes e.g. CopyOnWriteArrayList to withdraw elements piece y'all are looping over it.


Solving ConcurrentModificationException inwards ArrayList

Here is the Java plan to demonstrate 1 scenario where y'all acquire the ConcurrentModificationException fifty-fifty if simply 1 thread is modifying the ArrayList. In this example, nosotros are looping over ArrayList using advanced for loop in addition to removing selected elements, but because nosotros are using ArrayList's remove() method.


import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List;  /**  * Java Program to demonstrate how to bargain amongst  * ConcurrentModificationException.  * Unlike the refer suggests, this mistake tin come upwardly fifty-fifty if alone   * 1 thread is modifying the collection e.g. List.   * It happens when y'all modify collection   * piece iterating over it e.g. adding novel chemical constituent or removing elements.  *   * If y'all desire to withdraw elements piece traversing listing in addition to then   * brand certain y'all piece of occupation Iterator's remove() method or non ArrayList's remove()  * method() to avoid ConcurrentModificationExcetpion.  *   * @author WINDOWS 8  *  */ public class ConcurrentModExceptionDemo{      public static void main(String args[]) {          List<String> listOfPhones = new ArrayList<String>(Arrays.asList(                 "iPhone 6S", "iPhone 6", "iPhone 5", "Samsung Milky Way 4", "Lumia Nokia"));                  System.out.println("list of phones: " + listOfPhones);                  // Iterating in addition to removing objects from list         // This is wrong way, volition throw ConcurrentModificationException         for(String telephone : listOfPhones){             if(phone.startsWith("iPhone")){                // listOfPhones.remove(phone); // volition throw exception             }         }                  // The Right way, iterating elements using Iterator's remove() method                  for(Iterator<String> itr = listOfPhones.iterator(); itr.hasNext();){                         String telephone = itr.next();                         if(phone.startsWith("iPhone")){                 // listOfPhones.remove(phone);  // wrong again                 itr.remove(); // right call             }         }                  System.out.println("list later removal: " + listOfPhones);      }  }  Output : listing of phones: [iPhone 6S, iPhone 6, iPhone 5, Samsung Galaxy 4, Lumia Nokia] listing later removal: [Samsung Galaxy 4, Lumia Nokia]

If y'all uncomment the commented code inwards showtime loop in addition to minute loop, y'all volition acquire the next exception:

Exception inwards thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at dto.ReverseArrayInPlace.main(ReverseArrayInPlace.java:28)

because nosotros are using ArrayList's remove() method. In the minute example, nosotros accept used remove() method of Iterator in addition to that's why nosotros are successfully able to delete selected elements from the ArrayList without ConcurrentModificationException.

Here is summary of of import points most solving ConcurrentModificationException piece looping over ArrayList inwards Java :

NullPointerException in addition to ClassNotFoundException Avoid ConcurrentModificationException piece looping over Java ArrayList?


That's all most how to bargain amongst ConcurrentModificationException inwards Java. The biggest affair to larn in addition to recollect is that this mistake tin come upwardly fifty-fifty if y'all accept simply 1 thread modifying collection e.g. removing elements piece looping over the list.

Further Learning
Java In-Depth: Become a Complete Java Engineer
solution)
  • How to solve "could non create the Java virtual machine" mistake inwards Java? (solution)
  • Fixing java.lang.unsupportedclassversionerror unsupported major.minor version 50.0 (solution)
  • java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory mistake (solution)
  • How to solve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error? (hint)
  • How to solve java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver? (solution)
  • java.lang.ClassNotFoundException : org.Springframework.Web.Context.ContextLoaderListener (solution)
  • How to create 'javac' is non recognized equally an internal or external command (solution)
  • How to create Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger (solution)
  • How to solve java.lang.OutOfMemoryError: Java Heap Space inwards Eclipse, Tomcat? (solution)

  • Saturday, November 23, 2019

    10 Reasons Of Java.Lang.Numberformatexception Inward Coffee - Solution

    The NumberFormatException is ane of the most mutual errors inwards Java application along amongst NullPointerException. This mistake comes when yous endeavor to convert a String into numeric information types e.g. int, float, double, long, short, char or byte. The information type conversion methods similar Integer.parseInt(), Float.parseFloat(), Double.parseDoulbe(), as well as Long.parseLong() throws NumberFormatException to signal that input String is non valid numeric value. Even though the origin sweat is ever something which cannot live on converted into a number, in that location are many reasons as well as input due to which NumberFormatException occurs inwards Java application. Most of the fourth dimension I convey faced this mistake acre converting a String to int or Integer inwards Java, but in that location are other scenarios every bit good when this mistake occurs. In this article, I am sharing 10 of the most mutual reasons of java.lang.NumberFormatException inwards Java programs.

    Having noesis of these sweat volition assistance yous to understand, analyze as well as solve this mistake inwards your Java application. In each case, you'll run across an mistake message as well as so I'll explicate the argue behind it. It's hard to embrace all scenarios on which JVM throws this mistake but I convey tried to capture every bit many every bit possible here. If yous detect whatsoever other reasons or faced this mistake inwards your Java projection due to anything mentioned below so delight portion amongst us via comments.




    10 mutual reasons of NumberFormatException 

    Here are 10 reasons which I convey seen causing NumberFormatException inwards Java application. If yous convey whatsoever argue which is non listed hither but yous convey seen them causing this error, experience costless to add together it.


    1. Null Value
    Since String is an object, it's possible that it could live on null as well as if yous overstep a null String to a method similar parseInt(), it volition throw NumberFormatException because nothing is non numeric.

    Integer.parseInt(null); Exception in thread "main" java.lang.NumberFormatException: null at java.lang.Integer.parseInt(Integer.java:454) at java.lang.Integer.parseInt(Integer.java:527)

    You tin sack run across that mistake message too contains the declaration to parseInt() which is nothing as well as that's the argue of this error. Thanks to JDK developers for printing the declaration every bit good as well as a lesson to all Java developers who create their custom Exception class, ever impress the input which failed the process.  If yous desire to larn to a greater extent than almost best practices, read Java Coding Guidelines.

     is ane of the most mutual errors inwards Java application along amongst  10 Reasons of java.lang.NumberFormatException inwards Java  - Solution



    2. Empty String
    Another mutual argue of java.lang.NumberFormatException is an empty String value. Many developers intend empty String is OK as well as parseInt() volition provide null or something, but that's non true. The parseInt(), or parseFloat() both volition throw NumberFormat mistake every bit shown below:

    Integer.parseInt(""); Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:504) at java.lang.Integer.parseInt(Integer.java:527)

    Again yous tin sack run across that this method has printed the input, which is empty String as well as which caused the failure.


    3. Alphanumeric Input
    Another mutual argue for NumberFormatException is the alphanumeric input. No non-numeric missive of the alphabet other than + as well as - is non permitted inwards the input string.

    Short.parseShort("A1"); Exception in thread "main" java.lang.NumberFormatException: For input string: "A1" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:492) at java.lang.Short.parseShort(Short.java:117) at java.lang.Short.parseShort(Short.java:143)

    You tin sack run across that our input contains "A" which is non permitted, thence it caused the error, but yous should recollect that Influenza A virus subtype H5N1 is a valid missive of the alphabet when yous convert String to an integer inwards hexadecimal base. See Java: How to Program yesteryear Dietel as well as Dietel to larn to a greater extent than almost information type conversion inwards Java.



    4. Leading space
    You won't believe but leading as well as trailing spaces are ane of the major reasons of NumberFormatException inwards Java, yous volition intend that input String " 123" is Ok but it's not. It has a leading infinite inwards it.

    Long.parseLong(" 123"); Exception in thread "main" java.lang.NumberFormatException: For input string: " 123" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Long.parseLong(Long.java:430) at java.lang.Long.parseLong(Long.java:483)

    Even though parseLong() method is correctly printing the invalid input, it's hard to location the leading or trailing mistake inwards log files, peculiarly trailing one. So, pay special attending to leading as well as trailing infinite acre converting String to long inwards Java, if possible run trim() before passing String to parseLong() method.


    5. Trailing space
    Similar to higher upwardly issue, trailing infinite is simply about other top dog argue for numerous NumberFormatException inwards Java. Influenza A virus subtype H5N1 trailing white infinite is harder to location than a leading white space, item inwards log files.

    Long.parseLong("1001 "); Exception in thread "main" java.lang.NumberFormatException: For input string: "1001 " at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Long.parseLong(Long.java:441) at java.lang.Long.parseLong(Long.java:483)

    To avoid this mistake yous should trim() the input String before passing it to parse methods e.g. parseInt() or parseFloat().



    6. Null String
    We'have already seen a scenario where parseInt() method throws NumberFormatException if the input is null, but sometimes yous volition run across an mistake message similar Exception inwards thread "main" java.lang.NumberFormatException: "null", this is dissimilar than the kickoff scenario. In the kickoff case, nosotros convey a null value, hither nosotros convey a "null" String i.e. an initialized String object whose value is "null". Since this is too non numeric, parseInt(), or parseFloat() volition throw the NumberFormat exception every bit shown below.

    Float.parseFloat("null"); Exception in thread "main" java.lang.NumberFormatException: For input string: "null" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1250) at java.lang.Float.parseFloat(Float.java:452)

    If yous are non familiar amongst the concept of nothing inwards Java, delight run across Core Java Volume 1 - Fundamentals yesteryear Cay S. Horstmann to larn more.



    7. Floating quest String
    This is fiddling chip different, fifty-fifty though "1.0" is perfectly valid String i.e. it doesn't comprise whatsoever alphanumeric String but if yous endeavor to convert it into integer values using parseInt(), parseShort(), or parseByte() it volition throw NumberFormatException because "1.0" is a floating quest value as well as cannot live on converted into integral one. These methods don't cast they simply create the conversion.

    Long.parseLong("1.0"); Exception in thread "main" java.lang.NumberFormatException: For input string: "1.0" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Long.parseLong(Long.java:441) at java.lang.Long.parseLong(Long.java:483)

    So, live on careful acre converting floating quest String to numbers, they tin sack exclusively live on converted to float or double, but non on integral types similar byte, short, or int.



    8. Out of hit value
    Another rare argue of java.lang.NumberFormatException is out-of-range value. For example, if yous endeavor to convert String "129" to a byte value it volition throw NumberFormatException because maximum positive number byte tin sack stand upwardly for is 127. Clearly, 129 is out-of-range for a byte variable

    Byte.parseByte("129"); Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"129" Radix:10 at java.lang.Byte.parseByte(Byte.java:150) at java.lang.Byte.parseByte(Byte.java:174)

    If yous are non familiar amongst information types as well as their hit inwards Java, delight run across Core Java for the Impatient for to a greater extent than information.



    9. Non-printable character
    While working inwards the software industry, sometimes yous confront an effect where yous intend the calculator is wrong, it has gone mad, the input String looks perfectly OK but withal Java is throwing NumberFormatException, this happens but at the end, yous volition realize that calculator is ever right.

    For example, consider this mistake message:
    java.lang.NumberFormatException: For input string: "1" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source)

    "1" is perfectly Ok for parseInt() as well as it volition run fine so why java.lang.NumberFormatException? It turns out that in that location was a non-printable grapheme inwards front end of 1 which was non displaying inwards the house where yous are seeing. So, sentinel out for the non-printable grapheme if yous are facing weird error.



    10. Similar characters e.g 1 as well as l
    This is the unopen cousin of before error, this fourth dimension too our oculus believes that input String is valid as well as intend that calculator has gone mad, but it wasn't. Only later spending hours yous realize that Java was right, the String yous are trying to convert into number was non numeric ane "1" instead it was little instance missive of the alphabet L i.e. "l". You tin sack run across it's real subtle as well as non obvious from naked oculus unless yous are actually paying attention.

    Integer.parseInt("l"); Exception in thread "main" java.lang.NumberFormatException: For input string: "l" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:492) at java.lang.Integer.parseInt(Integer.java:527)


    From the mistake message, it looks similar the mistake is for numeric String "1". So live on careful amongst this.

    Here is the prissy slide to combine all these reasons into one, which yous tin sack portion every bit good :

     is ane of the most mutual errors inwards Java application along amongst  10 Reasons of java.lang.NumberFormatException inwards Java  - Solution


    That's all almost 10 mutual reasons of java.lang.NumberFormatException as well as how to solve them. It's ane of those errors where yous involve to investigate to a greater extent than almost information than code. You involve to detect the source of invalid information as well as right it. In code, simply brand certain yous choose grip of the NumberFormatException whenever yous convert a String to number inwards Java. Also, if yous acquire input from the user, brand certain yous perform validation. Use Scanner if taking input from dominance work as well as methods similar nextInt() to direct read integer instead of reading String as well as so parsing it to int in ane trial to a greater extent than using parseInt() method, exclusively to live on greeted yesteryear NumberFormatExcpetion.


    Other Java troubleshooting tutorials you may similar to explore
    • How to create "Error: Could non detect or charge top dog class" inwards Eclipse? (guide)
    • How to avoid ConcurrentModificationException inwards Java? (tutorial)
    • How to solve "could non create the Java virtual machine" mistake inwards Java? (solution)
    • How to create "illegal start of expression" compile fourth dimension mistake inwards Java? (tutorial)
    • Fixing java.lang.unsupportedclassversionerror unsupported major.minor version 50.0 (solution)
    • Cause as well as solution of "class, interface, or enum expected" compiler mistake inwards Java? (fix)
    • java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory mistake (solution)
    • How to solve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error? (hint)
    • How to solve java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver? (solution)
    • Common reasons of java.lang.ArrayIndexOutOfBoundsException inwards Java? (solution)
    • java.lang.ClassNotFoundException : org.Springframework.Web.Context.ContextLoaderListener (solution)
    • How to solve "variable mightiness non convey initialized" compile fourth dimension mistake inwards Java? (answer)
    • How to create 'javac' is non recognized every bit an internal or external command (solution)
    • How to create Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger (solution)
    • How to solve java.lang.OutOfMemoryError: Java Heap Space inwards Eclipse, Tomcat? (solution)


    Further Learning
    Complete Java Masterclass
    Java Fundamentals: The Java Language
    Java In-Depth: Become a Complete Java Engineer!



    Friday, November 1, 2019

    Javax.Net.Ssl.Sslhandshakeexception: Sun.Security.Validator.Validatorexception: Pkix Path Edifice Failed: Sun.Security.Provider.Certpath.Suncertpathbuilderexception: Unable To Uncovering Valid Certification Path To Requested Target

    Hello guys, this is ane of the mutual fault inward a client-server application. The big work inward solving this fault is non the fault but the noesis of how client-server SSL handshake works. I convey blogged close that earlier in addition to if you lot convey read that you lot know that inward guild to connect to whatsoever website or server (like LDAP Server) using SSL, you lot withdraw to convey certificates (public keys) to validate the certificates sends past times the website you lot are connecting. If you lot don't convey the root certificate or populace key, which is required to validate the certificate presented past times the server inward your JRE truststore in addition to thus Java volition throw this error.

    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path edifice failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to honour valid certification path to requested target

    In guild to solve this error, just add together the root certificate required to connect to the server inward enquiry into truststore of your application's JRE.

    If you lot don't know, JVM uses 2 files, keystore in addition to truststore to shop the SSL certificates. keystore is to a greater extent than ofttimes than non used past times the server in addition to it contains both mortal in addition to populace key, piece truststore is to a greater extent than ofttimes than non used on client-side in addition to contains the populace fundamental of the server.

    One to a greater extent than challenge hither could hold out for beginners to honour which version of JRE their application is using in addition to what is the PATH for it. This is real of import because you lot withdraw to ascertain which trust shop your application is using? Is it using default truststore coming amongst JRE? or it has its ain truststore created?

    It's possible to instruct JVM to alternative an alternative truststore past times using or thus JVM arguments. For example, if you lot desire your Tomcat to alternative certificates from a specific truststore, you lot tin add together the next lines into CATALINA startup files:

      -Djavax.net.ssl.keyStore=%CLIENT_CERT% 
      -Djavax.net.ssl.keyStorePassword=changeit 
      -Djavax.net.ssl.trustStore=%CLIENT_CERT% 
      -Djavax.net.ssl.trustStorePassword=changeit


    Once you lot ascertain that which JRE in addition to truststore your Java application is using, the side past times side measurement is to upgrade the root certificate on the truststore. See The Complete Java Masterclass to learn to a greater extent than close truststore in addition to keystore in addition to other safety features of Java.

     this is ane of the mutual fault inward a customer javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path edifice failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to honour valid certification path to requested target


    how create you lot acquire the root certificate? Well, your Java cacerts which comes along JRE already contains the root certificate for most of CA (Certificate authority) which is acting inward populace domain similar Verisign, Thwate, if you lot are internally connecting to ane of the servers, you lot withdraw the root certificate issued past times your company. You tin verbalize to your SSL admins or Infra squad for that.

    Once you lot got the root certificate, to a greater extent than ofttimes than non a file amongst something abc.cer, you lot tin role the keytool command to add together that certificate into truststore used past times your application similar cacerts from JRE/security/lib folder.

    You tin role the next keytool ascendancy to add together certificates into keystore/truststore :

    $ keytool -import -alias -ca -file /tmp/root_cert.cer -keystore cacerts

    movement into the password every bit changeit, this default password for cacerts from JRE.

    Now, your final result should hold out sorted.

    Though, you lot withdraw to retrieve to supercede the certificate inward your truststore when the server does the certificate upgrade. For example, Recently, ane of user reported that their companionship migrated from SHA-1 certificate to SHA-2 certificate in addition to it started seeing this fault until he added the SHA-2 certificates on the trust shop of his application.

    Further Learning
    Complete Java Masterclass
    tutorial)
  • 7 Common Socket Errors in addition to Exception inward Java Application (article)
  • How to solve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error? (hint)
  • How to prepare Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger (solution)
  • How to prepare "Error: Could non honour or charge primary class" inward Eclipse? (guide)
  • 10 mutual reasons of java.lang.NumberFormatException inward Java? (tutorial)
  • How to avoid ConcurrentModificationException inward Java? (tutorial)
  • How to connect to MySQL database inward Java? (tutorial)
  • java.sql.BatchUpdateException: Error converting information type float to numeric - Java + SQL Server  (solution)
  • How to solve "could not create the Java virtual machine" fault inward Java? (solution)
  • java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory fault (solution)
  • Cause in addition to solution of "class, interface, or enum expected" compiler fault inward Java? (fix)
  • java.sql.SQLException: No suitable driver works life for 'jdbc:mysql://localhost:3306/mysql [Solution]
  • How to solve java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver? (solution)
  • How to prepare 'javac' is non recognized every bit an internal or external command (solution)
  • How to solve "variable mightiness non convey initialized" compile fourth dimension fault inward Java? (answer)
  • java.sql.SQLServerException: The index 58 is out of attain - JDBC (solution)
  • How to solve java.sql.BatchUpdateException: String or binary information would hold out truncated (guide)
  • Fixing java.lang.unsupportedclassversionerror unsupported major.minor version 50.0 (solution)
  • How to solve java.lang.OutOfMemoryError: Java Heap Space inward Eclipse, Tomcat? (solution)
  • 25 Exception Interview Questions for Java Programmers (list)
  • Common reasons of java.lang.ArrayIndexOutOfBoundsException inward Java? (solution)
  • java.lang.ClassNotFoundException : org.Springframework.Web.Context.ContextLoaderListener (solution)

  • Thanks for reading this article thus far. If you lot similar this article in addition to thus delight part amongst your friends in addition to colleagues. 

    P. S. - If you lot desire to acquire to a greater extent than close Security inward Java, I advise you lot cheque the Understanding the Java Virtual Machine: Security course of study on Pluralsight.

    Wednesday, December 11, 2019

    Top Xl Centre Coffee Interview Questions Answers From Telephonic Round

    Here is my to a greater extent than or less other ship nigh preparing for Java Interviews, this fourth dimension nosotros volition receive got a facial expression at 40 meat Java questions from telephonic round of Java Programming interviews. Phone interviews are unremarkably the offset measuring to covert candidate after selecting his resume. Since it's piece of cake to telephone telephone a candidate than to schedule a face-to-face interview, mass rooms in addition to conform for a meeting, telephonic circular of interviews are quite pop right away days. There were days exclusively i telephonic circular of interview was plenty but nowadays, it's almost ii in addition to iii circular of telephone interview alongside different squad members. Key to success inward telephonic interview is to the indicate in addition to concise answer. Since Interviewer wants to encompass lot of things on telephonic round, they appreciate to the indicate reply instead of blah blah in addition to dragging reply for sake of time. Always remember, its your fourth dimension to brand impression equally good therefore brand certain you lot receive got skillful phone, fully charged in addition to usage vocalism modulation technique to live equally clear equally possible. Even if you lot don't know the answer, think a loud, interviewer appreciate powerfulness to think in addition to to a greater extent than or less fourth dimension that proves to live decisive equally well.


    40 Core Java Interview Questions alongside Answers

    Here is my listing of xl meat Java-based questions which oft appear on telephonic circular of Interview. These questions touch-based of of import meat coffee concepts e.g. String, Thread basics, multi-threading, inter thread communication, Java Collection framework, Serialization, Object-oriented programming concepts in addition to Exception handling. If you lot receive got faced pair of Java interviews, you lot volition certain receive got seen to a greater extent than or less of these questions already. I receive got provided but plenty reply for the sake of telephonic interview, but if you lot desire to know more, you lot tin e'er banking venture check the detailed reply link.



    1) Difference betwixt String, StringBuffer in addition to StringBuilder inward Java? (detailed answer)
    String is immutable spell both StringBuffer in addition to StringBuilder is mutable, which agency whatsoever alter e.g. converting String to upper instance or trimming white infinite volition gain to a greater extent than or less other instance rather than changing the same instance. On after two, StringBuffer is synchronized spell StringBuilder is not, inward fact its a ditto replacement of StringBuffer added inward Java 1.5.


    2) Difference betwixt extends Thread vs implements Runnable inward Java? (detailed answer)
    Difference comes from the fact that you lot tin exclusively extend i course of report inward Java, which agency if you lot extend Thread course of report you lot lose your chance to extend to a greater extent than or less other class, on the other mitt if you lot implement Runnable, you lot tin even therefore extend to a greater extent than or less other class.



    3) Difference betwixt Runnable in addition to Callable interface inward Java? (detailed answer)
    Runnable was the exclusively way to implement a chore inward Java which tin live executed inward parallel earlier JDK 1.5 adds Callable. Just similar Runnable, Callable equally good defines a unmarried call() method but dissimilar run() it tin render values in addition to throw exceptions.


    4) Difference betwixt ArrayList in addition to LinkedList inward Java? (detailed answer)
    In short, ArrayList is backed past times array inward Java, spell LinkedList is but collection of nodes, similar to linked listing information structure. ArrayList equally good provides random search if you lot know the index, spell LinkedList exclusively allows sequential search. On other hand, adding in addition to removing chemical cistron from catch is efficient inward LinkedList equally compared to ArrayList because it exclusively require to modify links in addition to no other chemical cistron is rearranged.


    5) What is deviation betwixt hold off in addition to notify inward Java? (detailed answer)
    Both hold off in addition to notify methods are used for inter thread communication, where hold off is used to recess the thread on a status in addition to notify is used to ship notification to waiting threads. Both must live called from synchronized context e.g. synchronized method or block.


    6) Difference betwixt HashMap in addition to Hashtable inward Java? (detailed answer)
    Though both HashMap in addition to Hashtable are based upon hash tabular array information structure, at that topographic point are subtle deviation betwixt them. HashMap is non synchronized spell Hashtable is synchronized in addition to because of that HashMap is faster than Hashtable, equally at that topographic point is no toll of synchronization associated alongside it. One to a greater extent than pocket-size deviation is that HashMap allows a null key but Hashtable doesn't.


    7) Difference betwixt TreeSet in addition to TreeMap inward Java? (detailed answer)
    Though both are sorted collection, TreeSet is essentially a Set information construction which doesn't allow duplicate in addition to TreeMap is an implementation of Map interface. In reality, TreeSet is implemented via a TreeMap, much similar how HashSet is implemented using HashMap.


    8) Write a Java programme to impress Fibonacci series? (solution)
     Here is my to a greater extent than or less other ship nigh preparing for Java Interviews Top xl Core Java Interview Questions Answers from Telephonic RoundFibonacci series is a series of number on which a number is equal to amount of previous ii numbers i.e. f(n) = f(n-1) + f(n-2). This programme is used to instruct recursion to students but you lot tin equally good solve it without recursion. Check out the solution for both iterative in addition to recursive solution of this problem. In telephonic interview, this enquiry is non that mutual but sometime interviewer equally good wants to banking venture check your employment solving science using such questions.


    9) Write a Java programme to banking venture check if a number is Prime or not? (solution)
    Influenza A virus subtype H5N1 number is said prime number if it is non divisible past times whatsoever other number except itself. 1 is non considered prime, therefore your banking venture check must start alongside 2. Simplest solution of this to banking venture check every number until the number itself to regard if its divisible or not. When Interviewer volition inquire you lot to improve, you lot tin tell that checking until foursquare root of the number. If you lot tin farther improve the algorithm, you lot volition to a greater extent than impress your interviewer. banking venture check out the solution for how to do this inward Java


    10) How to Swap ii numbers without using temp variable? (solution)
    This enquiry is ages old. I receive got offset seen this enquiry way dorsum inward 2005 but I am certain its fifty-fifty older than that. Good affair nigh this employment is that except XOR clit a fast i on all solution has to a greater extent than or less flaws, which is used to attempt out whether candidate actually knows his materials or not. Check out the solution for all iii possible solution in addition to drawback of each.


    11) How to banking venture check if linked listing contains loop inward Java? (solution)
    This is to a greater extent than or less other employment solving enquiry which is real pop inward telephonic in addition to screening  round. This is a swell enquiry to attempt out employment solving science of candidate, peculiarly if he has non seen this enquiry before. It equally good has a dainty trivial followup to respect the starting of the loop. See the solution for a Java programme which finds loop inward singly linked.


    12) Write Java programme to contrary String without using API? (solution)
    One to a greater extent than enquiry to attempt out employment solving science of candidate. You wouldn't hold off these form of enquiry inward telephonic circular of Java interview but these questions receive got right away acquire norms. All interviewer is looking it for logic, you lot don't demand to write the code but you lot should live able to think of solution.


    13) Difference betwixt Serializable in addition to Externalizable inward Java? (detailed answer)
    Serializable is a marking interface alongside no methods defined it but Externalizable interface has ii methods defined on it e.g. readExternal() in addition to writeExternal() which allows you lot to command the serialization process. Serializable uses default serialization procedure which tin live real deadening for to a greater extent than or less application.


    14) Difference betwixt transient in addition to volatile inward Java? (detailed answer)
    transient keyword is used inward Serialization spell volatile is used inward multi-threading. If you lot desire to exclude a variable from serialization procedure therefore grade that variable transient. Similar to static variable, transient variables are non serialized. On the other hand, volatile variables are signal to compiler that multiple threads are interested on this variable in addition to it shouldn't reorder its access. volatile variable equally good follows happens-before relationship, which agency whatsoever write happens earlier whatsoever read inward volatile variable. You tin equally good brand non atomic access of double in addition to long variable atomic using volatile.


    15) Difference betwixt abstract course of report in addition to interface? (detailed answer)
    From Java 8 onwards deviation betwixt abstract course of report in addition to interface inward Java has minimized, right away fifty-fifty interface tin receive got implementation inward price of default in addition to static method. BTW, inward Java you lot tin even therefore extend but i course of report but tin extend multiple inheritance. Abstract course of report is used to furnish default implementation alongside but something left to customize, spell interface is used heavily inward API to define contract of a class.


    16) Difference betwixt Association, Composition in addition to Aggregation? (detailed answer)
    Between association, composition in addition to aggregation, composition is strongest. If purpose tin exists without whole than human relationship betwixt ii course of report is known equally aggregation but if purpose cannot exists without whole than human relationship betwixt ii course of report is known equally composition. Between Inheritance in addition to composition, after provides to a greater extent than flexible design.


    17) What is deviation betwixt FileInputStream in addition to FileReader inward Java? (detailed answer)
    Main deviation betwixt FileInputStream in addition to FileReader is that sometime is used to read binary information spell after is used to read text data, which agency after equally good consider graphic symbol encoding spell converting bytes to text inward Java.


    18) How do you lot convert bytes to graphic symbol inward Java? (detailed answer)
    Bytes are converted to graphic symbol or text information using graphic symbol encoding. When you lot read binary information from a file or network endpoint, you lot furnish a graphic symbol encoding to convert those bytes to equivalent character. Incorrect alternative of graphic symbol encoding may alter pregnant of message past times interpreting it differently.


    19) Can nosotros receive got render disputation inward finally clause? What volition happen? (detailed answer)
    Yes, you lot tin usage render disputation inward finally block, but it volition non forestall finally block from existence executed. BTW, if you lot equally good used render disputation inward endeavour block therefore render value from finally block alongside override whatever is returned from endeavour block.


    20) Can you lot override static method inward Java? (detailed answer)
    No, you lot cannot override static method inward Java because they are resolved at compile fourth dimension rather than runtime. Though you lot tin declare in addition to define static method of same cite in addition to signature inward shaver class, this volition enshroud the static method from parent class, that's why it is equally good known equally method hiding inward Java.


    21) Difference betwixt private, public, packet in addition to protected inward Java? (detailed answer)
    All 4 are access modifier inward Java but exclusively private, world in addition to protected are modifier keyword. There is no keyword for packet access, its default inward Java. Which agency if you lot don't specify whatsoever access modifier than past times default that volition live accessible within the same package. Private variables are exclusively accessible inward the course of report they are declared, protected are accessible within all classes inward same packet but exclusively on sub course of report exterior packet in addition to world variables e.g. method, course of report or variables are accessible anywhere. This is highest grade of access modifier in addition to furnish lowest shape of encapsulation.


    22) v Coding best practices you lot learned inward Java? (detailed answer)
    If you lot are developing on a programming linguistic communication for pair of years, you lot certain knows lots of best practices, past times quest pair of them, Interviewer but checking that you lot know your merchandise well. Here are my v Java best practices :
    - Always cite your thread, this volition assist immensely inward debugging.
    - Use StringBuilder for string concatenation
    - Always specify size of Collection, this volition salve lot of fourth dimension spent on resizing
    - Always declare variable mortal in addition to lastly unless you lot receive got skillful reason.
    - Always code on interfaces instead of implementation
    - Provide dependency to method instead they acquire it past times themselves, this volition brand your code unit of measurement testable.


    23) Write a Program to respect maximum in addition to minimum number inward array? (solution)
    This is to a greater extent than or less other coding enquiry attempt out employment solving powerfulness of candidate. Be prepare for pair of follow upward equally good depending upon how you lot reply this question. Simplest way which comes inward heed is to sort the array in addition to therefore pick the top in addition to bottom element. For a improve reply regard the solution.


    24) Write a programme to contrary Array inward place? (solution)
    Another employment solving enquiry for Java programmers. Key indicate hither is that you lot demand to contrary the array inward place, which agency you lot cannot usage additional buffer, i or ii variable volition live fine. Note you lot cannot usage whatsoever library code, you lot demand to do your ain logic.


    25) Write a programme to contrary a number inward Java? (solution)
    This is an interesting programme for a real junior programmer, right from the college but tin sometime puzzle developer alongside pair of years of sense equally well. Most of these developer does real trivial coding therefore they flora these form of questions challenging. Here the clit a fast i on is to acquire the lastly digit of the number past times using modulus operator (%) in addition to reducing number inward each driblet dead past times using partitioning operator (/). See the solution for how to do that inward Java.


    26) Write a Program to calculate factorial inward Java? (solution)
    Another beginners coding problem, skillful for telephonic interview because you lot tin differentiate a guy who tin write programme to the guy who can't. It's equally good skillful to regard if developer is familiar alongside both recursive in addition to iterative algorithm in addition to pros in addition to cons of each. You tin equally good inquire lots of follow upward e.g. how to improve functioning of algorithm? Since factorial of a number is equal to number multiplied past times factorial of previous number, you lot tin cache those value instead of recalculating them, this volition impress your interviewer a bit. See the solution for total code example.


    27) What is deviation betwixt calling start() in addition to run() method of Thread? (detailed answer)
    You mightiness receive got heard this enquiry before, if calling start() method calls the run() method eventually therefore why non but telephone telephone the run() method? Well the deviation is, start method equally good starts a novel thread. If you lot telephone telephone the run method straight therefore it volition run on same thread non on different thread, which is what master intention would be.


    28) Write a Program to solve Producer Consumer employment inward Java? (solution)
    Influenza A virus subtype H5N1 real skillful enquiry to banking venture check if candidate tin write inter thread communication code or not. If a guy tin write producer consumer solution past times mitt in addition to indicate out critical department in addition to how to protect, how to communicate alongside thread therefore he is skillful plenty to write in addition to hold your concurrent Java program. This is the real minimum requirement for a Java developer in addition to that's why I dearest this question, it equally good has several solution e.g. past times using concurrent collections similar blocking queue, past times using hold off in addition to notify in addition to past times using other synchronizers of Java v e.g. semaphores.


    29) How to respect catch chemical cistron of linked listing inward i pass? (solution)
    Another unproblematic employment solving enquiry for warm up. In a singly linked listing you lot tin exclusively traverse inward i direction in addition to if you lot don't know the size therefore you lot cannot write a loop to exactly respect out catch element, that is the crux of the problem. One solution is past times using ii pointers, fast in addition to slow. Slower pointer moves 1 measuring when faster pointer displace to 2 steps, causing deadening to indicate to catch when fast is pointing to goal of the listing i.e. null. Check out solution for Java code sample.


    30) What is equlas() in addition to hashCode() contract inward Java? Where does it used? (detailed answer)
    One of the must inquire enquiry inward Java telephonic interview. If a guy doesn't know nigh equals() in addition to hashCode() therefore he is in all probability non worth pursuing farther because its the meat of the Java fundamentals. The key indicate of contract is that if ii objects are equal past times equals() method therefore they must receive got same hashcode, but unequal object tin equally good receive got same hashcode, which is the motility of collision on hash tabular array based collection e.g HashMap. When you lot override equals() you lot must retrieve to override hashCode() method to driblet dead along the contract valid.


    31) Why hold off in addition to notify methods are declared inward Object class? (detailed answer)
    This enquiry is to a greater extent than to respect out how much sense you lot actually receive got in addition to what is your thinking towards Java API in addition to its blueprint decision. Similar enquiry is why String is immutable inward Java? Well, truthful reply tin exclusively live given past times Java designers but you lot tin argue something. For example, hold off in addition to notify methods are associated alongside locks which is owned past times object non thread, in addition to that's why it brand sense to driblet dead along those method on java.lang.Object class. See the detailed reply for to a greater extent than give-and-take in addition to reasoning.


    32) How does HashSet industrial plant inward Java? (detailed answer)
    HashSet is internally implemented using HashMap inward Java in addition to this is what your interviewer wants to hear. He could therefore quiz you lot alongside to a greater extent than or less mutual sense based enquiry e.g. how tin you lot usage HashMap because its needs ii object key in addition to value? what is the value inward instance of HashSet? Well, inward instance of HashSet a dummy object is used equally value in addition to key objects are the actual chemical cistron on Set indicate of view. Since HashMap doesn't allow duplicate key it equally good follows contract of laid information construction to non allow duplicates. See detailed reply for to a greater extent than analysis in addition to explanation.


    33) What is deviation betwixt synchronize in addition to concurrent Collection inward Java? (detailed answer)
    There was time, earlier Java 1.5 when you lot exclusively receive got synchronized collection if you lot demand them inward a multi-threaded Java program. Those classes were plagued alongside several number most importantly functioning because they lock the whole collection or map whenever a thread reads or writes. To address those issue, Java released pair of Concurrent collection classes e.g. ConcurrentHashMap, CopyOnWriteArrayList in addition to BlockingQueue to furnish to a greater extent than scalability in addition to performance.


    34) What is deviation betwixt Iterator in addition to Enumeration inward Java? (detailed answer)
    Main deviation is that Iterator was introduced inward house of Enumeration. It equally good allows you lot to take elements from collection spell traversing which was non possible alongside Enumeration. The methods of Iterator e.g. hasNext() in addition to next() are equally good to a greater extent than concise therefore corresponding methods inward Enumeration e.g. hasMoreElements(). You should e'er usage Iterator inward your Java code equally Enumeration may acquire deprecated in addition to removed inward futurity Java release.


    35) What is deviation betwixt Overloading in addition to Overriding inward Java? (detailed answer)
    Another oft asked enquiry from telephonic circular of Java interviews. Though both overloading in addition to overriding are related alongside methods of same names but they receive got different characteristics e.g.overloaded methods must receive got different method signature than master method but overridden method must receive got same signature. Also, overloaded methods are resolved at compiled fourth dimension spell overridden methods are resolved at runtime. See the detailed reply for to a greater extent than analysis in addition to differences.


    36) Difference betwixt static in addition to dynamic binding inward Java? (detailed answer)
    This is unremarkably asked equally follow-up of previous question, static binding is related to overloaded method in addition to dynamic binding is related to overridden method. Method similar private, lastly in addition to static are resolved using static binding at compile fourth dimension but virtual methods which tin live overridden are resolved using dynamic binding at runtime.


    37) Difference betwixt Comparator in addition to Comparable inward Java? (detailed answer)
    This is i to a greater extent than basic concept, I hold off every Java candidate to know. You volition bargain alongside them on every Java project. Several meat classes inward Java e.g. String, Integer implements Comparable to define their natural sorting social club in addition to if you lot define a value course of report or a domain object therefore you lot should equally good implement Comparable in addition to define natural ordering of your object. Main deviation betwixt these ii is that, you lot could do multiple Comparator to define multiple sorting social club based upon different attribute of object. Also, In social club to implement Comparable you lot must receive got access of the course of report or code, but you lot tin usage Comparator without having source code of class, all you lot demand is the JAR file of particular object. That's why Comparator is real powerful to implement custom sorting social club in addition to from Java 8 you lot tin do it fifty-fifty to a greater extent than elegantly, equally seen here.


    38) How do you lot sort ArrayList inward descending order? (solution)
    You tin usage Collections.sort() method alongside contrary Comparator, which tin sort elements inward the contrary social club of their natural social club e.g.
    List<String> listOfString = Arrays.asList("London", "Tokyo", "NewYork"); Collections.sort(listOfString, Collections.reverseOrder()); System.out.println(listOfString); //[Tokyo, NewYork, London]


    39) What is deviation betwixt PATH in addition to CLASSPATH inward Java? (detailed answer)
    PATH is an environs variable which points to Java binary which is used to run Java programs. CLASSPATH is to a greater extent than or less other environs variable which points to Java course of report files or JAR files. If a course of report is non flora inward CLASSPATH therefore Java throws ClassNotFoundException.


    40) What is deviation betwixt Checked in addition to Unchecked Exception inward Java? (detailed answer)
    Checked exception ensures that treatment of exception is provided in addition to its verified past times compiler also, spell for throwing unchecked exception no special provision is needed e.g. throws clause. Influenza A virus subtype H5N1 method tin throw unchecked exception without whatsoever throw clause.


    That's all nigh 40 Core Java Interview Questions from telephonic round. Don't receive got a telephone interview lightly, its your offset conduct chances to impress your perspective employer. Given that you lot are non seeing your interviewer in addition to but communicating alongside your voice, its trivial chip different than face-to-face interview. So e'er live calm, relaxed in addition to reply questions to the indicate in addition to precisely, verbalize piece of cake in addition to brand certain you lot are non inward a house where your audio echoes e.g. on closed stair case. Having a skillful phone, caput laid in addition to existence on skillful reception expanse is equally good real important. I receive got seen it many times where candidate lost on interview because non able to take heed it properly or non able to sympathize enquiry earlier answering them. I know to a greater extent than or less people receive got telephonic interviews on those undercover places but if you lot do brand certain your telephone connectivity is enough.

    If you lot similar this tutorial in addition to looking for to a greater extent than or less to a greater extent than interview questions for grooming checkout my amazing collection :
    • 10 Advanced Core Java Interview Questions for Programmers (see here)
    • 15 Java Enum based Interview Questions alongside Answers (check here)
    • 21 Frequently asked Java Questions alongside Answers (see here)
    • Top 10 Linux in addition to UNIX Interview Questions for Java Programmers (check here)
    • Top xx SQL Query Interview Questions (see list)
    • Java Interview Questions for 2 to 3 Years Experienced Programmers (see here)
    • 12 Multithreading in addition to Concurrency Questions for Java Developers (check here)
    • 10 Tough Java Questions from Interviews (see list)
    • Top eleven Coding Questions from Java Interviews alongside Answers (see here)
    • 18 Good Java Design Pattern Questions for Senior Developers (see here)
    • 15 Tricky Questions from Java Interviews alongside Answers (check here)