Sunday, April 21, 2024

Java Coding Challenges For Interview

Don't Miss

Why Is Java Coding Popular Among Employers

Java Interview Coding Challenge #2: Two Sum [Java Brains]

One of the biggest reasons Java is popular among employers is because of its independence. As long as your computer has the Java Runtime Environment, you can execute a Java program on your computer. Most computers can handle a JRE, including Macintosh, Linux, Unix, Windows and selective mobile phones.

Features that make Java programming popular include:

  • It’s easy to learn and implement.

  • Any code written with Java can run on virtually any computing platform.

  • The code is robust enough to independently run Java programs without any external dependencies.

  • Java has experienced consistent development.

  • It’s a memory management and multithreaded programming language.

Related:12 Tough Interview Questions and Answers

Top 6 Java Interview Questions For Senior Developers

  • Whats the difference between using HashMap and HashTable?
  • Whats the relationship between polymorphism and inheritance?
  • How does garbage collection work in Java?
  • Scaffold out the architecture you would need to build out a chat app.
  • What type of database, if any, would you use for it?
  • What challenges would that architecture face as you scale up?
  • To help you prepare, here are examples of questions recruiters may ask during a Java interview.

    Q5 What Is The Difference Between Abstract Classes And Interfaces

    Abstract Class Interfaces
    An abstract class can provide complete, default code and/or just the details that have to be overridden An interface cannot provide any code at all, just the signature
    In the case of an abstract class, a class may extend only one abstract class A Class may implement several interfaces
    An abstract class can have non-abstract methods All methods of an Interface are abstract
    An abstract class can have instance variables An Interface cannot have instance variables
    An abstract class can have any visibility: public, private, protected An Interface visibility must be public none
    If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method
    An abstract class can contain constructors An Interface cannot contain constructors
    Abstract classes are fast Interfaces are slow as it requires extra indirection to find the corresponding method in the actual class

    Q6. What is inheritance in Java?

    Inheritance in Java is the concept where the properties of one class can be inherited by the other. It helps to reuse the code and establish a relationship between different classes. Inheritance is performed between two types of classes:

    Read Also: Watch Interview With The Vampire Online Free

    Preserve Immutability Of Objects

    Youre given the snippet below. And youre asked to create the newHeroes object so that the original hero object doesnt get changed, which is currently getting changed after creating the newHeroes object.

    To fix this you can follow the approach shown below, using both Object.assign or spread operator:

    Question 2: Count Number Of Occurrences Of Each Element In A Sorted Array

    Java Challenge #4: Switch Case

    Given a Sorted Array of integers containing duplicates. Find the frequency of every unique element present in the array.Frequency is defined as the number of occurrence of any element in the array.

    For example :

    intarr= Output:Frequency of1is:3Frequency of3is:2Frequency of4is:1Frequency of5is:2Frequency of6is:2

    Solution :

    Read Also: How To Give A Technical Interview

    Function Inside If Condition Statement

    You might have using if condition on your code for a long time. You might also have introduction with eval keyword, which is not recommended to use on your code for some reason. But do you know If condition statement evaluate using eval. So the following code will output 1undefined.

    Let me explain why. The following code is equivalent to the above code.

    eval ) which return function f which is true so inside if statement code execute. typeof f return undefined because if statement code execute at run time, so statement inside if condition evaluated at run time. I hope you get it. Check the fixed snippet below:

    What Are Constructors In Java

    Constructors refer to code that is used to initialize an object’s state in Java. Employers ask this question to determine whether you have an understanding of the basics of the programming language. Other questions such as, ‘Are there copy constructors in Java?’ and, ‘What is constructor chaining?’ are variations of the question.

    Example answer:”A constructor initializes a newly created object. Java supports copy constructor, but you have to write your own code to do it. Constructor chaining is calling a constructor from another constructor. However, you cannot call a sub-class constructor using a super-class constructor.”

    Recommended Reading: What Questions To Ask In An Interview At The End

    Q1 What Is Polymorphism

    Polymorphism is briefly described as one interface, many implementations. Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts specifically, to allow an entity such as a variable, a function, or an object to have more than one form. There are two types of polymorphism:

  • Compile time polymorphism
  • Run time polymorphism
  • Compile time polymorphism is method overloading whereas Runtime time polymorphism is done using inheritance and interface.

    Q2 What Is Runtime Polymorphism Or Dynamic Method Dispatch

    Java Interview Coding Challenge #1: FizzBuzz

    In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. Lets take a look at the example below to understand it better.

    class Car }class Audi extends Car public static void main}

    Read Also: How To Have A Great Phone Interview

    Q1 What Is The Difference Between Error And Exception

    An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors you cannot repair them at runtime. Though error can be caught in the catch block but the execution of application will come to a halt and is not recoverable.

    While exceptions are conditions that occur because of bad input or human error etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving the user feedback for entering proper values etc.

    What Type Of Database If Any Would You Use For It

    For this question, candidates would have to think through how a chat app works and the types of data such an application may need to store. The form of the data being stored, the way it is collected and how often it is accessed all have to do with the type of database to use. For instance, chat apps may need to store chat histories, user profiles, images or videos these different formats can all affect the type of database that works best.

    Read Also: How To Interview A Real Estate Agent

    Top 50 Java Programming Interview Questions

    While we believe that this content benefits our community, we have not yet thoroughly reviewed it.If you have any suggestions for improvements, please let us know by clicking theâreport an issueâ button at the bottom of the tutorial.

    Java Programming Interview Questions are always the deciding factor in any Java interview. Whether you are a beginner in Java or an expert programmer, you will be tested for your coding skills in the interview. So, itâs a good idea to brush up your coding skills before you face the interview.

    Reviews From The Previous Class

    Javastudypoint : Javastudypoint Java Interview Point Java Tutorial For ...
  • Rated 5 out of 5

    Iryna B

    I highly recommend this course! Dima is great instructor. He explains very well. He helped me a lot with coding challenges. Constantly in touch with students and very responsive. Thanks again Dima for your course!

  • Rated 5 out of 5

    Larissa O

    I am very glad that I took this course! Dmitry is a wonderful instructor: passionate and knowledgeable about Java, patient with students, responsive and prompt to questions in between sessions. I wish I knew about his instructions before, I would have loved to take a “Java, introduction to basics” course as well with Dmitry. I highly recommend this course to get you started in Java coding challenges!

  • Rated 5 out of 5

    Nastia S

    Dmitry is an excellent mentor with a very easy to follow teaching technique. This course will introduce you to a more professional way of solving coding challenges and will give you a deeper understanding of complex Java concepts.Highly recommend!

  • Recommended Reading: How To Pass Google Interview

    Q5 Explain The Role Of Dispatcherservlet And Contextloaderlistener

    DispatcherServlet is basically the front controller in the Spring MVC application as it loads the spring bean configuration file and initializes all the beans that have been configured. If annotations are enabled, it also scans the packages to configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.

    ContextLoaderListener, on the other hand, is the listener to start up and shut down the WebApplicationContext in Spring root. Some of its important functions includes tying up the lifecycle of Application Context to the lifecycle of the ServletContext and automating the creation of ApplicationContext.

    Q44 What Is A Map In Java

    In Java, Map is an interface of Util package which maps unique keys to values. The Map interface is not a subset of the main Collection interface and thus it behaves little different from the other collection types. Below are a few of the characteristics of Map interface:

  • Map doesnt contain duplicate keys.
  • Each key can map at max one value.

  • Also Check: Accounts Payable Associate Interview Questions

    What Challenges Would That Architecture Face As You Scale Up

    Candidates should be able to talk about what happens to the design as more users begin using the chat app platform. They should be able to reason through the pain points that will emerge and where the software should be expected to see strain. Hiring managers may ask about what happens when the number of concurrent users on the platform exceeds a thousand or a million. For example, are there better ways the code should be structured to accommodate for that?

    Q11 Name The Types Of Transaction Management That Spring Supports

    Implement a Stack – Java Interview Coding Challenge #4 [Java Brains]

    Two types of transaction management are supported by Spring. They are:

  • Programmatic transaction management: In this, the transaction is managed with the help of programming. It provides you extreme flexibility, but it is very difficult to maintain.
  • In this, transaction management is separated from the business code. Only annotations or XML based configurations are used to manage the transactions.
  • Apart from these Core Java interview questions for experienced professionals, if you want to get trained by professionals on this technology, you can opt for a structured training from edureka!

    Don’t Miss: What To Expect In A Second Interview

    Q7 Can You Explain The Java Thread Lifecycle

    The java thread lifecycle has the following states-

    New-

    When a thread is created, and before the program starts the thread, it is in the new state. It is also referred to as a born thread.

    Runnable

    When a thread is started, it is in the Runnable state. In this state, the thread is executing its task.

    Waiting

    Sometimes, a thread goes to the waiting state, where it remains idle because another thread is executing. When the other thread has finished, the waiting thread again comes into the running state.

    Timed Waiting

    In timed waiting, the thread goes to waiting state. But, it remains in waiting state for only a specified interval of time after which it starts executing.It remains waiting either till the time interval ends or till the other thread has finished.

    Terminated

    A thread is said to be in this state once it terminates. It may be because the thread has completed its task or due to any other reason.

    Scaffold Out The Architecture You Would Need To Build Out A Chat App

    This question is similar to the one given to the junior candidate. In this case, instead of mapping out a car rental company, the task is to whiteboard the architecture for a chat app service. Candidates arent expected to go into granular detail on all aspects of the app. Rather, focus on including the most important features like whether there needs to be data storage, how to send notifications and how to manage users when they are offline and online. Be sure to talk through your design process so the hiring manager can answer questions and give feedback along the way.

    You May Like: Microservice Design Patterns Interview Questions

    Q8 What Is Method Overloading And Method Overriding

    Method Overloading :

    • In Method Overloading, Methods of the same class shares the same name but each method must have a different number of parameters or parameters having different types and order.
    • Method Overloading is to add or extend more to the methods behavior.
    • It is a compile-time polymorphism.
    • The methods must have a different signature.
    • It may or may not need inheritance in Method Overloading.

    Lets take a look at the example below to understand it better.

    class Adder Static double addpublic static void main}

    Method Overriding:

    • In Method Overriding, the subclass has the same method with the same name and exactly the same number and type of parameters and same return type as a superclass.
    • Method Overriding is to Change existing behavior of the method.
    • It is a run time polymorphism.
    • The methods must have the same signature.
    • It always requires inheritance in Method Overriding.

    Lets take a look at the example below to understand it better.

    class Car Class Audi extends Carpublic static void main}

    Q13 What Do You Mean By Aggregation

    Java Challenge #6: Thread Start

    An aggregation is a specialized form of Association where all object has their own lifecycle but there is ownership and child object can not belong to another parent object. Lets take an example of Department and teacher. A single teacher can not belong to multiple departments, but if we delete the department teacher object will not destroy.

    Read Also: It Project Manager Interview Questions

    Soft Skills Questions For Java Developers

    Answering interview questions is about showcasing the skills you have already built up as a software developer.

    They create a space for job candidates to talk about both the technical and interpersonal side of their skillset. Developers should be able to discuss individual proficiencies as well as go over examples of how theyve practically applied them.

    Here are three examples of questions java developers might be asked about their soft skills.

    Career Experience Questions For Java Developers

    Stefanie Stewart, talent acquisition manager at SaaS company Kareo, said candidates arent graded on how they answer any single question. Instead, hiring managers consider all their interactions while candidates work through problems.

    Its one of those things thats evaluated through the process, Stewart told Built In in January 2022.

    Here are three example questions focused on past Java development experience.

    Read Also: How To Do A Group Interview

    Write A Code To Show Nullpointerexception

    If we are calling a function on the ânullâ, it will throw NullPointerException.

    public static void main static void printString}

    Thatâs why itâs better to have null check in place for early validation.

    static void printString}

    We can also throw IllegalArgumentException based on the project requirements.

    Q15 What Is Synchronization

    Design a Hashset – LeetCode Interview Coding Challenge [Java Brains]

    Synchronization refers to multi-threading. A synchronized block of code can be executed by only one thread at a time. As Java supports execution of multiple threads, two or more threads may access the same fields or objects. Synchronization is a process which keeps all concurrent threads in execution to be in sync. Synchronization avoids memory consistency errors caused due to inconsistent view of shared memory. When a method is declared as synchronized the thread holds the monitor for that methods object. If another thread is executing the synchronized method the thread is blocked until that thread releases the monitor.

    Also Check: What Happens In A Second Interview

    What Are The Advantages Of Hibernate Over Jdbc

    Some of the important advantages of Hibernate framework over JDBC are:

  • Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks cleaner and readable.
  • Hibernate supports inheritance, associations, and collections. These features are not present with JDBC API.
  • Hibernate implicitly provides transaction management, in fact, most of the queries cant be executed outside transaction. In JDBC API, we need to write code for transaction management using commit and rollback.
  • JDBC API throws SQLException that is a checked exception, so we need to write a lot of try-catch block code. Most of the times its redundant in every JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throw JDBCException or HibernateException un-checked exception, so we dont need to write code to handle it. Hibernate built-in transaction management removes the usage of try-catch blocks.
  • Hibernate Query Language is more object-oriented and close to Java programming language. For JDBC, we need to write native SQL queries.
  • Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
  • Hibernate provides option through which we can create database tables too, for JDBC tables must exist in the database.
  • Hibernate supports JPA annotations, so the code is independent of the implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.
  • Check If Two Arrays Contains Same Elements

    We will first create a set of elements from both the arrays. Then compare the elements in these sets to find if there is an element that is not present in both the sets?

    package com.journaldev.programminginterviews import java.util.Arrays import java.util.HashSet import java.util.Set public class ArraySameElements  Integer a2 =  Integer a3 =  System.out.println) System.out.println) }static boolean sameElements return true }}

    Read Also: How To Prepare For A Virtual Interview

    + Java Interview Questions For 2 To 3 Years Experienced Programmers

    So, without wasting any more of your time, here is my list of some of the frequently asked Core Java Interview Questions for beginner programmers. This list focuses on beginners and less experienced devs, like someone with 2 to 3 years of experience in Java.

    1) How does Java achieve platform independence? hint: bytecode and Java Virtual Machine

    2) What is ClassLoader in Java? hint: part of JVM that loads bytecodes for classes. You can write your own.

    3) Write a Java program to check if a number is Even or Odd? hint: you can use bitwise operator, like bitwise AND, remember, even the number has zero at the end in binary format and an odd number has 1 in the end.

    4) Difference between ArrayList and HashSet in Java? hint: all differences between List and Set are applicable here, e.g. ordering, duplicates, random search, etc. See Java Fundamentals: Collections by Richard Warburton to learn more about ArrayList, HashSet and other important Collections in Java.

    5) What is double checked locking in Singleton? hint: two-time check whether instances is initialized or not, first without locking and second with locking.

    6) How do you create thread-safe Singleton in Java? hint: many ways, like using Enum or by using double-checked locking pattern or using a nested static class.

    7) When to use the volatile variable in Java? hint: when you need to instruct the JVM that a variable can be modified by multiple threads and give hint to JVM that does not cache its value.

    More articles

    Popular Articles