Showing posts sorted by relevance for query how-classloader-works-in-java. Sort by date Show all posts
Showing posts sorted by relevance for query how-classloader-works-in-java. Sort by date Show all posts

Sunday, February 13, 2011

Spring Helloworld Representative Inward Coffee Using Notation In Addition To Autowiring

Spring framework has gone a duad of releases since I in conclusion portion the Spring hullo basis representative alongside XML configuration. In this article, I am going to explicate to you lot how to do a Spring hullo basis representative alongside Spring 4.2 release in addition to yesteryear using Annotation for dependency injection in addition to autowiring. So no to a greater extent than XML files to specify edible bean dependencies. It's a unproblematic programme that shows how you lot tin utilisation the Spring framework to do Services that are loosely coupled. The representative volition exhibit you lot the basic concept of dependency injection yesteryear creating a unproblematic Java application that greets the user. It's genuinely a lilliputian fleck complex version of a unproblematic Helloworld programme but if you lot require decoupling in addition to in-direction you lot require to bring to a greater extent than or less marking of complexity. That's the toll you lot require to pay to accomplish the flexibility inwards your code.

In this example, I receive got a GreetingSevice interface which has but i method greet(). This method is supposed to render a greeting of the hateful solar daytime similar "Good Morning", "Good AfterNoon, "Good Evening" etc.

Then I receive got a GreetingBot which prints greeting. This shape is decoupled from the GreetingService implementation, alongside Spring Framework wiring everything together. This agency you lot tin render whatever variety of GreetingService to greet the user you lot desire similar "Hi", "Hello", "Howdy" or whatever you lot like.

This is possible because GreetingBot calls GreetingService.greet() method to impress messages. The expert affair is that you lot don't require to inject whatever dependency, everything is wired yesteryear Spring framework using auto-wiring.

If you lot are non familiar alongside auto-wiring, I advise you lot depository fiscal establishment correspond a comprehensive Spring framework course of written report like Spring MasterClass - Beginner to Expert. There are a lot of unlike options for wiring in addition to this course of written report volition exhibit you lot that inwards detail.




Java Source files in addition to classes

GreetingService.java
This is our Service interface, which defines a service method, implemented yesteryear a Service provider class.

package hello;   public interface GreetingService {   String greet(); }


GreetingBot.java
H5N1 shape that uses the GreetingService interface to impress greetings. In other words, this is the shape which greets user but it is subject on GreetingService for that in addition to Spring framework provides that dependency to this class. At runtime, Spring Framework injects an instance of GreetingService to this class, which is thence used yesteryear the print() method.

package hello;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;   @Component public class GreetingBot {     final private GreetingService service;     @Autowired   public GreetingBot(GreetingService service) {     this.service = service;   }     public void print() {     System.out.println(this.service.greet());   } }


Main.java
This is our application class, this is the shape from the execution of our Java application starts. This shape uses before classes to construct an application. This is the shape that is also annotated alongside @Configuration in addition to @ComponentScan annotations which agency it volition hold out used every bit configuration every bit well.

If you lot await at the code, you lot volition give away a main() method, the entry signal of Java application. In this method, the offset business of code is nearly ApplicationContext, which represents a Spring container. In this case, I receive got used AnnotationConfigApplicatoinContext, which is i implementation of this interface in addition to piece of job based upon annotations.

If you lot see, nosotros don't receive got whatever Spring XML config file, thence how does the container know nearly Spring bean? Well, that's where @Bean annotation is used. If you lot await closely, you lot volition come across nosotros receive got a method called mockGreetingService() which returns a mock implementation of GreetingService implementation, this method is annotated alongside @Bean annotations in addition to Spring uses this method to inject dependency on GreetingBot class.

When nosotros telephone weep upwards the context.getBean() method it returns an instance of GreetingBot which is properly configured alongside a mock implementation fo GreetingService interface. This all happens nether the hood in addition to its completely transparent to Java developer.  Btw, if you lot are interested to larn to a greater extent than you lot tin see Spring Framework 5: Beginner to Guru to larn to a greater extent than nearly Spring container in addition to how precisely the Spring framework works.


package hello;
import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.*;   @Configuration @ComponentScan public class Main {     @Bean   GreetingService mockGreetingService() {     return new GreetingService() {       public String greet() {         return "Good Day!";       }     };   }     public static void main(String[] args) {     ApplicationContext context = new AnnotationConfigApplicationContext(         Main.class);     GreetingBot greeter = context.getBean(GreetingBot.class);     greeter.print();   } }

Output:
Jan 14, 2016 6:30:15 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@a4a63d8: startup engagement [Thu January xiv 18:30:15 SGT 2016]; root of context hierarchy
Good Day!


You tin come across that our programme worked fine in addition to it printed "Good Day!" which comes from the mock implementation of the GreetingService interface. In this program, I receive got used a duad of essential Spring annotations similar @Bean, @Configuration, @ComponentScan, in addition to @Component, which may seem alien to many of you.

H5N1 edible bean is zilch but a replacement of edible bean tag inwards XML, ComponentScan a variety of auto-wiring, a Configuration agency this shape contains edible bean definitions in addition to a shape annotated alongside @Component agency it volition hold out detected for auto-wiring.

These are but basic materials but you lot desire to larn more, depository fiscal establishment correspond out Learn Spring: The Certification Class yesteryear Eugen Paraschiv of Baeldung, i of swain blogger in addition to jump instructor. It's genuinely i of the best course of written report to larn Spring five in addition to Spring Boot two from scratch, inwards a guided, code-focused way

 Spring framework has gone a duad of releases since I in conclusion portion the  Spring HelloWorld Example inwards Java using Annotation in addition to Autowiring



Required Dependencies (JAR Files)

If you lot are non using Maven, thence you lot require to seat a lot of JAR files inwards your application's classpath or if you lot are using Eclipse thence on its construct path. Spring Framework includes a seat out of unlike modules for unlike functionality, in addition to this application volition alone utilisation the marrow functionality provided inwards spring-context, which provides marrow functionality, but but including spring-context-4.2.1.RELEASE.jar volition non hold out enough.

You volition require a few to a greater extent than JAR i yesteryear i to satisfy both compile-time in addition to runtime dependency in addition to avoid those dreaded NoClassDefFoundError in addition to ClassNotFoundExceptions.

In short, you lot volition require the next JAR to run this Spring 4.2 HelloWorld Program inwards Eclipse.

  • spring-context-4.2.1.RELEASE.jar
  • spring-beans-4.2.1.RELEASE.jar
  • spring-core-4.2.1.RELEASE.jar
  • commons-logging-1.0.4.jar
  • spring-aop-4.2.1.RELEASE.jar
  • spring-expression-4.2.1.RELEASE.jar


Yes, that many JARs you lot volition need, but if you lot utilisation Maven or Gradle thence you lot but require to specify the next dependency into your pom.xml file and

<dependencies>   <dependency>      <groupId>org.springframework</groupId>     <artifactId>spring-context</artifactId>     <version>4.2.4.RELEASE</version>   </dependency> </dependencies>    
in addition to for Gradle:

dependencies {
   compile 'org.springframework:spring-context:4.2.4.RELEASE'
}




Error:

It may hold out possible that when you lot offset run the programme you lot acquire to a greater extent than or less error, mainly because your environs would hold out unlike than mine (that's where Docker helps, along alongside programme it also allows you lot to bring the environs needed yesteryear that program). I also faced i mistake spell writing this programme in addition to I receive got posted hither but inwards instance if you lot acquire the same one

Exception inwards thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.springframework.context.support.AbstractApplicationContext.<init>(AbstractApplicationContext.java:158)
at org.springframework.context.support.GenericApplicationContext.<init>(GenericApplicationContext.java:102)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:60)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:82)
at hello.Application.main(Application.java:21)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... five more

Solution:

1) Add Apache commons-logging framework JAR into your Eclipse construct path.


That's all nearly how to write Spring 4.2 HelloWorld representative inwards Eclipse IDE without using Maven. In this example, nosotros receive got also used Annotation in addition to Autowiring to acquire rid of the XML configuration file. We receive got used AnnotationConfigApplicationContext as Bean container instead of ClassPathApplicationContext, which scans Spring config files in addition to classpaths to inject the dependency.

Further Learning
Spring Framework 5: Beginner to Guru
features)
  • Top five Free Courses to larn Spring in addition to Spring Boot inwards 2019 (courses)
  • 5 Course to Master Spring Boot online inwards 2019 (courses)
  • 10 Things Java Developer should larn inwards 2019 (goals)
  • 10 Tools Java Developers utilisation inwards their day-to-day life (tools)
  • 10 Tips to perish a ameliorate Java developer inwards 2019 (tips)
  • 3 Best Practices Java Programmers tin larn from Spring (best practices)
  • 5 courses to larn Spring Boot in addition to Spring Cloud inwards 2019( courses)
  • 3 ways to alter Tomcat port inwards Spring Boot (tutorial)
  • 10 Spring MVC annotations Java developers should larn (annotations)
  • 15 Spring Boot Interview Questions for Java Programmers (questions)
  • 10 Spring Core Annotations Java Developers should larn (annotations)

  • Thanks for reading this article thence far. If you lot give away these Spring Boot annotations useful thence delight portion alongside your friends in addition to colleagues. If you lot receive got whatever questions or feedback thence delight drib a note.

    P. S. - If you lot desire to larn Spring in addition to looking for a costless online course of written report thence you lot tin also depository fiscal establishment correspond out the Spring Core - Learn Spring Framework iv in addition to Spring Boot on Udemy, it's completely costless in addition to all you lot require to do is do an concern human relationship to enroll into this course.

    Wednesday, December 11, 2019

    Top 21 Oftentimes Asked Coffee Interview Questions Answers

    If yous convey been to couplet of Java interviews hence yous know that at that spot are roughly questions which choke on repeating e.g. difference betwixt == as well as equals() method and may of it's pop cousins similar HashMap vs Hashtable, ArrayList vs LinkedList, departure betwixt equals() as well as hashCode(), or departure betwixt Comparator as well as Comparable inward Java. I telephone telephone them often asked Java interview questions, as well as I propose every Java developer to brand a listing of them for their ain reference as well as revision. I am certain many Java programmer already has such listing of questions handy, if non this is a expert fourth dimension to honor as well as brand your ain list. These are the questions which yous precisely can't afford to miss, especially at freshers level. They seem at diverse phase of Java interviews. Most probable yous volition run across them on telephonic round, where Interviewer precisely desire to filter candidates betwixt who knows Java as well as who doesn't.

    Good matter close them is that they are hence mutual that everyone knows close it. Though for freshers it could hold out picayune difficult. but equally your sense grows these often asked questions acquire much easier to answer.

    Some programmers besides prefer to collect often asked Java questions based upon topics e.g. mutual questions from threads, strings, collections and other pop Java interview topics, roughly of them are already shared yesteryear me. In this list, I am sharing roughly of the most often asked questions from Java interviews.

    By the way, when yous hold off the list, yous volition run across roughly of the classics are missing e.g. difference betwixt String as well as StringBuffer, but at that spot are many similar that, as well as that is job for yous to collect equally many equally possible as well as choke on them handy to avoid searching from them precisely earlier interview. I volition besides add together roughly to a greater extent than questions on this listing but for straightaway let's start alongside these 21 questions.




    Frequently Asked Core Java Question as well as Answer

     If yous convey been to couplet of Java interviews hence yous know that at that spot are roughly questions Top 21 Frequently Asked Java Interview Questions AnswersHere is my listing of roughly of the most mutual questions from Java interviews. You volition mostly run across these questions on telephonic circular of your interview, but it is besides asked a lot of fourth dimension during confront to confront interviews. It's non express to whatever particular fellowship equally well, inward fact all major information technology companies inward Republic of Republic of India e.g. TCS, CTS, Infosys, Tech Mahindra, HCL, Oracle Financial Services, as well as major investment banks similar Barclays Capital, Morgan Stanley, Goldman Sachs, Credit Suisse asked these form of fact based query on their Java recruitment drives. By the way, roughly questions are actually easy, as well as roughly are existent tough, hence it's mixed of both, but 1 matter is common, they are the most often asked questions from Java interviews.


    1)  How Java achieves platform independence?
    Answer : When nosotros country Java is platform independent which agency Java programs are non theme on whatever platform, architecture or operating organization similar windows or Linux. Java arrive at this yesteryear using Java virtual machine, when Java programs are compiled they are converted to .class file which is collection of byte code as well as straight understandable  by JVM. So the same Java plan tin dismiss run on whatever operating organization alone JVM tin dismiss differ according to OS but all JVM tin dismiss sympathize converted byte code that's how Java arrive at platform independence. For a to a greater extent than detailed reply of this question, run across here.


    2)  What is ClassLoader inward Java?
    Answer : This was 1 of advanced query few years ago, but inward bridge of 2 to 3 years, this has acquire really common. When a Java plan is converted into .class file yesteryear Java compiler  which is collection of byte code  class loader is responsible to charge that degree file from file system,network or whatever other location. This degree loader is nix but besides a degree from which place they are loading the degree according to that degree loaders are 3 types :
      1.Bootstrap
      2.Extension
      3.System degree loader .
    to larn to a greater extent than classloaders inward Java, run across my article how classloader industrial plant inward Java.


    3)  Write a Java plan to depository fiscal establishment check if a pose out is Even or Odd?
    Answer : This query is non especially related to Java as well as besides asked on other programming interviews e.g. C, C++ or C#. I convey included this inward my listing of often asked questions from Java interviews because I convey seen it to a greater extent than often than not.

    import java.util.Scanner;  class TestEvenOdd {  public static void main(String arg[]){    int num;    //Read a number    Scanner input = new Scanner(System.in);    System.out.println("Enter a pose out to depository fiscal establishment check its Even or Odd");    num = input.nextInt();    // Conditional operator    System.out.println((num%2)==0 ? "even number":"odd number");   } }


    4)  Difference betwixt ArrayList as well as HashSet inward Java?
    Answer : If I country that this is 1 of the most most often asked query to Java programmers, hence it would non hold out wrong. Along alongside questions similar ArrayList vs LinkedList as well as ArrayList vs Vector, this query is most mutual on diverse Java interviews. Here are roughly of import differences betwixt these 2 classes :

    1. ArrayList implements List interface piece HashSet implements Set interface inward Java.
    2. ArrayList is an ordered collection as well as maintains insertion lodge of elements piece HashSet is an unordered collection as well as doesn't hold whatever order.
    3. ArrayList allow duplicates piece HashSet doesn't allow duplicates.
    4. ArrayList is backed yesteryear an Array piece HashSet is backed yesteryear an HashMap instance.
    5. One to a greater extent than departure betwixt HashSet as well as ArrayList is that its index based yous tin dismiss think object yesteryear calling get(index) or withdraw objects yesteryear calling remove(index) piece HashSet is completely object based. HashSet besides doesn't render get() method.



    5)  What is double checked locking inward Singleton?
    Answer : Interviewer volition never halt quest this question. It's woman nurture of all often asked query inward Java. Singleton agency nosotros tin dismiss exercise alone 1 instance of that class,in term of singleton DCL is the way to  ensure that at whatever toll alone  one instance is created inward multi-threaded surroundings its possible that simultaneously 2 thread trying to exercise instance of singleton degree inward that province of affairs nosotros cant certain that alone 1 instance is created hence avoid this province of affairs using double checked locking yesteryear using synchronized block where nosotros creating the object.

    Code Example :
    class SingletonClass {   private DCL dcl = null;   public DCL getDCL() {     if (dcl == null) {       synchronized {         if (dcl == null)           dcl = new DCL();       }     }     return dcl;   } }
    To larn to a greater extent than close why double checked locking was broken earlier Java 1.5, run across this article.

    6)  How exercise yous exercise thread-safe Singleton inward Java?
    Answer : This is usually follow-up of previous Java question. There are to a greater extent than than 1 ways to exercise it. You tin dismiss  create thread security Singleton degree inward Java yesteryear creating the 1 as well as alone instance during degree loading. static fields are initialized during degree loading as well as Classloader volition guarantee that instance volition non hold out visible until its fully created.


    7)  When to utilisation volatile variable inward Java?
    Answer : Volatile keyword is used alongside alone variable  in Java as well as it guarantees that value of volatile variable volition ever hold out read from principal retentiveness as well as non from Thread's local cache. So nosotros tin dismiss utilisation volatile to arrive at synchronization because its guaranteed that all reader thread volition run across updated value of volatile variable 1 time write performance completed, without volatile keyword dissimilar reader thread may run across dissimilar values. Volatile modifier besides helps to preclude reordering of code yesteryear compiler as well as offering visibility guarantee yesteryear happens-before relationship. See this article to larn to a greater extent than close volatile inward Java.


    8)  When to utilisation transient variable inward Java?
    Answer : Transient inward Java is  used to betoken that the variable should non hold out serialized. Serialization is a procedure of saving an object's land inward Java. When nosotros desire to persist as well as object's land yesteryear default all instance variables inward the object is stored. In roughly cases, if yous desire to avoid persisting roughly variables because nosotros don’t convey the necessity to transfer across the network. So, declare those variables equally transient. If the variable is declared equally transient, hence it volition non hold out persisted. This is the principal purpose of the transient keyword, to larn to a greater extent than close transient variable inward Java, run across this tutorial.


    9)  Difference betwixt transient as well as volatile variable inward Java?
    Answer : This is 1 time again follow-up of previous 2 Java questions. You volition run across this query on laissez passer on 10 on whatever listing of Java often asked question. Here are roughly of the of import departure betwixt them.
    Transient variable : transient keyword is used alongside those instance variable which volition non participate inward serialization process.we cannot utilisation static alongside transient variable equally they are purpose of instance variable.
    Volatile variable : volatile keyword is used alongside alone variable  in Java as well as it guarantees that value of volatile variable volition ever hold out read from principal retentiveness as well as non from Thread's local cache, it tin dismiss hold out static.
    to larn to a greater extent than differences as well as reply this query inward detail, run across here.


    10) Difference betwixt Serializable as well as Externalizable inward Java?
    Answer : If I country this is 1 of the most often asked Java query on both face-to-face as well as telephonic interview hence it would hold out an exaggeration. Serialization is a default procedure of  serializing or persisting  any object's land inward Java. It's triggered yesteryear implementing Serializable interface which is a mark interface (an interface without whatever method). While Externalizable is used to customize as well as command default serialization procedure which is implemented yesteryear application. Main departure betwixt these 2 is that Externalizable interface provides consummate command to the degree implementing the interface whereas Serializable interface unremarkably uses default implementation to grip the object serialization process.
    Externalizable interface has 2 method writeExternal(ObjectOutput) as well as readExternal(ObjectInput) method which are used to grip customized object serialize procedure as well as inward damage of performance its expert because everything is nether control. to larn to a greater extent than close this classical question, run across this answer equally well.


    11) Can nosotros override somebody method inward Java?
    Answer : No, nosotros cannot override somebody methods inward Java equally if nosotros declare whatever variable ,method equally somebody that variable or method volition hold out visible for that degree alone as well as besides if nosotros declare whatever method equally somebody than they are bonded alongside degree at compile fourth dimension non inward run fourth dimension hence nosotros cant reference those method using whatever object hence nosotros cannot override somebody method inward Java.


    12) Difference betwixt Hashtable as well as HashMap inward Java?
    Answer : This is roughly other often asked query from Java interview. Main departure betwixt HaspMap as well as Hashtable are next :

    • HashMap allows zero values equally fundamental as well as value whereas Hashtable doesn't allow nulls.
    • Hashtable is thread-safe as well as tin dismiss hold out shared betwixt multiple threads whereas HashMap cannot hold out shared betwixt multiple threads without proper synchronization.
    • Because of synchronization, Hashtable is considerably slower than HashMap, fifty-fifty inward illustration of unmarried threaded application.
    • Hashtable is a legacy class, which was previously implemented Dictionary interface. It was afterwards retrofitted into Collection framework yesteryear implementing Map interface. On the other hand, HashMap was purpose of framework from it's inception.
    • You tin dismiss besides brand your HashMap thread-safe yesteryear using Collections.synchronizedMap() method. It's performance is similar to Hashtable.
    See hither to larn to a greater extent than as well as sympathize when to utilisation Hashtable as well as HashMap inward Java



    13) Difference betwixt List as well as Set inward Java?
    Answer : One to a greater extent than classic often asked question. List as well as laid both are really useful interfaces of  collections inward Java as well as  difference betwixt these 2 is listing allows duplicate chemical cistron but laid don't allows duplicate elements roughly other departure is listing hold the insertion lodge of chemical cistron but laid is unordered collection .list tin dismiss convey many zero objects but laid permit alone 1 zero element. This query is roughly fourth dimension besides asked equally departure betwixt Map, List as well as Set to arrive to a greater extent than comprehensive equally those 3 are major information construction from Java's Collection framework. To reply that query run across this article.


    14) Difference betwixt ArrayList as well as Vector inward Java
    Answer : One to a greater extent than favourite of Java Interviewers, at that spot is hardly whatever interview of junior Java developers, on which this query doesn't appear. In 4 as well as v circular of interview, yous volition definitely going to run across this query inward roughly dot of time. Vector as well as ArrayList both implement the listing interface but principal departure betwixt these 2 is vector is synchronized as well as thread security but listing is non because of this listing is faster than vector.


    15) Difference betwixt Hashtable as well as ConcurrentHashMap inward Java?
    Answer : Both Hashtable as well as ConcurrentHashMap is used inward multi-threaded surroundings because both are therad-safe but principal departure is on performance Hashtable's performance acquire wretched if the size of Hashtable acquire large because it volition hold out locked for long fourth dimension during iteration but inward illustration of concurrent HaspMap  only specific purpose is locked because concurrent HaspMap industrial plant on sectionalisation as well as other thread tin dismiss access the chemical cistron without iteration to complete. To larn to a greater extent than close how ConcurrentHashMap achieves it's thread-safety, scalability using lock stripping as well as non blocking algorithm, run across this article equally well.


    16) Which 2 methods yous volition override for an Object to hold out used equally Key inward HashMap?
    Answer : equals() as well as hashCode() methods needs to hold out override for an object to hold out used equally fundamental inward HaspMap. In Map objects are stored equally fundamental as well as value.  put(key ,value) method is used to shop objects inward HashMap at this fourth dimension hashCode() method is used to calculate the hash-code of fundamental object as well as both fundamental as well as value object is stored equally map.entry.if 2 fundamental objects convey same hash-code hence alone value object is stored inward that same bucket place but equally a linked listing value is stored as well as if hash code is dissimilar hence roughly other bucket place is created. While retrieving get(key) method is used at this fourth dimension hash code of fundamental object is calculated as well as hence equals() method is called to compare value object. to larn to a greater extent than close how get() method of HashMap or Hashtable works, run across that article.


    17) Difference betwixt hold off as well as slumber inward Java?
    Answer:  Here are roughly of import differences betwixt hold off as well as slumber inward Java

    1. wait() method free the lock when thread is waiting but sleep() method concur the lock when thread is waiting.
    2. wait() is a instance method as well as slumber is a static method .
    3. wait method is ever called from synchronized block or method but for slumber at that spot is no such requirement.
    4. waiting thread tin dismiss hold out awake yesteryear calling notify() as well as notifyAll() piece sleeping thread tin dismiss non hold out awaken yesteryear calling notify method.
    5. wait method is status based piece sleep() method doesn't require whatever condition. It is precisely used to pose electrical current thread on sleep.
    6. wait() is defined inward java.lang.Object degree piece sleep() is defined inward java.lang.Thread class


    18) Difference betwixt notify as well as notifyAll inward Java?
    Answer : principal departure betwixt notify as well as notifyAll is notify method volition wake upwards  or notify alone 1 thread as well as notifyall volition notify all threads. If yous are certain that to a greater extent than than 1 thread is waiting on monitor as well as yous desire all of them to give equal lead chances to compete for CPU, utilisation notifyAll method. See here to a greater extent than differences betwixt notify vs notifyAll.


    19) What is charge cistron of HashMap means?
    Answer : HashMap's performance depends on 2 things offset initial capacity as well as minute charge cistron whenever nosotros exercise HashMap initial capacity pose out of bucket is created initially as well as charge cistron is criteria to determine when nosotros convey to increase the size of HashMap when its close to acquire full.


    20) Difference betwixt PATH as well as Classpath inward Java?
    Answer : PATH is a surroundings variable inward Java which is used to assist Java plan to compile as well as run.To laid the PATH variable nosotros convey to include JDK_HOME/bin directory inward PATH surroundings variable as well as besides nosotros cannot override this variable. On the other hand,  ClassPath variable is used yesteryear degree loader to locate as well as charge compiled Java codes stored inward .class file. We tin dismiss laid classpath nosotros demand to include all those directory where nosotros convey pose either our .class file or JAR file which is required yesteryear your Java application,also nosotros tin dismiss override this surroundings variable.


    21) Difference betwixt extends Thread as well as implements Runnable inward Java
    This is the 21st often asked query inward my list. You volition run across this query equally offset or minute on multi-threading topic. One of the principal dot to pose across piece answering this query is Java's multiple inheritance support. You cannot to a greater extent than than 1 class, but yous tin dismiss implement to a greater extent than than 1 interface. If yous extend Thread degree precisely to override run() method, yous lose might of extending roughly other class, piece inward illustration of Runnable, yous tin dismiss yet implement roughly other interface or roughly other class. One to a greater extent than departure is that Thread is abstraction of independent path of execution, piece Runnable is abstraction of independent task, which tin dismiss hold out executed yesteryear whatever thread. That's why it's ameliorate to implement Runnable than extending Thread degree inward Java. If yous similar to dig more, run across this answer.


    That's all on this list of xx most often asked Java interview questions as well as answers. By the way, this is non precisely the alone listing yous got here, I convey shared a lot of interview questions on subject wise e.g. yous tin dismiss honor often asked questions from Thread, Collections, Strings as well as other of import Java classes. Apart from coding questions, these fact based Java programming linguistic communication questions are really of import to exercise good on whatever interview. It's fifty-fifty to a greater extent than of import for freshers as well as less experienced developer because they are usually asked these questions to a greater extent than often than experienced developers. By the way, yous are most welcome to contribute inward this list.

    Java.Lang.Noclassdeffounderror: Org/Dom4j/Documentexception [Solution]

    Exception inwards thread "main" java.lang.NoClassDefFoundError: org/dom4j/DocumentException comes when your computer programme is using DOM4j library but necessary JAR is non present. This mistake tin too come upward when y'all are indirectly using DOM4j library e.g. when y'all purpose Apache POI library to read XLSX file inwards Java,  this library needs dom4j.jar inwards your classpath. Not but this i but at that spot are several other libraries which purpose this JAR internally, if y'all are using whatever of them but don't convey this JAR hence your computer programme volition compile fine but neglect at runtime because JVM volition endeavour to charge this bird but volition non last able to honour it on the classpath. Some curious developers mightiness ask, why it didn't neglect during compile fourth dimension if JAR was non acquaint there? Well, the argue for that is that your code mightiness non last using whatever bird file straight from the dom4j.jar file.

    When y'all compile your computer programme e.g. ExcelReader.java, hence the compiler volition exclusively await for a bird file which is straight referenced or required to generate the bird file, it volition non await for transitive dependencies.

    For example, suppose y'all demand WorkBook bird from Apache  POI, which internally uses dom4j library, compiler volition complain if poi.jar is non there, but volition non complain fifty-fifty if dom4j.jar is non acquaint because its compiling your code, it's non compiling WorkBook class, it's already compiled because bird file of this code is already acquaint inwards poi.jar. But things works differently when your run the program, at that fourth dimension JVM volition await for all the binary code.

    When it volition charge WorkBook bird it volition endeavour to charge the referenced bird from DOM4j library as well as at that fourth dimension if JVM didn't honour those classes inwards CLASSPATH, it volition throw java.lang.NoClassDefFoundError: org/dom4j/DocumentException.

    It tin too come upward every bit java.lang.ClassNotFoundException: org.dom4j.DocumentException but exclusively if your code tries to charge this bird explicitly instead of JVM. That's truly the difference betwixt ClassNotFoundException as well as NoClassDefFoundError inwards Java. Now 1000000 dollar question? How practise y'all solve this error? Just add together a dom4j-1.6.1.jar file into classpath.




    Cause of java.lang.NoClassDefFoundError: org/dom4j/DocumentException

    As I said the source drive of this mistake is missing dom4j JAR file. It could last due to guide dependency or 3rd political party dependency e.g. y'all are using Apache POI library to read as well as write Excel file inwards Java as well as that library demand dom4j JAR file but y'all convey exclusively include poi.jar into your classpath.  Here is how the stack draw of this mistake volition await similar :

    Exception inwards thread "main" java.lang.NoClassDefFoundError: org/dom4j/DocumentException
            at org.apache.poi.openxml4j.opc.OPCPackage.init(OPCPackage.java:154)
            at org.apache.poi.openxml4j.opc.OPCPackage.<init>(OPCPackage.java:141)
            at org.apache.poi.openxml4j.opc.Package.<init>(Package.java:54)
            at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:82)
            at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:228)
            at org.apache.poi.util.PackageHelper.open(PackageHelper.java:39)
            at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:1
    87)
            at ExcelReader.main(ExcelReader.java:12)
    Caused by: java.lang.ClassNotFoundException: org.dom4j.DocumentException
            at java.net.URLClassLoader$1.run(Unknown Source)
            at java.net.URLClassLoader$1.run(Unknown Source)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.net.URLClassLoader.findClass(Unknown Source)
            at java.lang.ClassLoader.loadClass(Unknown Source)
            at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
            at java.lang.ClassLoader.loadClass(Unknown Source)
            ... 8 more

    Let's endeavour to sympathize this mistake stack-trace inwards detail. You tin come across that source drive of this mistake is  "java.lang.ClassNotFoundException: org.dom4j.DocumentException", which suggests farewell "Caused yesteryear :" line. You tin come across that JVM was trying to charge that class from the reference of "java.net.URLClassLoader". If y'all movement upward y'all tin too come across that this mistake was initiated from your code at ExcelReader.main(ExcelReader.java:12), which is the twelfth occupation of your ExcelReader.java source file, which is null but a unproblematic computer programme which read information from XLSX file inwards Java. If y'all cry back correctly, XLSX  is an Open XML format file as well as y'all demand the poi-ooxml-XX.jar file to read that file.  A bird called org.apache.poi.openxml4j.opc.OPCPackage needs org.dom4j.DocumentException as well as their JVM failed because it didn't works life org.dom4j.DocumentException bird because the JAR file which contains this bird file is non acquaint inwards CLASSPATH. 



    How to solve java.lang.NoClassDefFoundError: org/dom4j/DocumentException

    If y'all sympathize the drive of this work as well as solution is easy.  This exception tin last solved yesteryear adding dom4j-1.6.1.jar to the classpath. The exact version of JAR file depends on upon inwards your code or 3rd political party library which is using this JAR file. It may possible that adding arbitrary JAR may effect inwards another mistake or exception. Usually, this types of mistake come upward when y'all manually larn by your projection dependencies yesteryear downloading JAR files from the internet. I advise using Apache Maven to larn by projection dependencies because it too downloads transitive dependencies e.g. if y'all had used Maven to download poi-ooxml-XX.jar hence it would convey automatically downloaded the dom4j-XX.jar file. If at that spot is no selection as well as y'all convey to add together JAR files manually hence brand certain y'all read well-nigh 3rd political party dependencies of your library as well as download right version of JAR files. 

    j library but necessary JAR is non acquaint java.lang.NoClassDefFoundError: org/dom4j/DocumentException [Solution]



    That's all well-nigh how to solve java.lang.NoClassDefFoundError: org/dom4j/DocumentException mistake inwards Java. As y'all seen this mistake comes when your projection is using org.dom4j.DocumentException bird either straight or indirectly but the dom4j-1.6.1.jar file is non acquaint inwards CLASSPATH. In firm to solve java.lang.NoClassDefFoundError: org/dom4j/DocumentException just add together dom4j-1.6.1.jar file into your program's classpath. You tin too purpose the same solution to solve java.lang.ClassNotFoundException: org.dom4j.DocumentException mistake every bit well, because both are the just same exclusively divergence is that inwards the instance of old JVM initiated the procedure of loading a bird as well as inwards the instance of afterwards your code explicitly tried to charge the bird file. 

    Further Learning
    Complete Java Masterclass
    answer)
  • Difference betwixt RuntimeException as well as checked exception inwards Java? (answer)
  • Difference betwixt throw as well as throws inwards Java? (answer)
  • How to practise user defined exception inwards Java? (answer)
  • How to fix java.lang.OutOfMemoryError: Direct buffer retentiveness inwards Java (solution)
  • How to solve java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject? (solution)
  • Could non practise the Java virtual machine Invalid maximum heap size: -Xmx (solution)
  • java.lang.unsupportedclassversionerror unsupported major.minor version 50.0? (solution)
  • How to bargain with org.springframework.web.context.ContextLoaderListener ? (solution)
  • How to solve java.lang.OutOfMemoryError: Java heap infinite inwards Tomcat as well as Eclipse? (solution)
  • How to fix  java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver inwards Java? (solution)

  • Thursday, October 31, 2019

    50+ Basic Essence Coffee Interview Questions Amongst Hints As Well As Answers

    If you lot are preparing for your side past times side Core Java interview as well as looking for approximately mutual enquiry to practise or cheque your knowledge, as well as thence you lot accept come upwardly to the correct place. In this article, I'll portion 50 Core Java Interview Questions from diverse companies. I accept already discussed the answers to these questions inwards this spider web log or Javarevisited, thence I accept only set the link. First, you lot should endeavour to respond it yourself as well as if you lot cannot as well as thence acquire to the link as well as bring out the answer. You tin too compare your respond amongst mine as well as larn a few things hither as well as there. In most of my interview post, I accept too shared approximately mutual techniques to drive interview towards your comfort zone as well as how to acquire out a long-lasting impression on the interviewer, you lot tin work those techniques to do good on your Java interviews.

    These questions are useful for both freshers as well as experienced Java programmers, mostly 2 to v years of experience. It too covers all of import topics for centre Java interviews, e.g. Java Fundamentals, Java Collections Framework, Java Multithreading as well as Concurrency, Serialization, Design Patterns, as well as JVM as well as Classloading.



    Core Java Interview Questions amongst Answers

    Without whatever farther ado, hither is my listing of 50 Core Java Interview Questions amongst Answers equally a link:



    1)  How Java achieves platform independence? (answer)
    hint: bytecode as well as Java Virtual Machine

    2)  What is ClassLoader inwards Java? (answer)
    Hint: operate of JVM which loads bytecodes for classes. You tin write your own.

    3)  Write a Java computer program to cheque if a publish is Even or Odd? (answer)
    hint: you lot tin work bitwise operator, e.g. bitwise AND &, remember, fifty-fifty publish has nix at the terminate inwards binary format, as well as an strange publish has 1 inwards the end.

    4)  Difference betwixt ArrayList as well as HashSet inwards Java? (answer)
    hint:  all differences betwixt List as well as Set are applicable here, e.g. ordering, duplicates, random search, etc.

    5)  What is double-checked locking inwards Singleton? (answer)
    hint: two-time cheque whether instances is initialized or not, commencement without locking as well as instant amongst locking.

    6)  How do you lot do thread-safe Singleton inwards Java? (answer)
    hint: many ways, e.g. using Enum or past times using double-checked locking designing or using nested static class.

    7)  When to work a volatile variable inwards Java? (answer)
    hint: when you lot ask to learn JVM that a variable tin live modified past times multiple threads as well as give a hint to JVM that does non cache its value.

    8)  When to work a transient variable inwards Java? (answer)
    Hint:  when you lot desire to brand a variable non-serializable inwards a shape which implements the Serializable interface.  In other words, you lot tin work it for a variable whose value you lot don't desire to save.

    9)  Difference betwixt the transient as well as volatile variable inwards Java? (answer)
    hint: totally different, i used inwards the context of serialization acre other is used inwards concurrency.

    10) Difference betwixt Serializable as well as Externalizable inwards Java? (answer)
    hint: Externalizable gives you lot to a greater extent than command over the Serialization process.

    11) Can nosotros override the someone method inwards Java? (answer)
    hint: No, because it's non visible inwards the subclass, a principal requirement for overriding a method inwards Java.

     If you lot are preparing for your side past times side Core Java interview as well as looking for approximately mutual questi 50+ Basic Core Java Interview Questions amongst Hints as well as Answersanswer)
    Hint: several but most of import is Hashtable is synchronized acre HashMap is not. It's too legacy as well as irksome equally compared to HashMap.

    13) Difference betwixt List as well as Set inwards Java? (answer)
    hint: List is ordered as well as allows duplicate, Set is unordered as well as doesn't allow duplicate elements.

    14) Difference betwixt ArrayList as well as Vector inwards Java (answer)
    Hint:  Many, but most of import is that ArrayList is non-synchronized as well as fast acre Vector is synchronized as well as slow. It's too legacy shape similar Hashtable.

    15) Difference betwixt Hashtable as well as ConcurrentHashMap inwards Java? (answer)
    hint: to a greater extent than scalable

    16) How does ConcurrentHashMap attain scalability? (answer)
    hint: past times dividing the map into segments as well as exclusively locking during the write operation. You tin farther see The Complete Java Masterclass to larn to a greater extent than almost how ConcurrentHashMap works.

     If you lot are preparing for your side past times side Core Java interview as well as looking for approximately mutual questi 50+ Basic Core Java Interview Questions amongst Hints as well as Answers


    17) Which ii methods you lot volition override for an Object to live used equally Key inwards HashMap? (answer)
    hint: equals as well as hashcode

    18) Difference betwixt hold back as well as slumber inwards Java? (answer)
    hint: The wait() method releases the lock or monitor, acre slumber doesn't.

    19) Difference betwixt notify as well as notifyAll inwards Java? (answer)
    Hint: notify notifies i random thread is waiting for that lock acre notifyAll inform to all threads waiting for a monitor. If you lot are surely that exclusively i thread is waiting, as well as thence work notify, or else notifyAll is better.

    20) Why you lot override hashcode, along amongst equals() inwards Java? (answer)
    hint: to live compliant amongst equals as well as hashcode contract which is required if you lot are planning to shop your object into collection classes, e.g. HashMap or ArrayList.

    21) What is the charge cistron of HashMap means? (answer)
    hint: The threshold which triggers re-sizing of HashMap, by as well as large 0.75, which agency HashMap resize itself if it's 75% full.

    22) Difference betwixt ArrayList as well as LinkedList inwards Java? (answer)
    Hint: same equally an array as well as linked list, i allows random search acre other doesn't. Insertion as well as deletion piece of cake on the linked list, but a search is piece of cake on an array.

    23) Difference betwixt CountDownLatch as well as CyclicBarrier inwards Java? (answer)
    hint: You tin reuse CyclicBarrier after the barrier is broken, but you lot cannot reuse CountDownLatch after the count reaches to zero. You tin farther see Multithreading as well as Parallel Computing inwards Java course of written report on Udemy to larn to a greater extent than almost concurrency utility classes similar CyclicBarrier, Phaser, as well as CountDownLatch inwards Java.

     If you lot are preparing for your side past times side Core Java interview as well as looking for approximately mutual questi 50+ Basic Core Java Interview Questions amongst Hints as well as Answers


    24) When do you lot work Runnable vs. Thread inwards Java? (answer)
    hint: always

    25) What is the pregnant of Enum type-safe inwards Java? (answer)
    Hint: It agency you lot cannot assign an representative of dissimilar Enum type to an Enum variable. e.g., if you lot accept a variable similar DayOfWeek day, as well as thence you lot cannot assign it value from DayOfMonth enum.

    26) How does Autoboxing of Integer piece of work inwards Java? (answer)
    hint: using valueOf() method

    27) Difference betwixt PATH as well as Classpath inwards Java? (answer)
    hint: PATH is used past times the operating arrangement acre Classpath is used past times JVM to locate Java binary, e.g. JAR files or Class files.

    28) Difference betwixt method overloading as well as overriding inwards Java? (answer)
    Hint: Overriding happens at subclass acre Overloading happens inwards the same class. Also, overriding is a runtime activeness acre overloading is resolved at compile time.

    29) How do you lot preclude a shape from beingness sub-classed inwards Java? (answer)
    hint: only brand its constructor private

    30) How do you lot limit your shape from beingness used past times your client? (answer)
    hint:  brand the constructor someone or throw an exception from the constructor

    31) Difference betwixt StringBuilder as well as StringBuffer inwards Java? (answer)
    hint: StringBuilder is non synchronized acre StringBuffer is synchronized.

    32) Difference betwixt Polymorphism as well as Inheritance inwards Java? (answer)
    hint: Inheritance allows code reuse as well as builds the human relationship betwixt class, which is required past times Polymorphism, which provides dynamic behavior.

    33) Can nosotros override static method inwards Java? (answer)
    hint: No because overriding resolves at runtime acre static method telephone phone is resolved at compile time.

    34) Can nosotros access the someone method inwards Java? (answer)
    hint: yes, inwards the same shape but non exterior the class

    35) Difference betwixt interface as well as abstract shape inwards Java? (answer)
    hint: from Java 8, the divergence is blurred, but notwithstanding a Java shape tin implement multiple interfaces but tin extend only i class.



    36) Difference betwixt DOM as well as SAX parser inwards Java? (answer)
    Hint: DOM loads whole XML File inwards retention acre SAX doesn't. It is an event-based parser as well as tin live used to parse a large file, but DOM is fast as well as should live preferred for pocket-sized files.

    37) Difference betwixt throw as well as throws keyword inwards Java? (answer)
    hint: throws declare what exception a method tin throw inwards representative of mistake but throw keyword genuinely throws an exception.

    38) Difference betwixt fail-safe as well as fail-fast iterators inwards Java? (answer)
    hint: fail-safe doesn't throw ConcurrentModificationException acre fail-fast does whenever they honour as well as exterior modify on underlying collection acre iterating over it.

    39) Difference betwixt Iterator as well as Enumeration inwards Java? (answer)
    hint: Iterator too gives you lot the mightiness to take away an chemical ingredient acre iterating acre Enumeration doesn't allow that.

    40) What is IdentityHashMap inwards Java? (answer)
    hint: Influenza A virus subtype H5N1 Map which uses  == equality operator to cheque equality instead of equals() method.

    41) What is String puddle inwards Java? (answer)
    Hint: Influenza A virus subtype H5N1 puddle of String literals. Remember it's moved to heap from perm gen infinite inwards JDK 7.

    42) Can a Serializable shape comprise a non-serializable champaign inwards Java? (answer)
    hint: Yes, but you lot ask to acquire far either static or transient.

    43) Difference betwixt this as well as super inwards Java? (answer)
    hint: this refers to the electrical flow representative acre super refers to an representative of the superclass.

    44) Difference betwixt Comparator as well as Comparable inwards Java? (answer)
    hint: Comparator defines custom ordering acre Comparable defines the natural lodge of objects, e.g. the alphabetic lodge for String.

    45) Difference betwixt java.util.Date as well as java.sql.Date inwards Java? (answer)
    hint: erstwhile contains both appointment as well as fourth dimension acre afterward contains exclusively appointment part.

    46) Why hold back as well as notify method are declared inwards Object shape inwards Java? (answer)
    hint: because they require lock which is exclusively available to an object.

    47) Why Java doesn't back upwardly multiple inheritances? (answer)
    Hint: It doesn't back upwardly because of a bad sense amongst C++, but amongst Java 8, it does inwards approximately sense. Only multiple inheritances of Type is non supported inwards Java now.

    48) Difference betwixt Checked as well as Unchecked Exception inwards Java? (answer)
    hint: In representative of checked, you lot must grip exception using grab block, acre inwards representative of unchecked, it's upwardly to you, compile volition non bother you.

    49) Difference betwixt Error as well as Exception inwards Java? (answer)
    hint: I am tired of typing, delight cheque the answer

    50) Difference betwixt race status as well as deadlock inwards Java? (answer)
    hint: both are errors occur inwards a concurrent application, i occurs because of thread scheduling acre others occur because of pitiable coding.


    Resources
    Java Interview Guide: 200+ Interview Questions as well as Answers
    Spring Framework Interview Guide - 200+ Questions & Answers
    Preparing For a Job Interview By John Sonmez
    Java Programming Interview Exposed past times Markham
    Cracking the Coding Interview - 189 Questions as well as Answers
    Data Structure as well as Algorithms Analysis for Job Interviews

    Thanks for reading this article thence far. If you lot similar these Core Java Questions, as well as thence delight portion amongst your friends as well as colleagues. If you lot accept whatever questions or feedback, as well as thence delight driblet a note.

    Sunday, November 24, 2019

    Top X Tricky Coffee Interview Questions Too Answers

    What is a tricky question? Well, tricky Java interview questions are those questions which direct maintain some surprise chemical component on it. If yous endeavour to reply a tricky enquiry amongst mutual sense, yous volition most probable neglect because they require some specific knowledge. Most of the tricky Java questions comes from confusing concepts similar component subdivision overloading as well as overriding, Multi-threading which is truly tricky to master, grapheme encoding, checked vs unchecked exceptions as well as subtle Java programming details similar Integer overflow. Most of import thing to reply a tricky Java enquiry is mental attitude as well as analytical thinking, which helps fifty-fifty if yous don't know the answer. Anyway inward this Java article nosotros volition run across 10 Java questions which are existent tricky as well as requires to a greater extent than than average cognition of Java programming linguistic communication to reply them correctly. As per my experience, in that location is e'er ane or 2 tricky or tough Java interview question on whatever meat Java or J2EE interviews, therefore it's proficient to fix tricky questions from Java inward advance.

    If I direct maintain an interview, I purposefully position this variety of enquiry to approximate the depth of candidate's agreement inward Java. Another wages of bespeak such enquiry is the surprising element, which is a key cistron to position the candidate on some pressure level during interviews.

    Since these questions are less common, in that location is proficient adventure that many Java developer doesn't know virtually it.  You won't detect these questions fifty-fifty on pop Java interview books similar Java Programming Interview exposed, which is all the same an splendid guide for Java interviews.

    Btw, if yous don't detect these enquiry tricky enough, therefore yous should depository fiscal establishment check Joshua Bloch's some other classic book, Java Puzzlers for super tricky questions. I am sure yous volition detect them challenging enough.




    10 Tricky Java interview enquiry - Answered

    Here is my listing of 10 tricky Java interview questions, Though I direct maintain prepared as well as shared lot of hard meat Java interview enquiry as well as answers, But I direct maintain chosen them every bit Top 10 tricky questions because yous tin non guess answers of this tricky Java questions easily, yous demand some subtle details of Java programming linguistic communication to reply these questions.

    Question: What does the next Java plan print?
    public class Test {     public static void main(String[] args) {         System.out.println(Math.min(Double.MIN_VALUE, 0.0d));     } }
    Answer: This enquiry is tricky because dissimilar the Integer, where MIN_VALUE is negative, both the MAX_VALUE as well as MIN_VALUE of the Double course of report are positive numbers. The Double.MIN_VALUE is 2^(-1074), a double constant whose magnitude is the to the lowest degree amid all double values. So dissimilar the obvious answer, this plan volition impress 0.0 because Double.MIN_VALUE is greater than 0. I direct maintain asked this enquiry to Java developer having sense upwards to 3 to v years as well as surprisingly almost 70% candidate got it wrong.


    What volition give off if yous position render declaration or System.exit () on endeavour or grab block? Will finally block execute?
    This is a really pop tricky Java enquiry as well as it's tricky because many programmers think that no thing what, but the finally block volition e'er execute. This enquiry challenge that concept past times putting a render declaration inward the endeavour or grab block or calling System.exit() from endeavour or grab block. Answer of this tricky enquiry inward Java is that finally block volition execute fifty-fifty if yous position a render declaration inward the endeavour block or grab block but finally block won't run if yous telephone band System.exit() from endeavour or grab block.


    Question: Can yous override a mortal or static method inward Java?
    Another pop Java tricky question, As I said method overriding is a proficient theme to inquire play tricks questions inward Java. Anyway, you tin non override a mortal or static method inward Java, if yous create a similar method amongst same render type as well as same method arguments inward fry course of report therefore it volition enshroud the superclass method, this is known every bit method hiding.

    Similarly, yous cannot override a mortal method inward sub course of report because it's non accessible there, what yous do is create some other mortal method amongst the same advert inward the fry class. See Can yous override a mortal method inward Java or to a greater extent than details.



    Question: What do the facial expression 1.0 / 0.0 volition return? volition it throw Exception? whatever compile fourth dimension error?
    Answer: This is some other tricky enquiry from Double class. Though Java developer knows virtually the double primitive type as well as Double class, acre doing floating indicate arithmetics they don't pay plenty attending to Double.INFINITY, NaN, as well as -0.0 as well as other rules that principle the arithmetics calculations involving them. The elementary reply to this enquiry is that it volition non throw ArithmeticExcpetion as well as render Double.INFINITY.

    Also, Federal Reserve annotation that the comparing x == Double.NaN e'er evaluates to false, fifty-fifty if x itself is a NaN. To attempt if x is a NaN, ane should occupation the method telephone band Double.isNaN(x) to depository fiscal establishment check if given number is NaN or not. If yous know SQL, this is really around NULL there.

    Btw, If yous are running out of fourth dimension for your interview preparation, yous tin likewise depository fiscal establishment check out Java Programming Interviews exposed for to a greater extent than of such pop questions,


     tricky Java interview questions are those questions which direct maintain some surprise chemical component on i Top 10 Tricky Java interview questions as well as Answers



    Does Java back upwards multiple inheritances?
    This is the trickiest enquiry inward Java if C++ tin back upwards instantly multiple inheritances than why non Java is the declaration Interviewer often give. Answer of this enquiry is much to a greater extent than subtle therefore it looks like, because Java does back upwards multiple inheritances of Type past times allowing an interface to extend other interfaces, what Java doesn't back upwards is multiple inheritances of implementation. This distinction likewise gets blur because of default method of Java 8, which at nowadays provides Java, multiple inheritances of demeanor every bit well. See why multiple inheritances are non supported inward Java to reply this tricky Java question.



    What volition give off if nosotros position a key object inward a HashMap which is already there?
    This tricky Java enquiry is component subdivision of some other oft asked question, How HashMap industrial plant inward Java. HashMap is likewise a pop theme to create confusing as well as tricky enquiry inward Java. Answer of this enquiry is if yous position the same key ane time again therefore it volition supersede the former mapping because HashMap doesn't allow duplicate keys. The Same key volition lawsuit inward the same hashcode as well as volition halt upwards at the same seat inward the bucket.

     Each bucket contains a linked listing of Map.Entry object, which contains both Key as well as Value. Now Java volition direct maintain the Key object from each entry as well as compare amongst this novel key using equals() method, if that render truthful therefore value object inward that entry volition live replaced past times novel value. See How HashMap industrial plant inward Java for to a greater extent than tricky Java questions from HashMap.



    Question: What does the next Java plan print?
    public class Test {     public static void main(String[] args) throws Exception {         char[] chars = new char[] {'\u0097'};         String str = new String(chars);         byte[] bytes = str.getBytes();         System.out.println(Arrays.toString(bytes));     } }

    Answer: The trickiness of this enquiry lies on grapheme encoding as well as how String to byte array conversion works. In this program, nosotros are get-go creating a String from a grapheme array, which only has ane grapheme '\u0097', afterward that nosotros are getting the byte array from that String as well as printing that byte. Since \u0097 is within the 8-bit attain of byte primitive type, it is reasonable to guess that the str.getBytes() telephone band volition render a byte array that contains ane chemical component amongst a value of -105 ((byte) 0x97).

    However, that's non what the plan prints as well as that's why this enquiry is tricky. As a thing of fact, the output of the plan is operating arrangement as well as locale dependent. On a Windows XP amongst the the U.S. locale, the higher upwards plan prints [63], if yous run this plan on Linux or Solaris, yous volition acquire different values.

    To reply this enquiry correctly, yous demand to know virtually how Unicode characters are represented inward Java char values as well as inward Java strings, as well as what role grapheme encoding plays inward String.getBytes().

    In elementary word, to convert a string to a byte array, Java iterate through all the characters that the string represents as well as plough each ane into a number of bytes as well as finally position the bytes together. The dominion that maps each Unicode grapheme into a byte array is called a grapheme encoding. So It's possible that if same grapheme encoding is non used during both encoding as well as decoding therefore retrieved value may non live correct. When nosotros call str.getBytes() without specifying a grapheme encoding scheme, the JVM uses the default grapheme encoding of the platform to do the job.

    The default encoding system is operating arrangement as well as locale dependent. On Linux, it is UTF-8 as well as on Windows amongst a the U.S. locale, the default encoding is Cp1252. This explains the output nosotros acquire from running this plan on Windows machines amongst a the U.S. locale. No thing which grapheme encoding system is used, Java volition e'er interpret Unicode characters non recognized past times the encoding to 63, which represents the grapheme U+003F (the enquiry mark, ?) inward all encodings.



    If a method throws NullPointerException inward the superclass, tin nosotros override it amongst a method which throws RuntimeException?
    One to a greater extent than tricky Java questions from the overloading as well as overriding concept. The reply is yous tin really good throw superclass of RuntimeException inward overridden method, but yous tin non do same if its checked Exception. See Rules of method overriding inward Java for to a greater extent than details.



    What is the number amongst next implementation of compareTo() method inward Java
    public int compareTo(Object o){    Employee emp = (Employee) o;    return this.id - e.id; }
    where an id is an integer number.
    Well, 3 is zilch wrong inward this Java enquiry until yous guarantee that id is e'er positive. This Java enquiry becomes tricky when yous can't guarantee that id is positive or negative. the tricky component subdivision is, If id becomes negative than subtraction may overflow as well as create an wrong result. See How to override compareTo method inward Java for the consummate reply of this Java tricky enquiry for an experienced programmer.



    How do yous ensure that due north thread tin access due north resources without deadlock?
    If yous are non good versed inward writing multi-threading code therefore this is a existent tricky enquiry for you. This Java enquiry tin live tricky fifty-fifty for the experienced as well as senior programmer, who are non truly exposed to deadlock as well as race conditions. The key indicate hither is ordering, if yous acquire resources inward a exceptional lodge as well as liberate resources inward the contrary lodge yous tin forestall deadlock. See how to avoid deadlock inward Java for a sample code example.



    Question: Consider the next Java code snippet, which is initializing 2 variables as well as both are non volatile, and 2 threads T1 as well as T2 are modifying these values every bit following, both are non synchronized
    int x = 0; boolean bExit = false;  Thread 1 (not synchronized) x = 1;  bExit = true;  Thread 2 (not synchronized) if (bExit == true)  System.out.println("x=" + x);
    Now tell us, is it possible for Thread 2 to impress “x=0”?

    Answer: It's impossible for a listing of tricky Java questions to non incorporate anything from multi-threading. This is the simplest ane I tin get. Answer of this enquiry is Yes, It's possible that thread T2 may impress x=0.Why? because without whatever didactics to compiler e.g. synchronized or volatile, bExit=true might come upwards earlier x=1 inward compiler reordering. Also, x=1 powerfulness non transcend away visible inward Thread 2, therefore Thread 2 volition charge x=0. Now, how do yous ready it?

     When I asked this enquiry to a pair of programmers they reply differently, ane suggests to brand both threads synchronized on a mutual mutex, some other ane said brand both variable volatile. Both are correct, every bit it volition forestall reordering as well as guarantee visibility.

    But the best reply is yous only demand to make bExit as volatile, therefore Thread 2 tin entirely impress “x=1”. x does non demand to live volatile because x cannot live reordered to come upwards after bExit=true when bExit is volatile.



    What is deviation betwixt CyclicBarrier as well as CountDownLatch inward Java
    Relatively newer Java tricky question, entirely been introduced from Java 5. The master copy deviation betwixt both of them is that yous tin reuse CyclicBarrier fifty-fifty if Barrier is broken, but yous tin non reuse CountDownLatch inward Java. See CyclicBarrier vs CountDownLatch inward Java for to a greater extent than differences.


    What is the deviation betwixt StringBuffer as well as StringBuilder inward Java?
    Classic Java questions which some people think tricky as well as some reckon really easy. StringBuilder inward Java was introduced inward JDK 1.5 as well as the entirely deviation betwixt both of them is that StringBuffer methods e.g. length(), capacity() or append() are synchronized acre corresponding methods inward StringBuilder are non synchronized.

    Because of this primal difference, concatenation of String using StringBuilder is faster than StringBuffer. Actually, it's considered the bad practise to occupation StringBuffer anymore, because, inward almost 99% scenario, yous perform string concatenation on the same thread. See StringBuilder vs StringBuffer for to a greater extent than differences.



    Can yous access a non-static variable inward the static context?
    Another tricky Java enquiry from Java fundamentals. No, yous tin non access a non-static variable from the static context inward Java. If yous try, it volition give compile fourth dimension error. This is truly a mutual job beginner inward Java human face upwards when they endeavour to access instance variable within the master copy method. Because master copy is static inward Java, as well as instance variables are non-static, yous tin non access instance variable within main. See, why yous tin non access a non-static variable from static method to larn to a greater extent than virtually this tricky Java questions.


    How many String objects are created past times the next code?
     tricky Java interview questions are those questions which direct maintain some surprise chemical component on i Top 10 Tricky Java interview questions as well as Answers


    Now, it's practise time, hither are some questions for yous guys to answer, these are contributed past times readers of this blog, big thank yous to them.
    1. When doesn't Singleton rest Singleton inward Java?
    2. is it possible to charge a course of report past times 2 ClassLoader?
    3. is it possible for equals() to render false, fifty-fifty if contents of 2 Objects are same?
    4. Why compareTo() should live consistent to equals() method inward Java?
    5. When do Double as well as BigDecimal give different answers for equals() as well as compareTo() == 0. 
    6. How does "has before" apply to volatile work?
    7. Why is 0.1 * 3 != 0.3,
    8. Why is (Integer) 1 == (Integer) 1 but (Integer) 222 != (Integer) 222 as well as which ascendence arguments alter this.
    9. What happens when an exception is thrown past times a Thread?
    10. Difference betwixt notify() as well as notifyAll() call?
    11. Difference betwixt System.exit() as well as System.halt() method?
    12. Does next code legal inward Java? is it an instance of method overloading or overriding?
    13. public String getDescription(Object obj){    return obj.toString; } public String getDescription(String obj){    return obj; } as well as public void getDescription(String obj){    return obj; }


    This was my listing of Some of the most mutual tricky questions inward Java. It's non a bad thought to fix tricky Java enquiry earlier appearing for whatever meat Java or J2EE interview. One or 2 open-ended or tricky enquiry is quite mutual inward Java interviews.


    Further Reading
    If yous are looking for super challenging play tricks coding questions therefore yous should depository fiscal establishment check out Joshua Bloch some other classic book, the Java Puzzlers, I am sure yous sick detect them truly challenging to solve, I sure as shooting did.

     tricky Java interview questions are those questions which direct maintain some surprise chemical component on i Top 10 Tricky Java interview questions as well as Answers



    Hungry for to a greater extent than Java Interview Question as well as Answer post, depository fiscal establishment check out these articles