• 800+ Interview Q&As

Learn by categories …

  • Why java-success.com?
  • What are the benefits?
  • PDF downloads
  • Privacy Policy
  • Top 50 posts last 7 days
  • Membership Levels
  • Membership Billing
  • Membership Checkout
  • Membership Invoice
  • Membership Account
  • Membership Cancel
  • 100+ Free Java Interview Q&As
  • 100+ Free Big Data Interview Q&As
  • Your - Resume writing skills
  • Your - Resume samples
  • Your - Self-taught success?
  • Your - Feeling stagnated?
  • Your - Earning more?
  • Your - Freelancing
  • Your - Job offers 2-6?
  • Your - Certification
  • Your - Job hunting tips
  • Your - Soft skills
  • Your - Blogging benefits
  • Your - Job interviews
  • Your - Lack of motivation?
  • Your - Philosophies
  • Your - Rants

18 Java scenarios based interview Q&As for the experienced – Part 1

Let’s look at scenarios or problem statements & how would you go about handling those scenarios in Java. These scenarios interview questions will judge your Java experience. Full list of Java scenarios based interview questions are covered at Judging your Java experience via scenarios based interview Q&As .

#1. Caching

Q01.Scenario : You need to load stock exchange security codes with price from a database and cache them for performance. The security codes need to be refreshed say every 30 minutes. This cached data needs to be populated and refreshed by a single writer thread and read by several reader threads. How will you ensure that your read/write solution is scalable and thread safe?

Cache for read performance

Cache for read performance

A01. Solution : There are a number of options as described below:

Option 1 : The java.util.concurrent.locks package provides classes that implement read/write locks where the read lock can be executed in parallel by multiple threads and the write lock can be held by only a single thread. The ReadWriteLock interface maintains a pair of associated locks, one for read-only and one for writing. The readLock( ) may be held simultaneously by multiple reader threads, while the writeLock( ) is exclusive. In general, this implementation improves performance and scalability when compared to the mutex locks (i.e. via synchronized key word) when

1. There are more reads and read duration compared to writes and write duration .

2. It also depends on the machine you are running on — for example, multi-core processors for better parallelism .

java.math.BigDecimal; java.util.HashMap; java.util.Map; java.util.concurrent.ExecutorService; java.util.concurrent.Executors; java.util.concurrent.TimeUnit; java.util.concurrent.locks.ReadWriteLock; java.util.concurrent.locks.ReentrantReadWriteLock; class MyApp { public static void main(String[] args) throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(2); Map<String, BigDecimal> map = new HashMap<>(); ReadWriteLock lock = new ReentrantReadWriteLock(); executor.submit(() -> { lock.writeLock().lock(); System.out.println("Writing ....." ); try { try { TimeUnit.SECONDS.sleep(3); //emulating update } catch (Exception e) { e.printStackTrace(); } map.put("stock-ABC", BigDecimal.valueOf(12.35)); } finally { lock.writeLock().unlock(); } }); Runnable readTask = () -> { lock.readLock().lock(); try { System.out.println("Reading ....." + map.get("stock-ABC")); try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) { e.printStackTrace(); } } finally { lock.readLock().unlock(); } }; //multiple reads executor.submit(readTask); executor.submit(readTask); //...............other code. As it keeps running. //executor.shutdown(); }
..... .....12.35 .....12.35

Here is another approach step by step: Simple caching Java application step by step

Option 2 : The ConcurrentHashmap is another example where improved performance can be achieved when you have more reads than writes . The ConcurrentHashmap allows concurrent reads and locks only the buckets that are used for modification or insertion of data.

<String, BigDecimal> map = new ConcurrentHashMap<>(); .put("stock-ABC", BigDecimal.valueOf(12.35));

Option 3 : Making use of caching frameworks like EHCache , OSCache , etc. Caching frameworks take care of better memory management with LRU (Least Recently Used) and FIFO(First In First Out) eviction strategies, disk overflow, data expiration and many other optional advanced features, as opposed to writing your own.

Here is a working example in Java to Implement an in-memory LRU cache in Java with TTL without using a framework like EHCache.

Option 4 : Using a distributed & an in memory database like Redis . Redis can be a choice for implementing a highly available in-memory cache to decrease data access latency, increase throughput, and ease the load off your relational or NoSQL database and application.

#2. Asynchronus processing

Q02. Scenario : If you have a requirement to generate online reports or feed files by pulling out millions of historical records from a database, what questions will you ask, and how will you go about designing it?

A02. Designing a system is all about asking the right questions to gather requirements.

— Online Vs Offline? Should we restrict the online reports for only last 12 months of data to minimise the report size and to get better performance, and provide reports/feeds for the data older than 12 months via offline processing? For example, Bank statements for last 12 months via online & for transactions older than 12 months via offline asynchronous processing without blocking the customer from browsing rest of the website. Reports can be generated asynchronously and once ready can be emailed or downloaded via a URL at a later time.

— What report generation framework to use like Jasper Reports , Open CSV , XSL-FO with Apache FOP , etc depending on the required output formats?

— How to handle exceptional scenarios? send an error email, use a monitoring system like Tivoli or Nagios to raise production support tickets on failures, etc?

— Security requirements. Are we sending feed/report with PII (i.e. Personally Identifiable Information) data via email? Do we need proper access control to restrict who can generate which online reports? Should we password protect the email attachments? Are there any compliance or regulatory requirements like PCI (i.e. Payment Card Industry), GDPR (i.e. General Data Protection Regulation), ACCC (i.e. Australian Competition and Consumer Commission), etc depending on the jurisdictions served by the application?

— Should we schedule the offline reports to run during off peak time ? For example, enter all the requests for a report into a “ Request ” table and then schedule a process to run at say midnight to refer to all pending requests in the “ Request ” table to generate and store the relevant reports in an outbox for the customers to download. An email can be sent to clients with the report URL to download the report.

— Archival and purging straggles of the historical reports. What is the report retention period for the requirements relating to auditing and compliance purpose? How big are the files?

Solution : An online application with a requirement to produce time consuming reports or a business process (e.g. re-balancing accounts, aggregating hierarchical information, etc) could benefit from making these long running operations asynchronous. Once the reports or the long running business process is completed, the outcome can be communicated to the user via emails or asynchronously refreshing the web page via techniques known as “ server push (JEE Async Servlet)” or “ client pull (Refresh meta tag)”. A typical example would be

a) A user makes an online request for an aggregate report or a business process like re-balancing his/her portfolios.

b) The user request will be saved to a database table for a separate process to periodically pick it up and process it asynchronously.

c) The user could now continue to perform other functionality of the website without being blocked .

d) A separate process running on the same machine or different machine can periodically scan the table for any entries and produce the necessary reports or execute the relevant business process. This could be a scheduled job that runs once during off-peak or every 10 minutes. This depends on the business requirement.

e) Once the report or the process is completed, notify the user via emails or making the report available online to be downloaded.

Offline report generation on AWS cloud

Offline report generation on AWS cloud

#3 Regular Expressions (i.e. regex)

Q03. Scenario : You need to find and change a text from “Client” to “Customer” in 300+ html files.

A03. Solution : Harness the power of Unix & Regex .

file in $(grep -il "Client" *.html) sed -e "s/Client/Customer/ig" $file > /tmp/tempfile.tmp mv /tmp/tempfile.tmp $file

sed and awk are very powerful Unix commands for file manipulations. These are covered in detail in The Unix interview Q&As .

#4 Auditing

Q04. Scenario : You have a requirement to maintain a history of insertion, modification, and deletion to the “Customer” table. How will you go about accomplishing this?

A04. Solution

1) Create an ETL (i.e. Extract Transform & Load) batch job that periodically extracts all the changes to batch files and send those files to a Data warehouse system, which loads these batch files to a SCD Type 2 history table. SCD Type 2 means maintain each change. This is discussed in detail at 13 Data Warehouse interview Q&As – Fact Vs Dimension, CDC, SCD, etc .

2) Asynchronously via publish & subscription paradigm. Publish each change as an event to a message oriented middle-ware like Apache Kafka, Rabbit MQ, Websphere MQ, etc & separate subscriber application will save each event to a SQL or NoSQL history table.

3) Create database table triggers to insert superseded records to a separate history table. A database trigger is procedural code that is automatically executed in response to certain events like insert, update, etc on a particular table or view in a database. Care must be taken in using or writing triggers as incorrectly written or used triggers can significantly impact performance of your database.

#5 Externalize business rules

Q05. Scenario : You are asked to design an application, which validates data with 100+ rules to comply with the government compliance requirements and tax laws. These compliance requirements can change and the application need to quickly and easily adapt to changing requirements.

A05. Solution : Harness the power of Rules Engines like Drools . Drools is a popular open source business rules and work flow engine. It helps you externalise the rules in database tables or excel spreadsheets as opposed to embedding within the Java code. The rules are executed in the form of when given a ($condition) then execute the ($consequence). The business will be the custodian of these rules that can be easily viewed on an excel spreadsheet or via querying the database tables. A GUI could be built to maintain these rules that reside in a database.

#6 Concurrency Management

Q06. Scenario : Reference counting where a shared resource is incremented or decremented. The increment/decrement operations must be thread safe. For example, a counter that keeps track of the number of active logged in users by incrementing the count when users log in and decrementing the count when the users log out. Sometimes you want to allow a finite number of concurrent accesses say 3 users at a time.

A06. Solution :

Mutex : is a single key to an object (E.g. a toilet). One person can have the key and occupy the toilet at the time. When finished, the person gives (or releases) the key to the next person in the queue. In Java, every object has a mutex and only a single thread can get hold of a mutex .

Semaphore : Is a number of free identical toilet keys. For example, having 3 toilets with identical locks and keys. The semaphore count is set to 3 at beginning and then the count is decremented as people are acquiring the key to the toilets. If all toilets are full, i.e. there are no free keys left, the semaphore count is 0. Now, when one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.

java.util.concurrent.ExecutorService; java.util.concurrent.Executors; java.util.concurrent.Semaphore; java.util.concurrent.TimeUnit; java.util.stream.IntStream; class MyApp { public static void main(String[] args) throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(10); Semaphore semaphore = new Semaphore(3); Runnable longRunningTask = () -> { boolean permit = false; try { permit = semaphore.tryAcquire(6, TimeUnit.SECONDS); if (permit) { System.out.println("Semaphore is acquired"); TimeUnit.SECONDS.sleep(3); } else { System.out.println("Could not acquire semaphore"); } } catch (InterruptedException e) { throw new IllegalStateException(e); } finally { if (permit) { semaphore.release(); } } }; IntStream.range(0, 10).forEach(i -> executor.submit(longRunningTask)); //Some other code as it keeps running //executor.shutdown(); }
is acquired is acquired is acquired is acquired is acquired is acquired is acquired is acquired is acquired not acquire semaphore

#7 Designing a trading system

Q07. Scenario : If you are working with an online trading application, you may want the functionality to queue trades placed after hours and process them when the stock market opens. You also need to asynchronously handle the order statuses sent from the stock exchange like partially-filled, rejected, fully filled, etc, and update the online order information. How will you go about solution this?

A07. Solution : The Message Oriented Middle-wares like Apache Kafka, Rabbit MQ, Websphere MQ, webMethods Broker, etc provide features like guaranteed delivery with store-and-forward mechanism, no duplicates, and transaction management for enterprise level program-to-program communications by sending and receiving messages asynchronously (or synchronously). The diagram below gives a big picture.

Screen shot 2014-08-31 at 11.14.08 AM

When using Message Oriented Middle-wares (MOM) to facilitate asynchronous processing

1) The producer (i.e Trading Engine) that submits user requests and consumer (i.e. FIX Router) that converts the messages to FIX protocol and send FIX messages to the Stock Exchange system retain processing control and do not block. In other words, they continue processing regardless of the state of others. Queue depths need to be properly set, and the messages need to be durable . Message correlation ids are used to pair request and response.

2) MOM creates looser coupling among systems, provides delivery guarantees, prevents message losses, scales well by decoupling performance characteristics of each system, has high availability and does not require same time availability of all sub-systems. So, MOM is ideal for geographically dispersed systems requiring flexibility, scalability, and reliability.

3) You may also require to perform logging, auditing and performance metrics gathering asynchronously and non-intrusively. For example, you could send the log messages from log4j to a queue to be processed later asynchronously by a separate process running on the same machine or a separate machine. The performance metrics can be processed asynchronously as well.

For example, a trading application may have a number of synchronous and asynchronous moving parts and metrics needs to be recorded for various operations like placing a trade on to a queue, receiving asynchronous responses from the stock market, correlating order ids, linking similar order ids, etc. A custom metrics gathering solution can be accomplished by logging the relevant metrics to a database and then running relevant aggregate queries or writing to a file system and then running PERL based text searches to aggregate the results to a “csv” based file to be opened and analyzed in a spreadsheet with graphs. In my view, writing to a database provides a greater flexibility. For example, in Java, the following approach can be used.

Asynchronous logging

Asynchronous logging

— Use log4j JMS appender or a custom JMS appender to send log messages to a queue.

— Use this appender in your application via Aspect Oriented Programming (AOP – e.g Spring AOP, AspectJ, etc) or dynamic proxy classes to non-intrusively log relevant metrics to a queue. It is worth looking at Perf4j and context based logging with MDC (Mapped Diagnostic Contexts) or NDC (Nested Diagnostic Contexts) to log on a per thread basis to correlate or link relevant operations.

— A stand-alone listener application needs to be developed to dequeue the performance metrics messages from the queue and write to a database or a file system for further analysis and reporting purpose. This listener could be written in Java as a JMX service using JMS or via broker service like webMethods, TIBCO, etc.

— Finally, relevant SQL or regular expression based queries can be written to aggregate and report relevant metrics in a customized way.

#8 Impact Analysis (aka IA)

Q08. Scenario : You are required to change the logic of a module that many other modules have dependency on. How would you go about making the changes without impacting dependent systems.

A08. Solution : You need to firstly perform an impact analysis . Impact analysis is about being able to tell which pieces of code, packages, modules, and projects use given piece of code, packages, modules, and projects, or vice versa is a very difficult thing.

Performing an impact analysis is not a trivial task, and there is not a single tool that can cater for every scenario. You can make use of some static analysis tools like IDEs (e.g. eclipse), JRipples , X- Ray , etc. But, unfortunately applying just static analysis alone not enough, especially in Java and other modern languages whereas lots of things can happen in run time via reflections, dynamic class loading & configuration, polymorphism, byte code injection, proxies, etc.

a) In eclipse Ctrl+Shift+g c an be used to search for references

b) You can perform a general “File Search” for keywords on all projects in the work-space.

c) You can use Notepad++ editor and select Search –> Find in files. You can search for a URL or any keyword across a number of files within a folder.

There are instances where you need to perform impact analysis across stored procedures, various services, URLs, environment properties, batch processes, etc. This will require a wider analysis across projects and repositories.

Search within your code repository like GIT :

rev-list --all | ( while read revision; do git grep -F 'password' $revision done

Tools like FishEye can be used to search across various code repositories. FisheEye is not targeted for any special programming language. It just supports various version control systems and the concept of text files being changed over time by various people. Handy for text searches like environment based properties files to change a URL or host name from A to B.

Grep the Unix/Linux environment where your application is deployed.You can perform a search on the file system where your application(s) are deployed.

Analyze across various log files . It is also not easy to monitor service oriented architectures. You can use tools like Splunk to trace transactions across the IT stack while being tested by the testers to proactively identify any issues related to change. Splunk goes across multiple log files.

Conduct impact analysis sessions across cross functional and system teams and communicate the changes . Brain storm major areas affected and document them. Have a manual test plan that covers the impact systems to be tested. Collaborate with cross functional teams and identify any gaps in your analysis. Have a proper review and sign-off process. Get more developers to do peer code reviews.

Have proper documentation with high level architecture diagrams and dependency graphs where possible . As the number systems grow, so does the complexity. A typical enterprise Java application makes use of different database servers, messaging servers, ERP systems, BPM systems, Work flow systems, SOA architectures, etc. Use online document management systems like Confluence or Wiki , which enables search for various documents.

More Java scenarios based interview Q&As

Q09 to Q18: 18 Java scenarios based interview Q&As for the experienced – Part 2

100+ Judging your Java experience

100+ Java scenarios based interview questions & answers .

Java Developer & Architect Q&As

Big data engineer & architect q&as, 16+ key areas & 13+ techs to fast-track, 800+ enterprise & core java q&as, java & big data tutorials, prepare to fast-track & go places.

Don't be overwhelmed by the number of questions as the technology stacks are so vast. The quality of the answers you provide to some of the key technical & open-ended questions along with your soft skills & attitude will go a long way in getting the job offers.

Popular posts:

  • 00: Top 50+ Core Java interview questions & answers for 1 to 3 years experience (3,330)
  • Java 8 String streams and finding the first non repeated character with functional programming (2,769)
  • 18 Java scenarios based interview Q&As for the experienced – Part 1 (2,413)
  • 800+ Java Interview Questions & Answers for 2 to 5 and 5 to 10+ years of experience… (2,219)
  • 01: 30+ Java architect interview questions & answers – Part 1 (745)
  • 02: 10 Java String class interview Q&As (559)
  • 30+ Java Code Review Checklist Items (548)
  • Membership Levels (473)
  • 500+ Big Data Interview Questions & Answers for 2 to 5 and 5 to 10+ years of experience… (464)
  • Loading a YAML or JSON file with Jackson into a Map & flatten it (348)
  • Latest Posts

Arulkumaran Kumaraswamipillai

  • 500+ Big Data Interview Questions & Answers for 2 to 5 and 5 to 10+ years of experience & architects - July 4, 2024
  • 800+ Java Interview Questions & Answers for 2 to 5 and 5 to 10+ years of experience &architects - July 4, 2024
  • 22: PySpark Row object Interview Q&As with tutorials - July 4, 2024

Insert/edit link

Enter the destination URL

Or link to existing content

Java Gently, Third Edition by Judith Bishop

Get full access to Java Gently, Third Edition and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

List of Examples and Case Studies

Get Java Gently, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

case study questions in java

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

Here are 41 public repositories matching this topic...

Dare-marvel / big-data-analytics--bda--.

💾 Welcome to the Big Data Analytics Repository! 📚✨ Immerse yourself in a carefully curated reservoir of knowledge on Big Data Analytics. 🌐💡 Explore the intricacies of deriving insights from vast datasets and navigating powerful analytics tools. 🚀🔍

  • Updated May 31, 2024

ManasMalla / PayPal-Clone-CaseStudy

PayPal (Payment Management System): A simple payment management system, inspired by PayPal, in the exact language in which the fin-tech giant started out.

  • Updated Apr 1, 2024

KeYProject / ips4o-verify

Case Study of the Verification of In-Place Parallel Super Scalar Samplesort Algorithm in Java

  • Updated Dec 30, 2023

vinimrs / spring-boot-clean-architecture

An analysis of a clean architecture implementation in a spring boot application.

  • Updated Nov 7, 2023

tugsef / word-search-java

Algorithm testing

  • Updated Oct 10, 2023

mobile-hcmus / TikTokCloneProject

TopTop - A native TikTok Clone Android App built with Java

  • Updated Oct 8, 2023


Fitur: verifikasi id 5 digit dengan total bilangan lebih dari 25 , beberapa pilihan dengan operator Switch Case dan if ,else , dan library buku yang bisa ditambahkan dengan template yang sudah ada.

  • Updated Sep 20, 2023

KeYProject / rbtree-verification

A Java implementation of red-black trees, verified with KeY.

  • Updated Sep 11, 2023

decimozs / verdant-vibes

A plant-focused e-commerce desktop application was created using Java, Java Swing, JUnit testing, and local database tailored specifically for plant-related enterprises.

  • Updated Jun 20, 2023

KeYProject / DualPivotQuickSort

  • Updated Jun 13, 2023

KeYProject / TimSort

Resources of the TimmSort Case Study

AchyutaMohapatra / Employee-App

  • Updated Apr 4, 2023

ainzone / cs-inventory-management

This case study is specifically designed to provide valuable insights to second semester students pursuing Business Informatics at Pforzheim University.

  • Updated Mar 24, 2023

ghareeb-falazi / SCIP-CaseStudy-2

A case-study that shows how the Smart Contract Locator (SCL), the Smart Contract Description Language (SCDL), and the Smart Contract Invocation Protocol (SCIP) can be used in combination to support the integration of heterogeneous multi-blockchain setups into client applications.

  • Updated Mar 2, 2023

ohbus / retail-banking

Consumer Banking Application

  • Updated Sep 14, 2022

YusufDagdeviren / Akbank-Web3-Practicum

Akbank Web3 Practicum için yapmış olduğum OOP case

  • Updated Sep 9, 2022

OzerBey / FTTeknolojiPracticum

This repo contains case study of FtTechPracticum

  • Updated Sep 7, 2022

AhmetFurkanDEMIR / Boyner-Case-Study

Boyner Case Study

  • Updated Jun 21, 2022

algokelvin-373 / CaseStudyProgramming

This is All Case Study for Basic Programming ( Java, Kotlin, Python, HTML, JS, etc )

  • Updated Jun 9, 2022

championswimmer / low-level-design-problem

Case studies (with solution codes) for Low Level System Design problems

  • Updated May 7, 2022

Improve this page

Add a description, image, and links to the case-study topic page so that developers can more easily learn about it.

Curate this topic

Add this topic to your repo

To associate your repository with the case-study topic, visit your repo's landing page and select "manage topics."

Java Code Geeks

Java.io in nutshell: 22 case studies

Photo of Yifan Peng

This post attempts to cover a comprehensive set of operations in java.io . Compared with other books and blogs related to this topic, my motivation is to show “how-to” through case studies. As once a Java student, I realize the most effective way of learning a new program language is through examples: copy and paste a piece of codes, run it to see results, then try to modify and re-run it step-by-step. Therefore, I assume this post will be helpful.

It is worth noting that this post will not touch anything related to java.nio because I think it is quite a different topic.    

Table of Contents

Case 0: create a new file, case 1: two constants in file, case 2: delete a file, case 3: create a directory, case 4: list files and directories in a given directory, case 5: tests whether a file is a file, case 6: write to a randomaccessfile, case 7: write bytes to a file, case 8: append bytes to a file, case 9: read bytes from a file, case 10: copy files, case 11: write chars to a file, case 12: read chars from a file, case 13: convert from outputstream to filewriter, case 14: convert from inputstream to filereader, case 15: use pipeline, case 16: write formatted string to a file, case 17: redirect the “standard” io, case 18: read a file line by line, case 19: compress to a zip file, case 20: extract from a zip file, case 21: push back bytes.

Output: a new and empty file is created in the working directory, iff there is no “helloword.txt” before.

I get the above output because I am working on Linux. If you use Windows, the output should be \ and ; . As can be seen, for the purpose of portability and robustness, it should always be recommended to use these two constants.

Output: I am using Eclipse

File . list() returns an array of strings. If you prefer an array of File s, please use File . listFiles() :

Combined with File . listFiles() , we can list all files in the given directory and its sub-directories.

Output: compared with Case 4 to see the difference

If you open the file using text editor, you will find garbled code except the first hello world!A (kindly note the char A at the end of “hello world!”). This is because RandomAccessFile only writes an array of bytes in the file.

This time you can see “hello world!” in the file. Of course you can write to an OutputStream byte by byte, but it is less effective:

Output: hello world!hello world!

The InputStream . read() will return -1 if it reaches the end of the file. Otherwise, it will return the total number of bytes read into the buffer.

Simply combine Case 7 and 9 , we will get the copy function.

For the above case, you will get the same result as in Case 7 . So what is the difference? FileWriter is meant for writing streams of characters. It will use the default character encoding and the default byte-buffer size. In other words, it is a wrapper class of FileOutputStream for convenience. Therefore, to specify these values yourself, consider using a FileOutputStream .

Whether to use streams of bytes or characters? It really depends. Both have buffers. InputStream/OutputStream provide more flexibility, but will make your “simple” program complex. On the other hand, FileWriter/FileReader give a neat solution but you lose the control.

Instead of using default character encoding, you can specify the charset. For example,

The following code creates two thread, a Producer which writes something into the pipeline at one end and a Consumer which reads it from the pipeline at the other end. To create a pipeline, we need to create PipedInputStream and PipedOutputStream seperately, and connect them using output.connect(input) or via their constructors. In this program, I intentionally start the Consumer thread first and ask the whole program to sleep 1 second before starting the Producer thread. This will show the pipeline DOES work. It is worthy noting that, I close the pipeline in the Producer because “ A thread that writes to a stream should always close the OutputStream before terminating. ” If we remove the out.close() line, an IOException will be thrown

PrintStream adds functionality to print representations of various data values conveniently. The format string syntax is almost same as C.

In Java, both standard and error output are PrintStream s. The standard input is InputStream . Therefore we can reassign them freely. The following code redirect the standard output to error output.

Output: In Eclipse, red text means error message

The above code creates a zip file and puts three files, named “helloworld0.txt”, “helloworld1.txt”, and “helloworld2.txt”, each of which contains the content “hello world!”.

The above code pushes a dot after reading a comma, therefore the output is

However, if you try to push more characters back such as push.unread("(...)".getBytes()); , you will get an IOException : Push back buffer is full. This is because the default size of the pushback buffer is 1. To specify it with larger capacity, use the constructor PushbackInputStream(InputStream in, int size) , such as

case study questions in java

We will contact you soon.

Photo of Yifan Peng

Related Articles

case study questions in java

Java 8 Streams – Group By Multiple Fields with Collectors.groupingBy()

Java program to calculate average using arrays, 150 java interview questions and answers – the ultimate list (pdf download & video), java 8 streams filter with multiple conditions examples, java arraylist insert/replace at index, switch as an expression in java with lambda-like syntax, 13 best java decompilers for download and online use for java developers, how to format/parse dates with localdatetime in java 8 – example tutorial.


This site uses Akismet to reduce spam. Learn how your comment data is processed .


I’m afraid to say that the guava library (especially com.google.common.io.Files) makes many of these redundant…


true. this post is mostly for beginners.


Nice collection of cases. But may I suggest to improve the examples to not lure beginners into thinking that a conversion between bytes and String is ok without excplicit encoding? This applies to String.getBytes(), as well as for all the constructors of Reader or Writer you use. Just yesterday we had to waste three hours for an encoding bug hunt where a Reader was opened without explicit encoding. It worked on Linux but not on Windows, because the default encoding is different. One further comment regarding IOExceptions. You define your main() methods as throwing an IOException. This gets you around …  Read more »

The Java Interview Prep Handbook – 50 Questions Solved + Code Examples

Vahe Aslanyan

If you're trying to get a job in big tech or you want to refine your skills in software development, a strong grasp of Java is indispensable.

Java is well-known for its robustness in Object-Oriented Programming (OOP), and it provides a comprehensive foundation essential for developers at every level.

This handbook offers a detailed pathway to help you excel in Java interviews. It focuses on delivering insights and techniques relevant to roles in esteemed big tech companies, ensuring you're well-prepared for the challenges ahead.

This guide serves as a comprehensive Java review tutorial, bridging the gap between foundational Java knowledge and the sophisticated expertise sought by industry leaders like Google. And it'll help you deepen your understanding and practical application of Java, preparing you for professional success in the tech industry.

Table of Contents

  • What is Java?
  • What's the difference between the JDK, JRE, and JVM?
  • How does the 'public static void main(String[] args)' method work?
  • What is bytecode in Java?
  • Differentiate between overloading and overriding
  • What is the Java ClassLoader?
  • Can we override static methods in Java?
  • How does the 'finally' block differ from the 'finalize' method in Java?
  • What is the difference between an abstract class and an interface?
  • Explain the concept of Java packages
  • What are Java annotations?
  • How does multi-threading work in Java?
  • Use throw to raise an exception
  • Use throws to declare exceptions
  • What is the significance of the transient keyword?
  • How do you ensure thread safety in Java?
  • Explain the Singleton pattern
  • What are Java Streams?
  • What are the primary differences between ArrayList and LinkedList?
  • How do HashSet, LinkedHashSet, and TreeSet differ?
  • Differentiate between HashMap and ConcurrentHashMap
  • Describe the contract between hashCode() and equals() methods
  • What is Java reflection?
  • How do you create a custom exception in Java?
  • What is the difference between a checked and unchecked exception?
  • What are generics? Why are they used?
  • Explain the concept of Java Lambda Expressions
  • What is the diamond problem in inheritance?
  • Describe the difference between fail-fast and fail-safe iterators
  • What is type erasure in Java generics?
  • Describe the differences between StringBuilder and StringBuffer
  • What is the volatile keyword in Java?
  • Explain the Java memory model
  • What is the purpose of the default keyword in interfaces?
  • How does switch differ in Java 7 and Java 8?
  • Explain the concept of Autoboxing and Unboxing
  • Describe the @FunctionalInterface annotation
  • How can you achieve immutability in Java?
  • What is the decorator pattern?
  • Explain the Java I/O streams
  • How does the garbage collector work in Java?
  • What are the benefits of using Java NIO?
  • Explain the Observer pattern
  • What is the purpose of Java's Optional?
  • Explain Java's try-with-resources
  • Explain the difference between C++ and Java
  • What is polymorphism? Provide an example
  • How can you avoid memory leaks in Java?
  • Explain the purpose of Java's synchronized block
  • Explain the concept of modules in Java


1. What is Java?

Java is a high-level, object-oriented programming language known for its platform independence. It allows developers to write code once and run it anywhere using the Java Virtual Machine (JVM).

2. What's the Difference between the JDK, JRE, and JVM?

  • JDK (Java Development Kit): This is a software package that provides developers with the tools and utilities necessary to develop, compile, and run Java applications.
  • JRE (Java Runtime Environment): A subset of the JDK, the JRE contains the essential components, including the JVM, to run Java applications but not to develop them.
  • JVM (Java Virtual Machine): An abstract computing machine, the JVM enables Java bytecode to be executed, providing the platform independence Java is known for.

3. How Does the public static void main(String[] args) Method Work?

This method is the entry point for Java applications. The public modifier means it's accessible from other classes, static denotes it's a class-level method, and void indicates it doesn't return any value. The argument String[] args allows command-line arguments to be passed to the application.

4. What is bytecode in Java?

Bytecode is an intermediate, platform-independent code that Java source code is compiled into. It is executed by the JVM, enabling the "write once, run anywhere" capability.

5. Differentiate between overloading and overriding

  • Overloading: This occurs when two or more methods in the same class share the same name but have different parameters. It's a compile-time concept.
  • Overriding: In this case, a subclass provides a specific implementation for a method already defined in its superclass. It's a runtime concept.


6. What is the Java ClassLoader?

The Java ClassLoader is a part of the JRE that dynamically loads Java classes into the JVM during runtime. It plays a crucial role in Java's runtime environment by extending the core Java classes.

7. Can We Override Static Methods in Java?

No, we cannot override static methods. While a subclass can declare a method with the same name as a static method in its superclass, this is considered method hiding, not overriding.

8. How Does the finally Block Differ from the finalize Method in Java?

Understanding the distinction between the finally block and the finalize method in Java is crucial for effective resource management and exception handling in your programs.

Finally Block:

  • Purpose and Usage: The finally block is a key component of Java's exception handling mechanism. It is used in conjunction with try-catch blocks.
  • Execution Guarantee: Regardless of whether an exception is thrown or caught within the try or catch blocks, the code within the finally block is always executed. This ensures that it runs even if there’s a return statement in the try or catch block.
  • Common Uses: It is typically utilized for cleaning up resources, such as closing file streams, database connections, or releasing any system resources that were acquired in the try block. This helps in preventing resource leaks.

Finalize Method:

  • Definition: The finalize method is a protected method of the Object class in Java. It acts as a final resort for objects garbage collection.
  • Garbage Collector Call: It is called by the garbage collector on an object when the garbage collector determines that there are no more references to the object. However, its execution is not guaranteed, and it's generally unpredictable when, or even if, the finalize method will be invoked.
  • Resource Release: The finalize method is designed to allow an object to clean up its resources before it is collected by the garbage collector. For example, it might be used to ensure that an open file owned by an object is closed.
  • Caution in Use: It's important to note that relying on finalize for resource cleanup is generally not recommended due to its unpredictability and potential impact on performance.

Access Modifiers in Java:

  • Private: This modifier makes a member accessible only within its own class. Other classes cannot access private members of a different class.
  • Default (no modifier): When no access modifier is specified, the member has package-level access. This means it is accessible to all classes within the same package.
  • Protected: A protected member is accessible within its own package and also in subclasses. This is often used in inheritance.
  • Public: Public members are accessible from any class in the Java program. It provides the widest level of access.

Understanding these distinctions and access levels is vital for effective Java programming, ensuring resource management, security, and encapsulation are handled appropriately in your software development endeavors.

9. What is the Difference between an Abstract Class and an Interface?

An abstract class in Java is used as a base for other classes. It can contain both abstract methods (without an implementation) and concrete methods (with an implementation).

Abstract classes can have member variables that can be inherited by subclasses. A class can extend only one abstract class due to Java's single inheritance property.

Example of an Abstract Class:

An interface in Java, on the other hand, is a completely "abstract class" that is used to group related methods with empty bodies.

From Java 8 onwards, interfaces can have default and static methods with a body. A class can implement any number of interfaces.

Example of an Interface:

Both abstract classes and interfaces are foundational concepts in Java, used for achieving abstraction and supporting design patterns like Strategy and Adapter. The use of these concepts depends on the specific requirements and design considerations of your software project.


10. Explain the Concept of Java Packages

Java packages are a way of organizing and structuring classes and interfaces in Java applications. They provide a means to group related code together. Packages help prevent naming conflicts, enhance code readability, and facilitate code reusability.

For example, consider a banking application. You might have packages like com.bank.accounts , com.bank.customers , and com.bank.transactions . These packages contain classes and interfaces specific to their respective functionalities.

In essence, Java packages are like directories or folders in a file system, organizing code and making it more manageable.

11. What are Java Annotations?

Java annotations are metadata that can be added to Java source code. They provide information about the code to the compiler or runtime environment. Annotations do not directly affect the program's functionality – instead, they convey instructions to tools or frameworks.

A common use of annotations is for marking classes or methods as belonging to a specific framework or for providing additional information to tools like code analyzers, build tools, or even custom code generators.

For example, the @Override annotation indicates that a method is intended to override a method from a superclass, helping catch coding errors during compilation. Another example is @Deprecated , which indicates that a method or class is no longer recommended for use.

12. How Does Multi-threading Work in Java?

Multi-threading in Java allows a program to execute multiple threads concurrently. Threads are lightweight processes within a program that can run independently. Java provides a rich set of APIs and built-in support for multi-threading.

Threads in Java are typically created by either extending the Thread class or implementing the Runnable interface. Once created, threads can be started using the start() method, causing them to run concurrently.

Java's multi-threading model ensures that threads share resources like memory and CPU time efficiently while providing mechanisms like synchronization and locks to control access to shared data.

Multi-threading is useful for tasks such as improving application responsiveness, utilizing multi-core processors, and handling concurrent operations, as often seen in server applications.

13. Use throw to Raise an Exception

In Java programming, the throw keyword is crucial for handling exceptions deliberately and responsively. This approach to exception management allows developers to enforce specific conditions in their code and maintain control over the program flow.

In this example, an IllegalArgumentException is thrown if the age parameter is less than 18. This method of raising an exception ensures that the program behaves predictably under defined conditions, enhancing both the security and reliability of the code.

14. Use throws to Declare Exceptions

The throws keyword in Java serves to declare that a method may cause an exception to be thrown. It signals to the method's caller that certain exceptions might arise, which should be either caught or further declared.

In this scenario, the readDocument method declares that it might throw a FileNotFoundException . This declaration requires the caller of this method to handle this exception, ensuring that appropriate measures are in place to deal with potential errors, and thus improving the robustness of the application.

Both throw and throws are integral to managing exceptions in Java. throw is used for actively raising an exception in the code, while throws declares possible exceptions that a method might produce, thereby mandating their handling by the caller. This distinction is essential for writing error-resistant and well-structured Java programs.


15. What is the Significance of the transient Keyword?

The transient keyword in Java is used to indicate that a field should not be serialized when an object of a class is converted to a byte stream (for example, when using Java Object Serialization).

This is significant when you have fields in a class that you do not want to include in the serialized form, perhaps because they are temporary, derived, or contain sensitive information.

16. How Do You Ensure Thread Safety in Java?

Thread safety in Java is achieved by synchronizing access to shared resources, ensuring that multiple threads can't simultaneously modify data in a way that leads to inconsistencies or errors.

You can ensure thread safety through synchronization mechanisms like synchronized blocks, using thread-safe data structures, or utilizing concurrent utilities from the java.util.concurrent package.

In the code above, we have a SharedCounter class with a synchronized increment method, ensuring that only one thread can increment the count variable at a time. This synchronization mechanism prevents data inconsistencies when multiple threads access and modify the shared count variable.

We create two threads ( thread1 and thread2 ) that concurrently increment the counter. By using synchronized methods or blocks, we guarantee thread safety, and the final count will be accurate, regardless of thread interleaving.

17. Explain the Singleton Pattern

The Singleton pattern is a design pattern that ensures a class has only one instance and provides a global point of access to that instance. It is achieved by making the constructor of the class private, creating a static method to provide a single point of access to the instance, and lazily initializing the instance when needed.

Implementation without Singleton:

Let's imagine a scenario where you want to establish a database connection. Without the Singleton pattern, every time you'd need a connection, you might end up creating a new one.

Now, imagine initializing this connection multiple times in different parts of your application:

For the above code, "Establishing a new database connection..." would be printed twice, implying two separate connections were created. This is redundant and can be resource-intensive.

Implementation with Singleton:

With the Singleton pattern, even if you attempt to get the connection multiple times, you'd be working with the same instance.

Initializing this connection multiple times:

For the above code, "Establishing a single database connection..." would be printed just once, even though we've called getInstance() twice.

18. What are Java Streams?

Java Streams are a powerful abstraction for processing sequences of elements, such as collections, arrays, or I/O channels, in a functional and declarative style. They provide methods for filtering, mapping, reducing, and performing various transformations on data.

Streams can significantly simplify code and improve readability when working with data collections.

19. What Are the Primary Differences between ArrayList and LinkedList?

ArrayList and LinkedList are both implementations of the List interface. The primary differences between them lie in their internal data structures.

ArrayList uses a dynamic array to store elements, offering fast random access but slower insertions and deletions. LinkedList uses a doubly-linked list, which provides efficient insertions and deletions but slower random access.


20. How do HashSet , LinkedHashSet , and TreeSet Differ?

  • HashSet stores elements in an unordered manner, offering constant-time complexity for basic operations.
  • LinkedHashSet maintains the order of insertion, providing ordered iteration of elements.
  • TreeSet stores elements in a sorted order (natural or custom), offering log(n) time complexity for basic operations.

In this code, we add a large number of elements to each type of set ( HashSet , LinkedHashSet , and TreeSet ) and measure the time it takes to perform this operation. This demonstrates the performance characteristics of each set type.

Typically, you will observe that HashSet performs the fastest for adding elements since it doesn't maintain any specific order, followed by LinkedHashSet , and TreeSet , which maintains a sorted order.

This output demonstrates the time taken (in nanoseconds) to add one million elements to each of the three sets: HashSet , LinkedHashSet , and TreeSet . As you can see, HashSet is the fastest, followed by LinkedHashSet , and TreeSet is the slowest due to its need to maintain elements in sorted order.

21. Differentiate between HashMap and ConcurrentHashMap

HashMap is not thread-safe and is suitable for single-threaded applications. ConcurrentHashMap , on the other hand, is designed for concurrent access and supports multiple threads without external synchronization. It provides high concurrency and performance for read and write operations.

22. Describe the Contract between the hashCode() and equals() Methods

The contract between hashCode() and equals() methods states that if two objects are equal ( equals() returns true), their hash codes ( hashCode() ) must also be equal.

However, the reverse is not necessarily true: objects with equal hash codes may not be equal. Adhering to this contract is crucial when using objects as keys in hash-based collections like HashMap .

23. What is Java Reflection?

Java reflection is a feature that allows you to inspect and manipulate the metadata of classes, methods, fields, and other program elements at runtime. It enables you to perform tasks such as dynamically creating objects, invoking methods, and accessing fields, even for classes that were not known at compile time.

24. How Do You Create a Custom Exception in Java?

You can create a custom exception in Java by extending the Exception class or one of its subclasses. By doing so, you can define your exception with specific attributes and behaviors tailored to your application's needs.


25. What is the Difference between a Checked and Unchecked Exception?

Checked exceptions are exceptions that must be either caught using a try-catch block or declared in the method signature using the throws keyword.

Unchecked exceptions (usually subclasses of RuntimeException ) do not require such handling.

Checked exceptions are typically used for recoverable errors, while unchecked exceptions represent programming errors or runtime issues.

Here is a code example to illustrate checked and unchecked exceptions.

In this code, we attempt to read a file using FileReader, which may throw a checked exception called IOException .

To handle this exception, we enclose the file reading code in a try-catch block specifically catching IOException . This is an example of how you handle checked exceptions, which are typically used for recoverable errors like file not found or I/O issues.

Now, let's take a look at an example of an unchecked exception:

In this code, we attempt to divide an integer by zero, which leads to an unchecked exception called ArithmeticException . Unchecked exceptions do not require explicit handling using a try-catch block. However, it's good practice to catch and handle them when you anticipate such issues. These exceptions often represent programming errors or runtime issues.

26. What Are Generics? Why Are They Used?

Generics in Java are a powerful feature that allows you to create classes, interfaces, and methods that operate on types. They provide a way to define classes or methods with a placeholder for the data type that will be used when an instance of the class is created or when a method is called.

Generics are used to make your code more reusable, type-safe, and less error-prone by allowing you to write generic algorithms that work with different data types. They help eliminate the need for typecasting and enable compile-time type checking.

For example, consider the use of a generic class to create a List of integers:

Generics ensure that you can only add integers to the list and that you don't need to perform explicit typecasting when retrieving elements from the list.

27. Explain the Concept of Java Lambda Expressions

Lambda expressions in Java are a concise way to express instances of single-method interfaces (functional interfaces) using a more compact syntax. They facilitate functional programming by allowing you to treat functions as first-class citizens.

Lambda expressions consist of a parameter list, an arrow (->), and a body. They provide a way to define and use anonymous functions.

For example, consider a functional interface Runnable that represents a task to be executed. With a lambda expression, you can define and execute a runnable task as follows:

We will talk about a more practical example later down the post.

28. What is the Diamond Problem in Inheritance?

The diamond problem in inheritance is a common issue in object-oriented programming languages that support multiple inheritance. It occurs when a class inherits from two classes that have a common ancestor class, resulting in ambiguity about which superclass's method or attribute to use.

Java solves the diamond problem by not supporting multiple inheritance of classes (that is, a class cannot inherit from more than one class).

But Java allows multiple inheritance of interfaces, which doesn't lead to the diamond problem because interfaces only declare method signatures, and the implementing class must provide concrete implementations. In case of method conflicts, the implementing class must explicitly choose which method to use.

Here's a simplified example to illustrate the diamond problem (even though Java doesn't directly encounter it):

In Java, the diamond problem is avoided through interface implementation and explicit method choice when conflicts arise.

29. Describe the Difference between Fail-fast and Fail-safe Iterators

In Java, fail-fast and fail-safe are two strategies for handling concurrent modification of collections during iteration.

Fail-fast iterators throw a ConcurrentModificationException if a collection is modified while being iterated. Fail-safe iterators, on the other hand, do not throw exceptions and allow safe iteration even if the collection is modified concurrently.

Fail-Fast Iterator Example:

In this example, when we attempt to remove an element from the list while iterating, it leads to a ConcurrentModificationException , which is characteristic of fail-fast behavior. Fail-fast iterators immediately detect and throw an exception when they detect that the collection has been modified during iteration.

Fail-Safe Iterator Example:

In this example, a ConcurrentHashMap is used, which supports fail-safe iterators. Even if we modify the map concurrently while iterating, there is no ConcurrentModificationException thrown. Fail-safe iterators continue iterating over the original elements and do not reflect changes made after the iterator is created.


30. What is Type Erasure in Java Generics?

Type erasure is a process in Java where type parameters in generic classes or methods are replaced with their upper bound or Object during compilation. This erasure ensures backward compatibility with pre-generic Java code. But it means that the type information is not available at runtime, which can lead to issues in some cases.

31. Describe the Differences between StringBuilder and StringBuffer

Thread safety:.

StringBuffer is thread-safe. This means it is synchronized, so it ensures that only one thread can modify it at a time. This is crucial in a multithreaded environment where you have multiple threads modifying the same string buffer.

StringBuilder , on the other hand, is not thread-safe. It does not guarantee synchronization, making it unsuitable for use in scenarios where a string is accessed and modified by multiple threads concurrently. But this lack of synchronization typically leads to better performance under single-threaded conditions.


Because StringBuffer operations are synchronized, they involve a certain overhead that can impact performance negatively when high-speed string manipulation is required.

StringBuilder is faster than StringBuffer because it avoids the overhead of synchronization. It's an excellent choice for string manipulation in a single-threaded environment.

Use Case Scenarios:

Use StringBuffer when you need to manipulate strings in a multithreaded environment. Its thread-safe nature makes it the appropriate choice in this scenario.

Use StringBuilder in single-threaded situations, such as local method scope or within a block synchronized externally, where thread safety is not a concern. Its performance benefits shine in these cases.

API Similarity:

Both StringBuilder and StringBuffer have almost identical APIs. They provide similar methods for manipulating strings, such as append() , insert() , delete() , reverse() , and so on.

This similarity means that switching from one to the other in your code is generally straightforward.

Memory Efficiency:

Both classes are more memory efficient compared to using String for concatenation. Since String is immutable in Java, concatenation with String creates multiple objects, whereas StringBuilder and StringBuffer modify the string in place.

Introduced Versions:

StringBuffer has been a part of Java since version 1.0, whereas StringBuilder was introduced later in Java 5. This introduction was primarily to offer a non-synchronized alternative to StringBuffer for improved performance in single-threaded applications.

You should make the choice between StringBuilder and StringBuffer based on the specific requirements of your application, particularly regarding thread safety and performance needs.

While StringBuffer provides safety in a multithreaded environment, StringBuilder offers speed and efficiency in single-threaded or externally synchronized scenarios.

32. What is the volatile Keyword in Java?

Basic Definition: The volatile keyword is used to modify the value of a variable by different threads. It ensures that the value of the volatile variable will always be read from the main memory and not from the thread's local cache.

Visibility Guarantee: In a multithreading environment, threads can cache variables. Without volatile, there's no guarantee that one thread's changes to a variable will be visible to another. The volatile keyword guarantees visibility of changes to variables across threads.

Happens-Before Relationship: volatile establishes a happens-before relationship in Java. This means that all the writes to the volatile variable are visible to subsequent reads of that variable, ensuring a consistent view of the variable across threads.

Usage Scenarios: volatile is used for variables that may be updated by multiple threads. It's often used for flags or status variables. For example, a volatile boolean running variable can be used to stop a thread.

Limitations: Volatile cannot be used with class or instance variables. It's only applicable to fields. It doesn't provide atomicity.

For instance, volatile int i; i++; is not an atomic operation. For atomicity, you might need to resort to AtomicInteger or synchronized methods or blocks. It's not a substitute for synchronization in every case, especially when multiple operations on the volatile variable need to be atomic.

Avoiding Common Misconceptions: A common misconception is that volatile makes the whole block of statements atomic, which is not true. It only ensures the visibility and ordering of the writes to the volatile variable.

Another misconception is that volatile variables are slow. But while they might have a slight overhead compared to non-volatile variables, they are generally faster than using synchronized methods or blocks. Performance Considerations: volatile can be a more lightweight alternative to synchronization in cases where only visibility concerns are present. It doesn't incur the locking overhead that synchronized methods or blocks do. Best Practices: Use volatile sparingly and only when necessary. Overusing it can lead to memory visibility issues that are harder to detect and debug. Always assess whether your use case requires atomicity, in which case other concurrent utilities or synchronization might be more appropriate.

volatile use case:

We will create a simple program where one thread modifies a volatile boolean flag, and another thread reads this flag. This flag will be used to control the execution of the second thread.

Code Example:

Key points in the comments:.

  • Visibility of volatile variable: The most crucial aspect of using volatile here is ensuring that the update to the running variable in one thread (main thread) is immediately visible to another thread ( thread1 ). This is what allows thread1 to stop gracefully when running is set to false .
  • Use in a Simple Flag Scenario: The example demonstrates a common scenario for using volatile , that is as a simple flag to control the execution flow in a multithreaded environment.
  • Absence of Compound Operations: Note that we are not performing any compound operations (like incrementing) on the running variable. If we were, additional synchronization would be needed because volatile alone does not guarantee atomicity of compound actions.
  • Choice of volatile Over Synchronization: The choice to use volatile over other synchronization mechanisms (like synchronized blocks or Locks ) is due to its lightweight nature when dealing with the visibility of a single variable. It avoids the overhead associated with acquiring and releasing locks.

33. Explain the Java Memory Model

The JMM defines how Java threads interact through memory. Essentially, it describes the relationship between variables and the actions of threads (reads and writes), ensuring consistency and predictability in concurrent programming.

Happens-Before Relationship:

At the heart of the JMM is the 'happens-before' relationship. This principle ensures memory visibility, guaranteeing that if one action happens-before another, then the first is visible to and affects the second.

For example, changes to a variable made by one thread are guaranteed to be visible to other threads only if a happens-before relationship is established.

Memory Visibility:

Without the JMM, threads might cache variables, and changes made by one thread might not be visible to others. The JMM ensures that changes made to a shared variable by one thread will eventually be visible to other threads.


The JMM utilizes synchronization to establish happens-before relationships. When a variable is accessed within synchronized blocks, any write operation in one synchronized block is visible to any subsequent read operation in another synchronized block.

Additionally, the JMM governs the behavior of volatile variables, ensuring visibility of updates to these variables across threads without synchronization.

Thread Interleaving and Atomicity:

The JMM defines how operations can interleave when executed by multiple threads. This can lead to complex states if not managed correctly.

Atomicity refers to operations that are indivisible and uninterrupted. In Java, operations on most primitive types (except long and double ) are atomic. However, compound operations (like incrementing a variable) are not automatically atomic.


The JMM allows compilers to reorder instructions for performance optimization as long as happens-before guarantees are maintained. However, this can lead to subtle bugs if not properly understood.

Use of Volatile Keyword:

The volatile keyword plays a significant role in the JMM. It ensures that any write to a volatile variable establishes a happens-before relationship with subsequent reads of that variable, thus ensuring memory visibility without the overhead of synchronization.

Locking Mechanisms:

Locks in Java (implicit via synchronized blocks/methods or explicit via ReentrantLock or others) also adhere to the JMM, ensuring that memory visibility is maintained across threads entering and exiting locks.

Safe Publication:

The JMM also addresses the concept of safe publication, ensuring that objects are fully constructed and visible to other threads after their creation.

High-Level Implications:

Understanding the JMM is critical for writing correct and efficient multi-threaded Java applications. It helps developers reason about how shared memory is handled, especially in complex applications where multiple threads interact and modify shared data.

Best Practices:

  • Always use the appropriate synchronization mechanism to ensure memory visibility and atomicity.
  • Be cautious about memory visibility issues; even simple operations can lead to visibility problems in a multi-threaded context.
  • Understand the cost of synchronization and use volatile variables where appropriate.

34. What is the Purpose of the default Keyword in Interfaces?

The default keyword in Java interfaces, introduced in Java 8, marks a significant evolution in the Java language, especially in how interfaces are used and implemented. It serves several key purposes:

Adding Method Implementations in Interfaces:

Prior to Java 8, interfaces in Java could only contain method signatures (abstract methods) without any implementation.

The default keyword allows you to provide a default implementation for a method within an interface. This feature bridges a gap between full abstraction (interfaces) and concrete implementations (classes).

Enhancing Interface Evolution:

One of the primary motivations for introducing the default keyword was to enhance the evolution of interfaces.

Before Java 8, adding a new method to an interface meant breaking all its existing implementations. With default methods, you can add new methods to interfaces with default implementations without breaking the existing implementations.

This is particularly useful for library designers, ensuring backward compatibility when interfaces need to be expanded.

Facilitating Functional Programming:

\The introduction of default methods played a crucial role in enabling functional programming features in Java, such as Lambda expressions. It allowed for richer interfaces (like java.util.stream.Stream ) which are fundamental to functional-style operations in Java.

Multiple Inheritance of Behavior:

While Java does not allow multiple inheritance of state (that is, you cannot inherit from multiple classes), the default keyword enables multiple inheritance of behavior.

A class can implement multiple interfaces, and each interface can provide a default implementation of methods, which the class inherits.

Reducing Boilerplate Code:

default methods can be used to reduce the amount of boilerplate code by providing a general implementation that can be shared across multiple implementing classes, while still allowing individual classes to override the default implementation if a more specific behavior is required.

Example Usage:

In this example, any class implementing the Vehicle interface must provide an implementation for cleanVehicle , but it's optional for startEngine . The default implementation of startEngine can be used as is, or overridden by the implementing class.

Best Practices and Considerations:

  • Use Sparingly: Default methods should be used judiciously. They are best suited for gradually evolving interfaces or for methods that have a common implementation across most implementing classes.
  • Design With Care: When designing interfaces with default methods, consider how they might be used or overridden. It's important to document the expected behavior and interactions between default methods and other abstract methods in the interface.
  • Overriding Default Methods: Just like any inherited method, default methods can be overridden in the implementing class. This should be done to provide a specific behavior different from the default implementation.


35. How Does switch Differ in Java 7 and Java 8?

Limited Case Types: In Java 7, the switch statement supports limited types for the case labels, namely byte , short , char , int , and their corresponding Wrapper classes, along with enum types and, as of Java 7, String .

Traditional Structure: The structure of the switch statement in Java 7 follows the conventional C-style format, with a series of case statements and an optional default case. Each case falls through to the next unless it ends with a break statement or other control flow statements like return .

No Lambda Expressions: Java 7 does not support lambda expressions, and thus, they cannot be used within a switch statement or case labels.

Lambda Expressions: While the basic syntax and supported types for the switch statement itself did not change in Java 8, the introduction of lambda expressions in this version brought a new paradigm in handling conditional logic.

This doesn’t directly change how switch works, but it offers alternative patterns for achieving similar outcomes, especially when used in conjunction with functional interfaces.

Functional Programming Approach: Java 8 promotes a more functional programming style, encouraging the use of streams, lambda expressions, and method references. This can lead to alternatives for traditional switch statements, like using Map of lambdas for conditional logic, which can be more readable and concise.

Enhanced Readability and Maintainability: Although not a direct change to the switch statement, the use of lambda expressions and functional programming practices in Java 8 can lead to more readable and maintainable code structures that might otherwise use complex switch or nested if-else statements.

Practical Considerations:

  • When to Use switch in Java 8: Despite the advancements in Java 8, the switch statement remains a viable and efficient method for controlling complex conditional logic. It is particularly useful when dealing with a known set of possible values, such as enum constants or strings.
  • Combining switch with Lambdas: While you cannot use lambdas directly in a switch statement, Java 8 allows for more elegant ways to handle complex conditional logic that might traditionally have been a use case for switch . For example, using a Map with lambdas or method references can sometimes replace a complex switch statement.
  • Performance Considerations: The performance of a switch statement is generally better than a series of if-else statements, especially when dealing with a large number of cases, due to its internal implementation using jump tables or binary search.

36. Explain the Concept of Autoboxing and Unboxing

What is autoboxing.

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer , a double to a Double , and so on.

When to use autoboxing

This feature is commonly used when working with collections, like ArrayList or HashMap , which can only store objects and not primitive types.

It simplifies the code by allowing direct assignment of a primitive value to a variable of the corresponding wrapper class.

Behind the Scenes:

When autoboxing, the compiler essentially uses the valueOf method of the respective wrapper class to convert the primitive to its wrapper type.

For example, Integer.valueOf(int) is used for converting int to Integer .

Performance Considerations:

  • While convenient, autoboxing can introduce performance overhead, especially in scenarios with extensive boxing and unboxing in tight loops, due to the creation of additional objects.

What is unboxing?

Unboxing is the reverse process, where the Java compiler automatically converts an object of a wrapper type to its corresponding primitive type.

When to use unboxing

It is often used when performing arithmetic operations or comparisons on objects of wrapper classes, where primitive types are required.

During unboxing, the compiler uses the corresponding wrapper class's method to extract the primitive value. For instance, it uses Integer.intValue() to get the int from an Integer .

Null Pointer Exception:

A crucial point to consider is that unboxing a null object reference will throw a NullPointerException . This is a common bug in code that relies heavily on autoboxing and unboxing.

  • Be Aware of Implicit Conversions: It's important to be aware that these conversions are happening, as they can sometimes lead to unexpected behavior, especially with regards to NullPointerExceptions during unboxing of null references.
  • Consider Performance: In performance-sensitive applications, prefer using primitives to avoid the overhead of autoboxing and unboxing.
  • Null Safety: Always check for null before unboxing, to avoid potential NullPointerExceptions .
  • Readability vs Efficiency: While autoboxing and unboxing significantly improve code readability and reduce boilerplate, be mindful of their impact on performance and choose wisely based on the application's context.

37. Describe the @FunctionalInterface Annotation

The @FunctionalInterface annotation in Java is a key feature that dovetails with the language's embrace of functional programming concepts, particularly since Java 8. It serves a specific purpose in defining and enforcing certain coding patterns, making it a vital tool for developers focusing on functional-style programming.

Definition and Purpose

@FunctionalInterface is an annotation that marks an interface as a functional interface.

A functional interface in Java is an interface that contains exactly one abstract method. This restriction makes it eligible to be used in lambda expressions and method references, which are core components of Java's functional programming capabilities.

Enforcing Single Abstract Method

The primary role of @FunctionalInterface is to signal the compiler to enforce the rule of a single abstract method. If the annotated interface does not adhere to this rule, the compiler throws an error, ensuring the interface's contract is not accidentally broken by adding additional abstract methods.

Usage and Implications:

  • Lambda Expressions: Functional interfaces provide target types for lambda expressions and method references. For example, Java's standard java.util.function package contains several functional interfaces like Function<T,R> , Predicate<T> , Consumer<T> , which are widely used in stream operations and other functional programming scenarios.
  • Optional but Recommended: While the @FunctionalInterface annotation is not mandatory for an interface to be considered a functional interface by the Java compiler, using it is considered best practice. It makes the developer's intention clear and ensures the contract of the functional interface is not inadvertently broken.
  • Existing Interfaces: Many existing interfaces from earlier versions of Java naturally fit the definition of a functional interface. For example, java.lang.Runnable and java.util.concurrent.Callable are both functional interfaces as they have only one abstract method.

In this example, SimpleFunction is a functional interface with one abstract method execute() . The @FunctionalInterface annotation ensures that no additional abstract methods are inadvertently added.

  • Clarity and Documentation: Use @FunctionalInterface to communicate your intention clearly both to the compiler and to other developers. It serves as a form of documentation.
  • Design with Care: When designing a functional interface, consider its general utility and how it fits into the broader application architecture, especially if it's intended to be used across different parts of the application.
  • Avoid Overuse: While functional programming in Java can lead to more elegant and concise code, be cautious of overusing lambdas and functional interfaces, as they can make the code harder to read and debug if used excessively or inappropriately.
  • Compatibility with Older Java Versions: Be aware that @FunctionalInterface is a Java 8 feature. If you're working on applications that need to be compatible with earlier Java versions, you won’t be able to use this feature.

38. How Can You Achieve Immutability in Java?

Achieving immutability in Java is a fundamental practice, particularly useful for creating robust, thread-safe applications.

An immutable object is one whose state cannot be modified after it is created. Here's a detailed and precise explanation of how to achieve immutability in Java:

Core Principles of Immutability:

  • No Setters: Immutable objects do not expose any methods to modify their state after construction. This typically means not providing any setter methods.
  • Final Class: The class should be declared as final to prevent subclassing. Subclasses could add mutable state, undermining the immutability of the parent class.
  • Final Fields: All fields should be final , ensuring they are assigned only once, typically within the constructor, and cannot be re-assigned.
  • Private Fields: Fields should be private to prevent external modification and to encapsulate the data.
  • No Direct Access to Mutable Objects:
  • If your class has fields that are references to mutable objects (like arrays or collections), ensure these fields are not directly exposed or modified:
  • Do not provide methods that modify mutable objects.
  • Do not share references to the mutable objects. Provide copies of mutable objects when needed.

How to Create an Immutable Class:

  • Defensive Copies: When dealing with mutable objects passed to the constructor or returned by methods, create defensive copies. This practice prevents external code from modifying the internal state of the immutable object.
  • Immutable Collections: Utilize immutable collections (like those provided in Java 9 and later) to simplify the creation of classes with immutable collection fields.
  • Performance Considerations: Be mindful of the performance implications of creating defensive copies, especially in performance-critical applications.
  • Use in Multi-threaded Environments: Immutable objects are inherently thread-safe, making them ideal for use in multi-threaded environments.
  • String and Wrapper Types: Leverage the immutability of String and wrapper types (Integer, Long, and so on) as part of your immutable objects.
  • Design Strategy: Consider immutability as a design strategy, especially for objects representing values that are not expected to change, such as configuration data, constants, or natural data types.

Advantages of Immutability:

  • Simplicity and Clarity: Immutable objects are easier to understand and use. There's no need to track changes in state, reducing cognitive load.
  • Thread Safety: Immutability eliminates issues related to concurrency and synchronization, as immutable objects can be freely shared between threads without synchronization.
  • Caching and Reuse: Immutable objects can be cached and reused, as they are guaranteed not to change, reducing the overhead of object creation.
  • Hashcode Caching: Immutable objects are great candidates for caching their hashcode, which can be beneficial in collections like HashMaps and HashSets .

39. What is the Decorator Pattern?

The Decorator Pattern is a structural design pattern used in object-oriented programming, and it's particularly useful for extending the functionality of objects at runtime. It is a robust alternative to subclassing, providing a more flexible approach to add responsibilities to objects without modifying their underlying classes.

Purpose of decorator pattern

The Decorator Pattern allows you to attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

The pattern involves a set of decorator classes that are used to wrap concrete components. Each decorator class has a reference to a component object and adds its own behavior either before or after delegating the task to the component object.

How to implement the decorator pattern

It typically involves an abstract decorator class that implements or extends the same interface or superclass as the objects it will dynamically add functionality to. Concrete decorators then extend the abstract decorator.

Key Components:

  • Component: An interface or abstract class defining the operations that can be altered by decorators.
  • Concrete Component: A class implementing or extending the Component, defining an object to which additional responsibilities can be attached.
  • Decorator: An abstract class that extends or implements the Component interface and has a reference to a Component.
  • Concrete Decorator: A class that extends the Decorator and adds functionalities to the Component it decorates.

Decorator example in Java:

Usage and advantages:.

  • Flexibility: The Decorator Pattern provides a more flexible way to add responsibilities to objects compared to subclassing. New functionalities can be added at runtime.
  • Avoid Class Explosion: It helps in avoiding an extensive hierarchy of subclasses when you need multiple combinations of functionalities.
  • Single Responsibility Principle: Decorators allow functionalities to be divided into simple classes with single responsibilities.


  • Complexity: Overuse of the decorator pattern can lead to complexity, making the code harder to understand and maintain.
  • Instantiation Management: Managing the instantiation of decorated objects can be challenging, especially when dealing with multiple layers of decoration.

The Decorator Pattern is a powerful tool in a software developer's toolkit, offering a dynamic and flexible solution for extending object functionality. Understanding and applying this pattern can greatly enhance the design of software, particularly in situations where adding responsibilities to objects at runtime is necessary.

This pattern is highly valued in software development, as it showcases an ability to effectively manage and extend object functionalities without altering existing codebases, aligning with principles of maintainability and scalability.

40. Explain Java I/O Streams

Java I/O (Input/Output) streams are a fundamental part of the Java I/O API, providing a robust framework for handling input and output operations in Java. Understanding these streams is crucial for efficient data handling in Java applications.

Overview of Java I/O Streams

I/O streams in Java are used to read data from an input source and to write data to an output destination. The Java I/O API is rich and provides various classes to handle different types of data, like bytes, characters, objects, etc.

Stream Types:

Java I/O streams are broadly categorized into two types:

  • Byte Streams: Handle I/O of raw binary data.
  • Character Streams: Handle I/O of character data, automatically handling character encoding and decoding.

Byte Streams:

  • Classes: InputStream and OutputStream are abstract classes at the hierarchy's root for byte streams.
  • Usage: They are used for reading and writing binary data, such as image or video files.
  • Example Classes: FileInputStream , FileOutputStream , BufferedInputStream , BufferedOutputStream , etc.

Character Streams:

  • Classes: Reader and Writer are abstract classes for character streams.
  • Usage: Suitable for handling textual data, ensuring correct interpretation of characters according to the default character encoding.
  • Example Classes: FileReader , FileWriter , BufferedReader , BufferedWriter , etc.

Key Features of Java I/O Streams:

  • Stream Hierarchy: Java uses a hierarchy of classes to manage different types of I/O operations, allowing for flexibility and reusability of code.
  • Decorators: Java I/O uses decorators, where one stream wraps another and adds additional capabilities, like buffering, data conversion, and so on.
  • Buffering: Buffering is a common practice in I/O streams to enhance I/O efficiency, allowing for the temporary storage of data in memory before it's written to or read from the actual I/O source.
  • Exception Handling: I/O operations in Java are prone to errors like file not found, access denied, etc. Hence, most I/O operations throw IOException , which must be properly handled using try-catch blocks or thrown further.
  • Use Buffered Streams: Always use buffered streams ( BufferedInputStream , BufferedOutputStream , BufferedReader , BufferedWriter ) for efficient I/O operations, as they reduce the number of actual I/O operations by buffering chunks of data.
  • Close Streams: Ensure streams are closed after their operation is complete to free up system resources. This is typically done in a finally block or using try-with-resources introduced in Java 7.
  • Error Handling: Implement robust error handling. I/O operations are susceptible to many issues, so proper exception handling is crucial.
  • Character Encoding: Be mindful of character encoding while using character streams. Incorrect handling of encoding can lead to data corruption.

Practical Example:

In this example, BufferedReader and BufferedWriter are used for reading from and writing to a text file, demonstrating the use of character streams with buffering for efficiency.

Java I/O streams form the backbone of data handling in Java applications. Understanding the distinction between byte and character streams, along with the proper use of buffering and exception handling, is essential for writing efficient, robust, and maintainable Java code.

This knowledge is vital for Java developers and is often a subject of interest in technical interviews, showcasing one's capability to handle data proficiently in Java applications.


41. How Does the Garbage Collector Work in Java?

In Java, garbage collection (GC) is a critical process of automatically freeing memory by reclaiming space from objects that are no longer in use, ensuring efficient memory management.

Understanding how the garbage collector works in Java is essential for writing high-performance applications and is a key area of knowledge in professional Java development.

Overview of Garbage Collection in Java

The primary function of garbage collection in Java is to identify and discard objects that are no longer needed by a program. This prevents memory leaks and optimizes memory usage.

Automatic Memory Management

Unlike languages where memory management is manual (like C/C++), Java provides automatic memory management through its garbage collector, which runs in the background.

How the Garbage Collector Works

Object creation and heap storage:.

In Java, objects are created in a heap memory area. This heap is divided into several parts – Young Generation, Old Generation (or Tenured Generation), and Permanent Generation (replaced by Metaspace in Java 8).

  • Young Generation: Newly created objects reside in the Young Generation, which is further divided into three parts: one Eden space and two Survivor spaces (S0 and S1). Most objects die young. When the Eden space fills up, a minor GC is triggered, moving surviving objects to one of the Survivor spaces (S0 or S1) and clearing Eden.
  • Aging of Objects: As objects survive more garbage collection cycles, they age. After surviving certain cycles, they are moved to the Old Generation.
  • Old Generation: The Old Generation stores long-living objects. A more comprehensive form of GC, known as major GC, occurs here, which is generally more time-consuming.
  • Metaspace (Java 8 and above): Metaspace stores metadata of classes. Unlike the PermGen (Permanent Generation) space in earlier Java versions, Metaspace uses native memory, and its size is not fixed but can be configured.

Types of Garbage Collectors in Java:

  • Serial GC: Suitable for single-threaded environments. It freezes all application threads during garbage collection.
  • Parallel GC: Also known as Throughput Collector, it uses multiple threads for young generation garbage collection but stops all application threads during major GC.
  • Concurrent Mark Sweep (CMS) GC: Minimizes pauses by doing most of its work concurrently with application threads but requires more CPU resources.
  • G1 Garbage Collector: Designed for large heap memory areas, it divides the heap into regions and prioritizes GC on regions with the most garbage first.

Garbage Collection Processes

The process starts by marking all reachable objects. Reachable objects are those that are accessible directly or indirectly through references from root objects (like local variables, static fields, etc.).

Unreachable objects (those not marked as reachable) are considered for deletion .

To prevent fragmentation and optimize memory usage, some garbage collectors perform compaction , moving surviving objects closer together.

  • Avoid Memory Leaks: Despite automatic garbage collection, memory leaks can still occur (for example, through static references). It's crucial to be mindful of object references and their lifecycles.
  • GC Tuning: For high-performance applications, GC tuning can be essential. Understanding different garbage collector types and their configuration parameters allows for optimal tuning according to application needs.
  • Monitoring and Profiling: Regular monitoring of garbage collection and memory usage is important, especially for applications with high throughput or large heaps.

Garbage collection in Java is a sophisticated system designed to efficiently manage memory in the Java Virtual Machine (JVM). An in-depth understanding of how garbage collection works, its types, and its impact on application performance is essential for Java developers, particularly those working on large-scale, high-performance applications.

This knowledge not only helps in writing efficient and robust applications but also is a valuable skill in troubleshooting and performance tuning, aspects highly regarded in the field of software development.

42. What Are the Benefits of Using Java NIO?

Java NIO (New Input/Output), introduced in JDK 1.4, marks a substantial advancement in Java's approach to I/O operations. It was developed to address the constraints of traditional I/O methods, leading to improved scalability and efficiency.

This makes Java NIO particularly advantageous in scenarios demanding high throughput and concurrent access.

Let’s discuss the key benefits of using Java NIO in detail.

1. Channels and Buffers: Enhanced Data Handling

  • Channels : These are bi-directional conduits allowing both reading and writing operations. Unlike traditional unidirectional streams, channels simplify I/O patterns, especially for network sockets, by enabling two-way communication within a single channel.
  • Buffers : Acting as fixed-size data containers, buffers allow batch processing of data. This is more efficient compared to the byte-by-byte processing in traditional I/O, as it enables handling data in larger, more manageable blocks.

2. Non-blocking and Asynchronous I/O

Java NIO supports non-blocking and asynchronous I/O operations, a stark contrast to the blocking nature of traditional I/O where a thread remains idle until an operation completes.

This feature of NIO means a thread can initiate an I/O operation and continue performing other tasks without waiting for the I/O process to finish. This capability significantly enhances the scalability and responsiveness of applications, making them more efficient in handling multiple concurrent I/O requests.

3. Practical Applications

Java NIO is particularly effective in environments that require high-performance and low latency, such as:

  • Web and Application Servers : Managing high-volume network traffic efficiently.
  • Real-time Systems : Like trading platforms where quick data processing is critical.
  • Big Data Applications : Benefiting from efficient handling of large datasets.
  • File-based Database Systems : Where efficient file I/O operations are crucial.

4. Channels: The Foundation of NIO’s Architecture

Channels serve as the backbone of NIO, providing a more unified and simplified interface for various I/O operations. They come in different types, each catering to specific needs:

  • FileChannel : For file operations.
  • SocketChannel and ServerSocketChannel : For TCP network communications.
  • DatagramChannel : For UDP operations.
  • Pipes : For inter-thread communication. Particularly in network operations, the ability of channels to operate in a non-blocking mode allows a single thread to handle multiple connections, enhancing the application’s scalability.

5. Buffers: Central to NIO’s Data Transfer

Buffers in NIO are essential for data transfer, acting as temporary storage for data during I/O operations. Their key operations include:

  • Put and Get : For writing and reading data.
  • Flip : To switch modes between reading and writing.
  • Clear and Compact : Preparing the buffer for new data. Different buffer types (like ByteBuffer, CharBuffer, IntBuffer) cater to various data primitives, enhancing the flexibility and efficiency of data handling. Notably, direct buffers, which are allocated outside of the JVM heap, can provide faster I/O operations, though they come with higher allocation and deallocation costs.

6. Selectors: Streamlining Scalable I/O Operations

Selectors are a unique NIO feature enabling a single thread to monitor multiple channels for readiness, thus efficiently managing numerous I/O operations. This reduces the need for multiple threads, cutting down on resource usage and context switching, which is particularly advantageous in high-performance environments.

7. Improved Performance and Scalability

The amalgamation of channels, buffers, and selectors provides a substantial performance boost. The non-blocking nature of NIO minimizes idle thread time, and managing multiple channels with a single thread significantly improves the scalability. This is pivotal in server environments dealing with numerous simultaneous connections.

Java NIO offers a robust, scalable, and efficient framework for handling I/O operations, addressing many of the limitations of traditional I/O. Its design is particularly advantageous for high-throughput and concurrent-processing systems.

While the complexity of NIO might be higher compared to traditional I/O, the performance and scalability benefits it provides make it an indispensable tool for developers working on large-scale, I/O-intensive Java applications.

43. Explain the Observer Pattern

The Observer pattern is a design pattern where an object, known as the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

It's particularly useful in the scenario where a single object needs to notify an array of objects about a change in its state. In the context of a newsletter system, the Observer pattern can be effectively used to notify subscribers whenever a new post is available.

How to Implement the Observer Pattern for a Newsletter System

Let's break down the implementation using the Observer pattern in the context of a newsletter system:

  • Subject (Newsletter) : This is the entity being observed. It will notify all attached observers when a new post is available.
  • Observer (Subscriber) : These are the observers who wish to be notified about new posts in the newsletter.
  • Client : This will use both the Subject and Observers.

Step 1: Create the Subject Class (Newsletter)

Step 2: create the observer abstract class (subscriber), step 3: create concrete observer classes.



Step 4: Use the Newsletter and Concrete Subscriber Objects

Step 5: output verification.

When running NewsletterSystemDemo , the output will be something like:

This output indicates that both the email and SMS subscribers are notified whenever the newsletter has a new post.

The Observer pattern provides a clean and straightforward way to implement a subscription mechanism in a newsletter system, ensuring that all subscribers are automatically updated with the latest posts.

This pattern enhances modularity and separation of concerns, making the system easier to understand, maintain, and extend.

44. Explain the Purpose of the this Keyword.

The this keyword in Java serves a very specific and useful purpose. It refers to the current instance of the class in which it is used. This is particularly valuable in scenarios where you need to distinguish between class fields (instance variables) and parameters or variables within a method that have the same name. Let's break it down:

Reference to Instance Variables: When a class’s field is shadowed by a method or constructor parameter, this can be used for referencing the class's field. For instance, in a setter method, this helps differentiate between the instance variable and the parameter passed to the method.

Calling One Constructor from Another: In a class with overloaded constructors, this can be used to call one constructor from another, avoiding code duplication.

Returning the Current Instance: Methods can return this to return the current class instance. This is often used in method chaining.

Passing the Current Instance to Another Method: this can be passed as an argument in the method call or constructor call. This is common in event handling.

Disambiguation: It eliminates ambiguity when instance variables and parameters or local variables share the same name.


45. Explain Java's try-with-resources.

Java's try-with-resources, introduced in Java 7, is a mechanism that ensures more efficient handling of resources, like files or sockets, in Java. Its primary purpose is to simplify the cleanup of resources which must be closed after their operations are completed.

Key Characteristics:

Automatic Resource Management: In try-with-resources, resources declared within the try clause are automatically closed at the end of the statement, even if exceptions are thrown. This reduces boilerplate code significantly as compared to traditional try-catch-finally blocks.

Syntax: The resources that implement java.lang.AutoCloseable or java.io.Closeable are declared and initialized within parentheses just after the try keyword.

  • Here, the BufferedReader instance is automatically closed when the try block exits, regardless of whether it exits normally or due to an exception.
  • Exception Handling: Any exception thrown by the automatic closure of resources is suppressed if an exception is thrown in the try block. These suppressed exceptions can be retrieved using Throwable.getSuppressed() method.
  • Improved Readability and Reliability: This structure enhances code readability and reliability. It reduces the risk of resource leaks, as the closing of resources is handled automatically.
  • Use in Custom Resources: Custom classes can also utilize this mechanism by implementing the AutoCloseable interface and overriding the close method.

Practical Implications:

In real-world applications, try-with-resources ensures that resources like file streams, database connections, or network sockets are closed properly, preventing resource leaks which could lead to performance issues and other bugs. It is especially valuable in large-scale applications where resource management is critical for efficiency and reliability.

46. Explain the Difference between C++ and Java.

When distinguishing between C++ and Java, it's important to understand that both are powerful programming languages with their unique characteristics and use cases.

They share some similarities, as both are object-oriented and have similar syntax (being influenced by C), but there are key differences that set them apart.

Language Nature and Design Philosophy:

C++ is a multi-paradigm language that supports both procedural and object-oriented programming. It's often chosen for system-level programming due to its efficiency and fine-grained control over memory management.

Java , on the other hand, is primarily object-oriented and designed with a simpler approach to avoid common programming errors (like pointer errors in C++). Java's design principle "Write Once, Run Anywhere" (WORA) emphasizes portability, which is achieved through the Java Virtual Machine (JVM).

Memory Management:

In C++ , memory management is manual. Programmers have direct control over memory allocation and deallocation using operators like new and delete .

Java abstracts away the complexity of direct memory management through its Automatic Garbage Collection, which periodically frees memory that's no longer in use, reducing the likelihood of memory leaks but at the cost of less control and potential overhead.

Platform Dependency and Portability:

C++ is platform-dependent. A C++ program needs to be compiled for each specific platform it's intended to run on, which can lead to more work when targeting multiple platforms.

Java is platform-independent at the source level. Java programs are compiled into bytecode, which can run on any device equipped with a JVM, making it highly portable.

Runtime and Performance:

C++ generally offers higher performance than Java. It compiles directly to machine code, which the CPU executes, resulting in faster execution suitable for performance-critical applications.

Java may have slower performance due to the added abstraction layer of the JVM. But improvements in Just-In-Time (JIT) compilers within the JVM have significantly narrowed this performance gap.

Pointers and Memory Safety:

C++ supports both pointers and references, allowing for powerful, albeit potentially risky, memory manipulation.

Java has references but does not support pointers (at least not in the traditional sense), reducing the risk of memory access errors, thereby increasing program safety.

Exception Handling:

C++ supports exception handling but does not enforce error handling (uncaught exceptions can lead to undefined behavior).

Java has a robust exception handling mechanism, requiring checked exceptions to be caught or declared in the method signature, promoting better error management practices.


C++ has more complex approaches to multi-threading and requires careful management to ensure thread safety.

Java provides built-in support for multi-threading with synchronized methods and blocks, making concurrent programming more manageable.

Standard Template Library (STL) vs. Java Standard Library:

C++ 's STL is a powerful library that offers containers, algorithms, iterators, and so on for efficient data manipulation.

Java 's Standard Library provides a rich set of APIs, including collections, streams, networking, and so on with a focus on ease of use.

Legacy and Use Cases:

C++ is often chosen for system/software development, game development, and applications where hardware access and performance are critical.

Java is widely used in enterprise environments, web services, and Android app development due to its portability and robust libraries.

Both C++ and Java have their strengths and are chosen based on the requirements of the project.

C++ is preferred for scenarios where performance and memory control are crucial, while Java is ideal for applications where portability and ease of use are more important.

Understanding these differences is key in selecting the right language for a particular task or project, and adapting to the strengths of each can lead to more efficient and effective programming practices.

47. What is Polymorphism? Provide an Example.

Polymorphism, a fundamental concept in object-oriented programming, allows objects to be treated as instances of their parent class or interface. It’s a Greek word meaning “many shapes” and in programming, it refers to the ability of a single function or method to work in different ways based on the object it is acting upon.

There are two primary types of polymorphism: compile-time (or static) polymorphism and runtime (or dynamic) polymorphism.

Compile-Time Polymorphism : This is achieved through method overloading and operator overloading. It’s called compile-time polymorphism because the decision about which method to call is made by the compiler.

Method Overloading involves having multiple methods in the same scope, with the same name but different parameters.

In this example, the operate method is overloaded with different parameter types, allowing it to behave differently based on the type of arguments passed.

Runtime Polymorphism : This is mostly achieved through method overriding, which is a feature of inheritance in object-oriented programming. In runtime polymorphism, the method to be executed is determined at runtime.

Method Overriding involves defining a method in a subclass that has the same name, return type, and parameters as a method in its superclass.

In this example, the speak method in the subclass Dog overrides the speak method in its superclass Animal . When the speak method is called on an object of type Dog , the overridden method in the Dog class is executed, demonstrating runtime polymorphism.

Why Polymorphism is Important

  • Flexibility and Extensibility : Polymorphism allows for flexible and extensible code. You can create a more generalized code that works on the superclass type, and it automatically adapts to the specific subclass types.
  • Code Reusability : It enables the reuse of code through inheritance and the ability to override or overload methods.
  • Loose Coupling : By using polymorphic behavior, components can be designed loosely coupled, which means a change in one part of the system causes minimal or no effect on other parts of the system.
  • Simplifies Code Maintenance : With polymorphism, developers can write more maintainable and manageable code, as changes to a superclass are inherited by all subclasses, reducing the need for changes across multiple classes.

Polymorphism is a cornerstone in the world of object-oriented programming, enabling more dynamic and flexible code. It allows objects to interact in a more abstract manner, focusing on the shared behavior rather than the specific types.

Understanding and effectively using polymorphism can lead to more robust and maintainable code, a crucial aspect for any software developer looking to excel in their field.

48. How Can You Avoid Memory Leaks in Java?

Avoiding memory leaks in Java, despite its automated garbage collection mechanism, requires a deep understanding of how memory allocation and release work in Java, alongside meticulous coding practices and effective use of analysis tools.

Let’s delve into some advanced and specific strategies for preventing memory leaks in Java applications:

Understand Object Lifecycle and Scope:

  • Scope Management : Ensure objects are scoped as narrowly as possible. For instance, use local variables within methods rather than class-level variables if the data does not need to persist beyond the method’s execution context.
  • Reference Management : Be cautious with static references. Static fields can keep objects alive for the lifetime of the class, potentially leading to memory leaks.

Efficient Use of Collections:

  • WeakHashMap : For cache implementations, consider using WeakHashMap . It uses weak references for keys, which allows keys (and their associated values) to be garbage-collected when no longer in use.
  • Data Structure Choice : Be mindful of the choice of data structure. For example, use ArrayList over LinkedList for large lists of data where frequent access is required, as LinkedList can consume more memory due to the storage of additional node references.

Leveraging WeakReferences and SoftReferences :

  • SoftReferences for Caches : Use SoftReference for memory-sensitive caches. The garbage collector will only remove soft-referenced objects if it needs memory, making them more persistent than weak references.
  • WeakReferences for Listeners : Utilize WeakReference for listener patterns where listeners might not be explicitly removed.

Managing Resources and I/O:

  • AutoCloseable and Try-with-Resources : For resources like streams, files, and connections, use try-with-resources for automatic closure. Ensure that objects implementing AutoCloseable are closed properly to release resources.

Inner Classes Handling:

  • Static Inner Classes : Prefer static inner classes over non-static to avoid the implicit reference to the outer class instance, which can prevent the outer instance from being garbage-collected.

Profiling and Leak Detection:

  • Heap Dump Analysis : Regularly analyze heap dumps in tools like Eclipse Memory Analyzer (MAT) to detect large objects and potential memory leaks.
  • Java Flight Recorder : Use Java Flight Recorder for runtime analysis and monitoring, which can help identify memory leaks.

ThreadLocal Variables Management:

  • Explicit Removal : Always remove ThreadLocal variables after use, particularly in thread-pooled environments like servlet containers or application servers.

ClassLoader Leaks:

  • ClassLoader Lifecycle : In environments with dynamic class loading/unloading (for example, web servers), ensure that class loaders are garbage collected when not needed. This involves ensuring that classes loaded by these class loaders are no longer referenced.

Garbage Collection Tuning:

  • GC Analysis : Analyze GC logs to understand the garbage collection behavior and identify potential memory leaks.
  • GC Algorithm Choice : Choose an appropriate garbage collection algorithm based on application needs, which can be tuned with JVM options for optimal performance.

String Interning:

  • Selective Interning : Be cautious with the String.intern() method. Unnecessary interning of strings can lead to a bloated String pool.

Static Analysis Tools:

Utilize tools like SonarQube, FindBugs, or PMD to statically analyze code for patterns that could lead to memory leaks.

Developer Training and Code Reviews:

Regularly train developers on best practices in memory management and conduct thorough code reviews with a focus on potential memory leak patterns.

Memory leak prevention in Java is a sophisticated practice that involves a thorough understanding of Java memory management, careful coding, diligent use of analysis tools, and regular monitoring.

By adopting these advanced practices, developers can significantly mitigate the risk of memory leaks, leading to more robust, efficient, and scalable Java applications.

49. Explain the Purpose of Java's Synchronized Block

The purpose of Java's synchronized block is to ensure thread safety in concurrent programming by controlling access to a shared resource among multiple threads.

In a multithreaded environment, where multiple threads operate on the same object, there's a risk of data inconsistency if the threads simultaneously modify the object. A synchronized block in Java is used to lock an object for exclusive access by a single thread.

Thread Safety and Data Consistency:

When different threads access and modify shared data, it can lead to unpredictable data states and inconsistencies. The synchronized block ensures that only one thread can execute a particular block of code at a time, thus maintaining data integrity.

Lock Mechanism:

In Java, each object has an intrinsic lock or monitor lock. When a thread enters a synchronized block, it acquires the lock on the specified object. Other threads attempting to enter the synchronized block on the same object are blocked until the thread inside the synchronized block exits, thereby releasing the lock.

Syntax and Usage:

The synchronized block is defined within a method, and you must specify the object that provides the lock:

The lockObject is a reference to the object whose lock the synchronized block acquires. It can be this to lock the current object, a class object for class-level locks, or any other object.

Advantages Over Synchronized Methods:

Compared to synchronized methods, synchronized blocks provide finer control over the scope and duration of the lock.

While a synchronized method locks the entire method, a synchronized block can lock only the part of the method that needs synchronization, potentially improving performance.

Avoiding Deadlocks:

Take care to avoid deadlocks, a situation where two or more threads are blocked forever, each waiting for the other's lock. This usually occurs when multiple synchronized blocks are locking objects in an inconsistent order.

Synchronized blocks also solve memory visibility problems. Changes made by one thread in a synchronized block are visible to other threads entering subsequent synchronized blocks on the same object.

Best Practices

  • Minimize Lock Contention : Keep the synchronized sections as short as possible to minimize lock contention and avoid performance bottlenecks.
  • Consistent Locking Order : Always acquire locks in a consistent order to prevent deadlocks.
  • Avoid Locking on Public Objects : Locking on public objects can lead to accidental and uncontrolled access to the lock, increasing the deadlock risk. Prefer private objects as lock targets.
  • Complement with Other Concurrency Tools : In some cases, using higher-level concurrency tools like ReentrantLock , Semaphore , or concurrent collections from java.util.concurrent package might be more appropriate.

Java's synchronized block is a critical tool for achieving thread safety in concurrent applications. Its proper use ensures data integrity and consistency by controlling access to shared resources. But, it requires careful consideration to avoid common pitfalls like deadlocks and performance issues due to excessive lock contention.

Understanding and applying these concepts is essential for developers working in a multithreaded environment to create robust and efficient Java applications.

50. Explain the Concept of Modules in Java

Modules in Java, introduced in Java 9 with the Java Platform Module System (JPMS), represent a fundamental shift in organizing Java applications and their dependencies.

Understanding modules is essential for modern Java development, as they offer improved encapsulation, reliable configuration, and scalable system architectures.

What are Java modules?

A module in Java is a self-contained unit of code and data, with well-defined interfaces for communicating with other modules. Each module explicitly declares its dependencies on other modules.

Modules enable better encapsulation by allowing a module to expose only those parts of its API which should be accessible to other modules, while keeping the rest of its codebase hidden. This reduces the risk of unintended usage of internal APIs.

Key Components of modules:

module-info.java : Each module must have a module-info.java file at its root, which declares the module's name, its required dependencies, and the packages it exports.

  • Here, com.example.myapp is the module name, java.sql is a required module, and com.example.myapp.api is the exported package.
  • Exports and Requires: The exports keyword specifies which packages are accessible to other modules, while requires lists the modules on which the current module depends.
  • Improved Application Structure: Modules encourage a cleaner, more organized code structure, helping in maintaining large codebases and improving code quality.
  • Reduced Memory Footprint: By only loading the required modules, applications can reduce their memory footprint and start-up time, enhancing performance.
  • Enhanced Security and Maintenance: Modules reduce the surface area for potential security vulnerabilities. They also simplify dependency management, making it easier to update and maintain libraries without affecting the entire system.

Consider a scenario where you are developing a large-scale application with various functionalities like user management, data processing, and reporting. By organizing these functionalities into separate modules (like usermodule , dataprocessmodule , reportmodule ), you can maintain them independently, avoiding the complexities of a monolithic application structure.

Modules in Java are a powerful feature for building scalable, maintainable, and efficient applications. They offer clear boundaries and contracts between different parts of a system, facilitating better design and architecture.

For developers and teams aiming to build robust Java applications, understanding and leveraging modules is not just a technical skill but a strategic approach to software development.

This modular architecture aligns with modern development practices, enabling Java applications to be more scalable and easier to manage in the long term.


As we wrap up this roundup of Java interview questions, I want to take a moment to thank the freeCodeCamp team. This platform is a fantastic resource for people learning to code, and it's great to have such a supportive community in the tech world.

I also want to thank the editorial team for their help in making this guide possible. Working together has been a great experience, and it's been rewarding to combine our efforts to help others learn Java.

It's important to reflect on the journey we've undertaken together. Java's robustness in Object-Oriented Programming (OOP) is a critical asset for developers at all levels, especially those aspiring to join top-tier tech firms. This handbook has aimed to provide a clear pathway to mastering Java interviews, focusing on the insights and techniques that matter most in the competitive landscape of big tech.

From the fundamentals to the more complex aspects of Java, I've sought to bridge the gap between basic Java knowledge and the sophisticated expertise that industry leaders like Google value. This resource is crafted not just for those new to Java, but also for those revisiting key concepts, offering a comprehensive understanding of the language in a practical context.

As you continue to explore the depths of Java, remember that mastering this language is not just about enhancing coding skills, but also about expanding your professional horizons. Java's significant role in IoT and its presence in billions of devices worldwide make it a language that can truly shape your career.

In closing, I hope this handbook has provided you with valuable insights and a strong foundation for your future endeavors in Java programming and beyond. Whether you're preparing for a big tech interview or simply looking to refine your software development skills, this guide is a stepping stone towards achieving those goals.

If you're keen on furthering your Java knowledge, here's a guide to help you conquer Java and launch your coding career . It's perfect for those interested in AI and machine learning, focusing on effective use of data structures in coding. This comprehensive program covers essential data structures, algorithms, and includes mentorship and career support.

Additionally, for more practice in data structures, you can explore these resources:

  • Java Data Structures Mastery - Ace the Coding Interview : A free eBook to advance your Java skills, focusing on data structures for enhancing interview and professional skills.
  • Foundations of Java Data Structures - Your Coding Catalyst : Another free eBook, diving into Java essentials, object-oriented programming, and AI applications.

Visit LunarTech's website for these resources and more information on the bootcamp .

Connect with Me:

  • Follow me on LinkedIn for a ton of Free Resources in CS, ML and AI
  • Visit my Personal Website
  • Subscribe to my The Data Science and AI Newsletter

About the Author

I'm Vahe Aslanyan, deeply engaged in the intersecting worlds of computer science, data science, and AI. I invite you to explore my portfolio at vaheaslanyan.com, where I showcase my journey in these fields. My work focuses on blending full-stack development with AI product optimization, all fueled by a passion for innovative problem-solving.


I've had the privilege of contributing to the launch of a well-regarded data science bootcamp and collaborating with some of the best minds in the industry. My goal has always been to raise the bar in tech education, making it accessible and standard for everyone.

As we conclude our journey here, I want to thank you for your time and engagement. Sharing my professional and academic experiences in this book has been a rewarding experience. I appreciate your involvement and look forward to seeing how it helps you advance in the tech world.

I'm Vahe Aslanyan, dedicated to making AI and data science education inclusive and accessible. I guide developers towards clear tech understanding in software engineering.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started


Java Programming Case Study Examples

  • in Talent Insight

If you are an HR professional looking for talented Java programmers, then you are in the right place. This article will provide you with some great case study examples that showcase the skills and expertise of top Java programmers.

Importance of Case Studies for HR Professionals

Case studies are an essential tool for HR professionals when hiring top talent. They provide a deeper understanding of a candidate’s skills, knowledge, and experience, which is not always possible through resumes or interviews. By reviewing case studies, HR professionals can evaluate a candidate’s ability to solve complex problems and develop innovative solutions.

Here are some excellent case study examples that demonstrate the skills and expertise of top Java programmers:

  • Google Maps : Google Maps is one of the most popular navigation applications in the world. It is built using Java and provides real-time traffic updates, street views, and satellite imagery. Google Maps is an excellent example of how Java programming can be used to develop complex and innovative solutions.
  • Amazon : Amazon is the world’s largest online retailer, and its website is built using Java. The website handles millions of transactions every day, and its success is a testament to the reliability and scalability of Java programming.
  • Netflix : Netflix is a streaming platform that delivers movies and TV shows to millions of users worldwide. It uses Java programming to create personalized recommendations, manage user profiles, and optimize streaming quality.

Why Choose Algobash?

At Algobash, we specialize in connecting HR professionals with top Java programmers. Our platform features a comprehensive database of talented programmers who have been rigorously tested and vetted. By using Algobash, you can save time and money while finding the perfect candidate for your organization.

Best Assessment Types for Effective Employee Selection

Trends and innovations in the world of employee assessment, shehacks 2024 to accelerate women’s empowerment.


Java Interview Preparation Guide

Have a planned job interview in the coming days? This guide having 200+ questions will help you revise most asked Java interview questions from beginner level to experienced and asked in small startups to big corporates.

This guide starts with basic core java questions and progresses towards more advanced topics. I have tried to add answers to most questions and links to resources to read more about the subject.

It is not possible to include every possible question in this guide, so I have included some good resources at the end of this interview guide.

1. Core Java Questions

1.1. core java interview questions.

Generally, each interviewer will start with core Java concepts before jumping onto more advanced topics. The reason is simply that he wants you to feel comfortable.

These questions may range from simple object-oriented principles to most used Java classes such as String or HashMap . I refer to them as simple questions because they test your foundation, basic knowledge, and curiosity to go deeper into details. Try to answer all such questions. They are low-hanging fruits that you should not miss.

These questions will help you quickly revise most asked core java questions in a very short period.

1.2. Object Initialization Best Practices

In Java, object initialization is considered a heavy process and you are expected to know how each newly created object affects memory and application performance. A simple example is Java wrapper classes which look very easy from the outside, just like primitives, but they are not as easy as they look. Learn how Java helps you with the internal caching of objects inside wrapper classes such as Double , Long or Integer .

1.3. How HashMap Works in Java

HashMap is probably the most discussed and controversial topic if you are appearing in any junior or mid-level interview. You can face any interview question related to HashMap if you know how hashmap works internally? This post will help you in answering some good questions like –

  • How HashMap store key-value pairs?
  • How HashMap resolve conflicts?
  • How hashCode() and equals() method are used in HashMap?
  • Impact of random/fixed hashCode() value for key?
  • Using HashMap in multi-threaded environment?

1.4. Design a Good Key for HashMap

So you know now how HashMap works? Now learn about designing a good key for HashMap . This question is an excellent way to test if you correctly understood HashMap’s internal working. This will help you in answering questions like –

  • Why String is a good key for HashMap?
  • How you will design a class to be used as key?
  • Will you override hashCode() method in Key class? What will be impacts?
  • Write the syntax for a class which can be HashMap key object?

1.5. Questions on ConcurrentHashMap

HashMap is not thread-safe. We can use HashTable in concurrent applications, but it impacts the application performance. So we have ConcurrentHashMap . It is the concurrent version of HashMap which gives the same performance as HashMap and it is also thread-safe at the same time.

You are expected to know ConcurrentHashMap in more depth. There are plenty of concepts in this single class alone.

1.6. Java Collections Interview Questions

Should I recommend you to prepare the Collection framework and all of its main classes? I guess you are already intelligent enough.

Any interview (junior and mid-level) will be incomplete if there are no questions related to the Collections framework. It truly tests your programming skills and your knowledge of core Java APIs. Questions may be as simple as Collections hierarchy to difficult ones such as Queue and Stacks. Here is a list of such commonly asked collections interview questions –

  • Explain Collections hierarchy?
  • Difference between Set and List ?
  • Difference between Vector and ArrayList ?
  • Difference between HashMap and HashTable?
  • Difference between Iterator and ListIterator ?
  • Why Map interface does not extend Collection interface?
  • How to convert an array of String to ArrayList?
  • How to reverse the list?
  • How HashSet store elements?
  • Can a null element added to a TreeSet or HashSet ?
  • What are IdentityHashMap and WeakHashMap ?
  • When to use HashMap or TreeMap?
  • How to make a collection read only?
  • How to make a collection thread safe?
  • What is difference between fail-fast and fail-safe ?
  • What is Comparable and Comparator interface?
  • What are Collections and Arrays class?
  • What is Queue and Stack ? List their differences?

1.7. What is polymorphism in Java?

In simple words, polymorphism is the ability by which we can create functions or reference variables that behave differently in a different programmatic context. Polymorphism is one of the major building blocks of object-oriented programming along with inheritance, abstraction, and encapsulation.

Learn the concept in more detail with examples. This is just so much important.

1.8. What is abstraction in Java?

In the previous question, you learned polymorphism. Now it’s time to expand your knowledge by understanding abstraction as well. A very complicated topic for any Java interview.

1.9. Abstraction vs. Encapsulation?

Knowing the difference between abstraction and encapsulation is the key to profoundly understanding both concepts. You cannot learn either of both in isolation. They walk along in Java, so we must understand them collectively.

In this post, I have explained encapsulation and differentiated it with abstraction. A must-read interview question before moving forward.

1.10. Difference between Interfaces and Abstract Classes?

There has been obvious separation abstract classes and interfaces in Java since the language was born. But a lot has changed since Java 8 release. Its one of the core concepts was functional interfaces.

Functional interfaces completely changed how we look at both fundamental building blocks of Java language. You cannot skip this question if your resume says you work on Java 8. In the linked tutorial, I will show you the correct scenarios, which will help you crack some complex interview questions and case studies.

1.11. Enum interview questions

The enum has been a core building block for a long time. They can be seen in the most popular Java libraries. They help you in managing constants in a more object-oriented manner. They look straightforward but they hide lots of complexity if you dig deep enough. Some enum questions maybe –

  • Difference between enum vs. Enum class?
  • Can enum be using with String?
  • Can we extend enum?
  • Write syntax of enum?
  • How to implement reverse-lookup in enum?
  • What is EnumMap and EnumSet?

1.12. Java Serialization and Serializable Interface

Suppose you are preparing for a Java interview with a Telecom company or any such domain that uses serialization in their application flows. In that case, you will highly benefit from this tutorial. There is a very good list of do’s and dont’s with serialization in Java. Possible questions may include –

  • What is serialVersionUID ?
  • What is readObject and writeObject ?
  • ow you will serialize and deserialize a class?
  • How you will make changes to a class so that serialization should not break?
  • Can we serialize static fields?

1.13. Java Main Method

Ever wondered why main() is public, static and void? It’s not a very frequently asked interview question in Java interviews but still, I will recommend reading this post to answer these questions:

  • Java main method syntax?
  • Why main method is public?
  • Why main method is static?
  • Why main method is void?
  • What happens internally when you invoke main method?

1.14. Java Object Clone

Object cloning in Java is not an easy concept. I took a long time to understand cloning in Java. It seems simple; use the Cloneable interface and override clone() method. But wait, there is much more to tell and ask in an interview. e.g.

  • How clone() method works?
  • What is shallow copy in Java?
  • What are copy constructors?
  • What is deep copy in Java?
  • Different ways to create deep copy of an object?

1.15. What is CountDownLatch?

Since Java 5, java.uti.concurrent package has lots of useful but complex classes to work on concurrent applications. CountDownLatch is one of those classes which are highly asked in any Java interview with big corporates. In this tutorial, CountDownLatch is explained with examples and concepts around it.

1.16. Why Strings are Immutable?

This question is a prevalent interview question at the beginner level. Basically, the interviewer tests your knowledge around the String class, string pool , memory areas and object creation.

I wrote this post separately because the concept is so much important. In fact, immutability is itself a very important concept in Java. Feel the tip of the iceberg.

1.17. How to Make a Java class immutable?

An immutable class is one whose state can not be changed once created. There are certain guidelines to create a class immutable in Java and you must know them to answer this question correctly.

Be aware that immutability is important in many design aspects and is a recommended design pattern by all Java gurus. Learn to make a java class immutable, how it benefits the application design and be prepared to encounter more software design interview questions on it.

2. Concurrency Questions

2.1. what is thread safety.

Defining thread safety is surprisingly tricky. At the heart of any reasonable definition of thread-safety is the concept of correctness. So, before understanding the thread-safety, we should first understand this “correctness”.

In this must-read Java tutorial, clear your doubts and be ready to answer some popular interview questions. e.g.

  • What is correctness in thread safety?
  • Give an example of thread-safe class?
  • How you will design a thread safe Java class?
  • Are immutable classes thread safe?

2.2. Object level locking vs. class level locking

At the heart of concurrency , there lie the concepts of object locking. Locking happens at instance level as well as class level.

  • Object level locking is mechanism when you want to synchronize a non-static method or non-static code block such that only one thread will be able to execute the code block on given instance of the class. This should always be done to make instance level data thread safe.
  • Class level locking prevents multiple threads to enter in a synchronized block in any of all available instances on runtime. This means if in runtime there are 100 instances of DemoClass , then only one thread will be able to execute demoMethod() in any one of the instances at a time, and all other instances will be locked for other threads. This should always be done to make static data thread safe.

Understand the whole concept in detail in this tutorial.

2.3. Difference between “implements Runnable” and “extends Thread”?

This question is also a very popular interview question. If your role demands creating designs for concurrent applications, you must know the correct answer to this question. The answer to this question decides which construct you choose between both.

Also, it will help you in answering fundamental questions such as –

  • Difference between Thread and Runnable?
  • Write Java code to create thread with Runnable interface?
  • Which method should be preferred between both?

2.4. Compare and Swap [CAS] Algorithm

This question is targeted towards mid-level or senior developers. This requires a deep understanding of other concurrent concepts before answering this question. So It is an excellent way to test deep knowledge in Java concurrency.

  • What is optimistic and pessimistic locking?
  • What is compare and swap algorithm?
  • What is an atomic operation?
  • How AtomicInteger and AtomicLong works?

2.5. What is Fork/Join framework?

This is not a new concept but is now used in multiple ways since Java 8. Fork-Join breaks the task at hand into mini-tasks until the mini-task is simple enough that we can solve it without further breakups. It’s like a divide-and-conquer algorithm. One important concept to note in this framework is that ideally no worker thread is idle. They implement a work-stealing algorithm in that idle workers steal the work from those workers who are busy.

Learn this sweet and very efficient algorithm to better prepare for your next interview.

2.6. What is ThreadPoolExecutor?

In concurrent Java applications, creating a thread is an expensive operation. And if you start creating a new thread instance every time to execute a task, application performance will degrade indeed. ThreadPoolExecutor solves this problem.

ThreadPoolExecutor separates the task creation and its execution. With ThreadPoolExecutor, you only have to implement the Runnable objects and send them to the executor. It is responsible for their execution, instantiation, and running with necessary threads.

Read how ThreadPoolExecutor solves various problems and how it is used with BlockingQueue .

2.7. Java executor framework tutorial and best practices

You will learn the executors in the previous link, but there are certain things you need to know for using these executors effectively in terms of performance.

2.8. How to write a deadlock and resolve in Java

It can come in the form of a puzzle. Better be ready for it. The interviewer may test your concurrency knowledge and your deep understanding on wait() and notify() method calls.

Be ready with one deadlock source-code example at your fingertips. You will need it.

3. Questions on Patterns and Practices

3.1. best practices guides.

A list of highly recommended best practices. They will open up your mind to think in different directions. In short, they will sharpen your weapon for your next java interview.

3.2. Checkout some Puzzles

Solve these puzzles and play around them. You never know what will come in your way on a bad day.

3.3. Brush up Design Patterns

Aiming for a senior position in your next java interview, you MUST know these design patterns to handle complex application design issues, which are usually discussed in all interviews nowadays.

3.4. Random browsing on Core Java Topics

Still got the strength to read more. Browse more java interview questions here.

4. Spring Framework Questions

4.1. spring core interview questions.

I have tried to collect some top spring core interview questions which you face into your next technical interview e.g.

  • What is Inversion of Control (IoC) and Dependency Injection (DI)?
  • Difference between BeanFactory and ApplicationContext?
  • What is Spring Java-Based Configuration?
  • Explain Spring Bean lifecycle?
  • What are different Spring Bean Scopes?
  • Are Singleton beans thread safe in Spring Framework?
  • Explain different modes of bean autowiring?
  • Explain @Qualifier annotation with example?
  • Difference between constructor injection and setter injection?
  • Name some of the design patterns used in Spring Framework?

4.2. Spring AOP Interview Questions

Spring AOP (Aspect Oriented Programming) compliments OOPs in the sense that it also provides modularity. In OOPs, the key unit is Objects, but in AOP key unit is aspects or cross-cutting concerns such as logging and security. AOP provides the way to dynamically add the cross-cutting concern before, after or around the actual logic using simple pluggable configurations

Go through these most asked AOP interview questions-

  • Difference between concern and cross-cutting concern?
  • What are the available AOP implementations?
  • What are the different advice types in spring AOP?
  • What is Spring AOP Proxy?
  • What is Joint point and Point cut ?
  • What is aspect weaving?

4.3. Spring MVC Interview Questions

These Spring MVC interview questions and answers have been written to help you prepare for the interviews and quickly revise the concepts in general. I will strongly suggest you go deeper into each concept if you have extra time. In general, you should be able to answer these questions-

  • What is MVC Architecture?
  • What is DispatcherServlet and ContextLoaderListener?
  • How to use Java based configuration?
  • How can we use Spring to create Restful Web Service returning JSON response?
  • Difference between <context:annotation-config> vs <context:component-scan>?
  • Difference between @Component, @Controller, @Repository & @Service annotations?
  • How does Spring MVC provide validation support?
  • What is Spring MVC Interceptor and how to use it?
  • How to handle exceptions in Spring MVC Framework?
  • How to achieve localization in Spring MVC applications?

5. Test Your Knowledge

So far you have been learning all different concepts in Java which can come in front of you in the form of interview questions. It’s time to see whether you are prepared or not. Please go through some real questions asked from Sreenath Ravva, in his interview with Oracle Corporation.

  • Can you just start telling about your self and your project?
  • What is abstraction and encapsulation in java ?
  • Method Overloading rules?
  • Widening and narrowing in java?
  • Can I have only try block in code?
  • Threads : producer and consumer problem?
  • Why wait(), notify() and notifyAll() are defined in Object class?
  • Can we override wait() or notify() methods?
  • Difference between wait(), sleep() and yield()?
  • Explain about join() method in thread class?
  • Have you faced out of memory error? If yes how you fixed ? Tell different scenarios why it comes?
  • Database connection leakage?
  • Write a program to swap two numbers with out using third variable?
  • Write a program to sort an array and remove duplicates?
  • Write a program on Singleton?
  • Write a program to merge two arrays?
  • What is the use of final and finally keywords?
  • Can I declare class as static or private?
  • Why you want to change the company?

6. Recommended Books

6.1. java puzzlers.

Every programming language has its quirks. This book reveals the oddities of the Java programming language through programming puzzles.

6.2. Java Concurrency in Practice

Java Concurrency in Practice provides you with the concepts and techniques needed to write safe and scalable Java programs for today’s–and tomorrow’s–systems.

6.3. Effective Java by Joshua Bloch

Effective Java, Second Edition, brings together seventy-eight indispensable programmer’s rules of thumb: working, best-practice solutions for the programming challenges you encounter daily.

Happy Learning !!

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Tutorial Series

Privacy Policy

REST API Tutorial

Jinal Desai

DevOps, GCP, etc.

  • 50 Java Interview Questions + 30 Scenario Based Q&A

This is post 2 of 8 in the series “Programming Language Interview Questions”

  • Object Oriented Programming (OOPs) Interview Questions
  • Cracking the Code: 200 Interview Q&A for Software Developers
  • Performance and Optimization Interview Questions
  • Caching Interview Questions and Answers
  • Error Handling and Debugging Interview Questions
  • C Programming Language Interview Questions
  • C++ Programming Interview Questions

Table of Contents


Java is one of the most popular and widely used programming languages today. It is important for aspiring Java developers to be well-prepared for technical interviews which typically involve many Java programming questions.

The interviewers often ask a mix of theoretical Java questions to test the conceptual knowledge and practical programming questions to evaluate the coding skills. In this article, we provide a compilation of commonly asked Java interview questions and sample answers to help candidates prepare effectively.

The questions cover core Java basics, OOP concepts, classes and objects, methods and constructors, access modifiers, inheritance, polymorphism, abstraction, interfaces, Java collections, exception handling, multithreading and concurrency. There are also scenario-based Java questions that can be asked in interviews to check how candidates can apply the language features to build real-world applications.

50 interview questions and answers

1. What is Java? Java is a high-level, object-oriented programming language. It is a general-purpose concurrent and class-based language that is designed to have as few implementation dependencies as possible.

2. What are objects and classes in Java? Objects are basic building blocks in Java that contains state and behavior. Classes are templates that define objects and their behavior.

3. What is JVM and JRE? JVM (Java Virtual Machine) is the runtime environment for Java programs. It converts Java bytecode into machine language. JRE (Java Runtime Environment) is the implementation of JVM that provides core libraries and other components to run Java programs.

4. Explain the platform independence of Java. Java is compiled to bytecode that can run on any platform with a JVM. The JVM interprets the bytecode into native machine code. This makes Java platform independent.

5. What are constructors in Java? Constructors are special methods in Java that are used to initialize objects. The constructor is invoked when an object of a class is created. It has the same name as the class and does not have a return type.

6. What is method overloading and overriding in Java? Method overloading is defining methods with the same name but different parameters. Overriding is providing a specific implementation of a method already defined in the parent class.

7. What is abstraction in Java? Abstraction refers to hiding the implementation details and exposing only the functionality to users. Abstract classes and interfaces are used to achieve abstraction in Java.

8. What are Java packages? Packages in Java are collections of related classes and interfaces that are bundled together. Packages provide namespace management and access control in Java.

9. What is final keyword in Java? The final keyword is used to apply restrictions on classes, methods and variables. Final class cannot be inherited, final method cannot be overridden and final variable value cannot be changed.

10. What is static in Java? Static is a keyword in Java used to denote a class member belongs to a type rather than to an instance. Static members can be used without creating an object of class.

11. What is encapsulation in Java? Encapsulation is the mechanism of wrapping data (variables) and code acting on data (methods) together as a single unit. In Java, encapsulation is achieved by making fields private and providing public setter and getter methods.

12. What is inheritance in Java? Inheritance represents parent-child relationship between classes in Java. It allows a derived class to inherit commonly used state and behavior from its parent class.

13. What is polymorphism in Java? Polymorphism means ability to take different forms. In Java, polymorphism allows assigning a variable and method call to take different forms or classes. Method overloading and overriding uses polymorphism.

14. What is JIT compiler in Java? JIT (Just-In-Time) compiler in Java converts bytecode into native machine code at runtime when required by the program. It improves performance by compiling bytecode lazily.

15. What is multithreading in Java? Multithreading allows concurrent execution of multiple parts of a Java program. The main ways to create threads in Java are extending Thread class and implementing Runnable interface.

16. Explain different ways to create a thread in Java. There are two ways to create a thread in Java – 1. Extending Thread class 2. Implementing Runnable Interface. Runnable is preferred because Java does not support multiple inheritance.

17. What are access modifiers in Java? Java provides access control through public, protected, private and default modifiers. Public grants access from anywhere. Private restricts access to the class itself. Default and protected have specialized uses.

18. What is Collections Framework in Java? Java Collections Framework provides ready-made architecture to store and manipulate group of objects. It contains interfaces like List, Set, Queue and classes like ArrayList, LinkedHashSet, PriorityQueue etc.

19. What are different types of inner classes in Java? – Nested (static) inner class – Inner class – Local inner class – Anonymous inner class

They allow logical grouping of classes and interfaces and access to the outer class.

20. What is Java API and where is it documented? Java API (Application Programming Interface) is a collection of pre-built packages, classes and interfaces in Java. It is documented at https://docs.oracle.com/en/java/javase/index.html

21. What is JDBC API in Java? JDBC (Java Database Connectivity) is an API used to connect and execute queries to a database from Java. JDBC provides a set of interfaces that allows connectivity to relational databases.

22. What are the basic interfaces of JDBC API? The core interfaces of JDBC API are – Driver, Connection, Statement and ResultSet that allows connecting and interacting with a database.

23. What are the different types of JDBC drivers? There are 4 types of JDBC drivers: 1. JDBC-ODBC bridge driver 2. Native API driver (partially java driver) 3. Network Protocol driver (fully java driver) 4. Thin driver (fully java driver)

24. What is singleton class in Java and how can we make a class singleton? Singleton class means that only one instance of the class can be created. Singleton pattern involves a single private constructor, a static variable and a static public method that returns the instance.

25. What is Java Serialization API? Java Serialization API provides a standard mechanism to serialize objects to stored or transmitted across streams. Only serializable objects can be serialized.

26. How can we convert bytes to objects and vice-versa in Java? We can convert bytes to objects and vice-versa using serialization and deserialization in Java. ObjectOutputStream is used to convert objects to bytes and ObjectInputStream is used to recreate objects from bytes.

27. What are anonymous inner classes in Java? Anonymous inner classes are inner classes without a name declared and instantiated in a single expression using the new keyword. They are used for inline implementation of interfaces.

28. What is reflection API in Java and why is it useful? Java reflection API allows inspecting and modifying runtime behavior of classes at runtime. It is useful to introspect objects and call methods dynamically at runtime without knowing the names at compile time.

29. What is autoboxing and unboxing in Java? Autoboxing is automatic conversion of primitive types to object wrapper classes. Unboxing is the reverse process of converting wrapper objects to primitives. They were introduced in Java 1.5.

30. What is final, finally and finalize in Java? final is a keyword – final class can’t be inherited, final method can’t be overridden, final variable value can’t change. finally is a block – used with try/catch to put code that executes always. finalize is a method – called by Garbage collector before object is collected.

31. What is try-with-resources in Java? try-with-resources is a way to automatically close resources after usage without needing an explicit finally block. Any class that implements AutoCloseable interface can be used in try-with-resources.

32. What is multi-catch block in Java? A multi-catch block allows handling multiple exceptions in a single catch block instead of using multiple catch blocks for different exceptions. The catch parameter is specified using pipe (|) symbol.

33. What are the advantages of Java? Simple, Object-Oriented, Portable, Platform independent, Secured, Robust, Architecturally neutral, Interpreted, High Performance, Multithreaded, Distributed, Dynamic

34. What are the disadvantages of Java? Not suitable for low-level programming. Limited speed. No unsigned data type. Backward incompatible.

35. What is namespace in Java? Namespace is a naming system to organize classes in Java packages. It resolves naming collisions and confusions and allows fully qualified name to uniquely identify classes, interfaces etc.

36. What is JIT compiler in Java? JIT (Just-In-Time) compiler is used to improve the performance. It converts bytecode into native machine language when required by the running Java program.

37. What is the difference between path and classpath variables? PATH is an environment variable used by operating system to locate executables. Classpath is specific to Java and used by JVM to locate Java bytecode files (classes).

38. What is Anonymous inner class in Java? Anonymous inner class is an inner class without a name declared and instantiated in a single expression using the new operator. Commonly used for simplified event handling.

39. What is difference between Heap and Stack memory? Heap memory is used by all parts of the application whereas stack memory is used only by one thread of execution. Objects are created in Heap, Stack is used for local primitive variables and references to objects in Heap.

40. What is Java String Pool? Java String Pool refers to collection of Strings stored in heap memory. String literals and constants are stored in the String pool for reuse to optimize memory usage.

41. How is a string immutable in Java? In Java, string objects are immutable meaning their state cannot be changed once created. Whenever changes are made to a string, a new instance is created. This optimizes performance by reusing strings from pool.

42. What is ThreadPoolExecutor in Java? ThreadPoolExecutor is a thread pool implementation added from Java 5 that provides more configurable thread pools to execute tasks. It allows configuring pool size, rejection policies, thread factories etc.

43. What is Java Memory Model? It is a specification that describes the shared memory system defined by the Java programming language and virtual machine including visibility and atomicity guarantees on shared data.

44. What is memory leak in Java? Memory leak occurs when objects are no longer used by the application but Garbage Collector fails to recognize them as unused. This results in out of memory errors if too many objects are unreferenced.

45. What is shallow copy and deep copy in Java? Shallow copy is copying an object’s field references into another instance. Deep copy is making separate copy of all the objects in the original object graph.

46. What are transient and volatile keywords in Java? transient – skip field during serialization, volatile – field will not be cached and always read from main memory.

47. What is Executor Framework in Java? The Executor framework in Java provides an abstraction over management of threads. Executors can schedule asynchronous tasks and control concurrency transparently using thread pool.

48. Explain Generics in Java? Generics allow defining type-safe classes, interfaces and methods which work with different types while avoiding duplicity. Generics work only with reference types in Java.

49. What is Comparable and Comparator interface in Java? Comparable is used to provide natural ordering of objects of a class. Comparator provides custom ordering and added flexibility of sorting objects.

50. Explain different ways to iterate over a collection in Java? Iterating collections can be done through Iterator, for-each loop, forEach(), forEachRemaining() and ListIterator. Iterator allows removing elements during iteration while ListIterator can iterate in reverse.

30 scenarios based interview questions and answers

1. How will you find if a string contains only digits in Java? I can use matches() method of string to match the given string against a regular expression that matches digits like below:

String str = “123”; boolean result = str.matches(“[0-9]+”);

2. How can you swap two numbers without using a temporary variable in Java? We can use arithmetic operators to swap two numbers:

int a = 5; int b = 10;

a = a + b; b = a – b; a = a – b;

3. How can you reverse a string in Java without using any library method? We can write a for loop which starts from the end of the string and appends each character to form the reverse string.

StringBuilder reversed = new StringBuilder();

for(int i = str.length()-1; i >= 0 ; i–){ reversed.append(str.charAt(i)); }

4. How can you find duplicate elements in an array in Java? Iterate through array and store elements as key in a HashMap. If element is already present, print it as duplicate. Time complexity is O(n) and space is O(n).

5. How can you find the largest and smallest number in an unsorted integer array in Java? Iterate through array keeping track of min and max element so far. Time complexity is O(n) to traverse array once.

6. How can you remove duplicates from an array without using any library in Java? Add elements to HashSet which lets only unique elements. Then add set back to array. Time complexity is O(n).

7. How can you find the factorial of a number in Java? Factorial can be calculated using recursion. Base case is f(0) = f(1) = 1. General case is f(n) = n * f(n-1).

8. How can you check if two string are anagrams in Java? 1. Check if length is same 2. Convert strings to char array 3. Sort the char arrays 4. Check if both arrays are equal

9. How can you design a vending machine in Java? Vending machine would have attributes like currentQuantity, pricePerItem. Methods like insertMoney(), selectItem(), dispenseItem(), giveChange() which implement the vending logic.

10. How can you check if a string contains only alphabets in Java? Use matches() with regex “[a-zA-Z]+” to check if string has only alphabets.

11. How can you find whether a year is leap year or not in Java? If year is divisible by 4 and not 100, or divisible by 400, then it is a leap year.

if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) System.out.println(“Leap year”); else System.out.println(“Not a leap year”);

12. How can you swap two Strings without using a temporary variable? We can use StringBuilder’s append() method to swap strings.

string1 = string1.concat(string2); string2 = string1.substring(0, string1.length()-string2.length()); string1 = string1.substring(string2.length());

13. How can you find the middle element of a linked list in Java? – Iterate through linked list to find total length – Traverse till length/2 to find middle element

14. How can you reverse a linked list iteratively and recursively?

1. Initialize prev, current and next 2. In loop, make next = current.next, current.next = prev, prev = current

1. Base case: head or head.next is null 2. Recursively call reverse() on head.next 3. Attach head to the end of reversed list

15. How can you find if a linked list contains a cycle in Java? Use two pointers – fast that moves 2 nodes ahead and slow that moves 1 node. If cycle exists, fast and slow will meet at some node.

16. How can you implement a stack using array and linked list?

Array: Use array, top pointer and push(), pop() operations. Linked List: Use linked list node with next pointer. top pointer and push(), pop() operations.

17. How can you implement a queue using array in Java? Use array, front and rear index, enqueue() and dequeue() operations. Handle queue full and empty conditions.

18. How can you find all permutations of a String in Java? Use recursion. For each char, fix it and find permutations of remaining chars. Add fixed char to beginning and append permutations.

19. How can you design a parking lot using OOPS in Java? ParkingLot class has attributes like totalSpots, availableSpots. Car class has regNo, color etc. Entry and Exit classes manage parkings. Use ArrayList to store parked cars.

20. How can you implement autoboxing and unboxing in your own classes? Autoboxing: Have constructors that take primitive types. Unboxing: Provide get methods that return primitives.

21. How can you find the length of a linked list iteratively and recursively?

Iterative: Initialize length to 0. Traverse linked list and increment length.

Recursive: Length(head) if head == null return 0 else return 1 + length(head.next)

22. How can you find the height of a binary tree in Java? Recursively calculate height of left and right subtrees. Height is max of left height and right height plus 1 for root.

23. How is Bubble Sort algorithm implemented in Java? Compare adjacent elements, swap if currentElement > nextElement. Largest element bubbles up towards end. Repeat until sorted.

24. How can you search for an element in a binary search tree in Java? Start from root and traverse left if element is less than current node otherwise right. Return node if matching element is found.

25. How is Inheritance implemented in Java? Using extends keyword. Single inheritance is supported. Child class inherits properties and methods except private from Parent.

26. How will you implement thread synchronization in Java? 1. Using synchronized keyword 2. Using concurrent collections 3. Using Lock interface 4. Using atomic classes from java.util.concurrent.atomic package

27. How can you avoid deadlock in Java? – Avoid nested locks – Using lock ordering – Using lock timeouts – Avoiding resource sharing between threads

28. How will you store different data types in ArrayList? ArrayList can store only objects. Primitive data types need to be converted to object wrappers like Integer, Character etc.

29. How can you improve performance of ArrayList in Java? Initialise ArrayList with optimal initial capacity to avoid resizing. Use ensureCapacity() before adding large elements to avoid reindexing.

30. How will you implement a HashMap in Java? Use array of LinkedList for chaining. Compute index using hashCode() and compress to fit array. Handle collisions through linked list chaining.

Preparing a strong set of Java interview questions is crucial for aspiring Java developers to successfully clear the technical screening rounds. This collection of 50 Java theory questions and 30 practical scenario-based questions covers a wide range of topics and concepts typically assessed in Java interviews.

Learning the fundamentals and practicing these questions will help candidates master Java programming principles and be able to write code to solve problems. The sample answers provided illustrate how to structure and present your solutions to interviewers to best highlight your Java skills. With thorough preparation on these aspects, developers can confidently tackle Java interview questions and excel in their tech job interviews.

Crack the top 40 Java coding interview questions

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Java remains a popular language across the world. Especially in financial fields, Java’s scalability and efficiency keep it in-demand with interviewers in a variety of famous companies like Goldman Sachs, eBay, and Google .

Today, we’ll help you prepare for your upcoming coding interview at these and other popular eCommerce companies by reviewing the top 40 Java questions asked by interviewers. By the end, you’ll have the experience to walk into any Java interview with confidence.

Let’s get started!

Here are the types of questions we’ll cover today:

  • Big O Notation

Data Structures

Dynamic programming.

  • Mixed Subject Questions

Wrapping up and next steps

Answer any Java interview problem by learning the patterns behind common questions.


Interview Questions

Describe and compare fail-fast and fail-safe iterators. Give examples.

The main distinction between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated. Fail-safe iterators allow this; fail-fast iterators do not.

Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified (i.e., upon realizing that a member has been added, modified, or removed) and will throw a ConcurrentModificationException . Some examples include ArrayList , HashSet , and HashMap (most JDK1.4 collections are implemented to be fail-fast).

Fail-safe iterates operate on a cloned copy of the collection and therefore do not throw an exception if the collection is modified during iteration. Examples would include iterators returned by ConcurrentHashMap or CopyOnWriteArrayList .

ArrayList , LinkedList , and Vector are all implementations of the List interface. Which of them is most efficient for adding and removing elements from the list? Explain your answer, including any other alternatives you may be aware of.

Of the three, LinkedList is generally going to give you the best performance. Here’s why:

ArrayList and Vector each use an array to store the elements of the list. As a result, when an element is inserted into (or removed from) the middle of the list, the elements that follow must all be shifted accordingly. Vector is synchronized, so if a thread-safe implementation is not needed, it is recommended to use ArrayList rather than Vector.

LinkedList , on the other hand, is implemented using a doubly linked list. As a result, an inserting or removing an element only requires updating the links that immediately precede and follow the element being inserted or removed.

However, it is worth noting that if performance is that critical, it’s better to just use an array and manage it yourself, or use one of the high performance 3rd party packages such as Trove or HPPC .

Why would it be more secure to store sensitive data (such as a password, social security number, etc.) in a character array rather than in a String?

In Java, Strings are immutable and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected. Therefore, even after you’re done processing the string value (e.g., the password), it remains available in memory for an indeterminate period of time thereafter (again, until being garbage collected) which you have no real control over. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and exploit it.

In contrast, if you use a mutable object like a character array, for example, to store the value, you can set it to blank once you are done with it with confidence that it will no longer be retained in memory.

Apply to Join Toptal's Development Network

and enjoy reliable, steady, remote Freelance Java Developer Jobs

What is the ThreadLocal class? How and why would you use it?

A single ThreadLocal instance can store different values for each thread independently. Each thread that accesses the get() or set() method of a ThreadLocal instance is accessing its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or transaction ID). The example below, from the ThreadLocal Javadoc , generates unique identifiers local to each thread. A thread’s id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

What is the volatile keyword? How and why would you use it?

In Java, each thread has its own stack, including its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables into its own stack. The volatile keyword basically says to the JVM “Warning, this variable may be modified in another Thread”.

In all versions of Java, the volatile keyword guarantees global ordering on reads and writes to a variable. This implies that every thread accessing a volatile field will read the variable’s current value instead of (potentially) using a cached value.

In Java 5 or later, volatile reads and writes establish a happens-before relationship, much like acquiring and releasing a mutex.

Using volatile may be faster than a lock, but it will not work in some situations. The range of situations in which volatile is effective was expanded in Java 5; in particular, double-checked locking now works correctly.

The volatile keyword is also useful for 64-bit types like long and double since they are written in two operations. Without the volatile keyword you risk stale or invalid values.

One common example for using volatile is for a flag to terminate a thread. If you’ve started a thread, and you want to be able to safely interrupt it from a different thread, you can have the thread periodically check a flag (i.e., to stop it, set the flag to true ). By making the flag volatile, you can ensure that the thread that is checking its value will see that it has been set to true without even having to use a synchronized block. For example:

Compare the sleep() and wait() methods in Java, including when and why you would use one vs. the other.

sleep() is a blocking operation that keeps a hold on the monitor / lock of the shared object for the specified number of milliseconds.

wait() , on the other hand, simply pauses the thread until either (a) the specified number of milliseconds have elapsed or (b) it receives a desired notification from another thread (whichever is first), without keeping a hold on the monitor/lock of the shared object.

sleep() is most commonly used for polling, or to check for certain results, at a regular interval. wait() is generally used in multithreaded applications, in conjunction with notify() / notifyAll() , to achieve synchronization and avoid race conditions.

Tail recursion is functionally equivalent to iteration. Since Java does not yet support tail call optimization, describe how to transform a simple tail recursive function into a loop and why one is typically preferred over the other.

Here is an example of a typical recursive function, computing the arithmetic series 1, 2, 3…N. Notice how the addition is performed after the function call. For each recursive step, we add another frame to the stack.

Tail recursion occurs when the recursive call is in the tail position within its enclosing context - after the function calls itself, it performs no additional work. That is, once the base case is complete, the solution is apparent. For example:

Here you can see that a plays the role of the accumulator - instead of computing the sum on the way down the stack, we compute it on the way up, effectively making the return trip unnecessary, since it stores no additional state and performs no further computation. Once we hit the base case, the work is done - below is that same function, “unrolled”.

Many functional languages natively support tail call optimization, however the JVM does not. In order to implement recursive functions in Java, we need to be aware of this limitation to avoid StackOverflowError s. In Java, iteration is almost universally preferred to recursion.

How can you swap the values of two numeric variables without using any other variables?

You can swap two values a and b without using any other variables as follows:

How can you catch an exception thrown by another thread in Java?

This can be done using Thread.UncaughtExceptionHandler .

Here’s a simple example:

What is the Java Classloader? List and explain the purpose of the three types of class loaders.

The Java Classloader is the part of the Java runtime environment that loads classes on demand (lazy loading) into the JVM (Java Virtual Machine). Classes may be loaded from the local file system, a remote file system, or even the web.

When the JVM is started, three class loaders are used: 1. Bootstrap Classloader: Loads core java API file rt.jar from folder. 2. Extension Classloader: Loads jar files from folder. 3. System/Application Classloader: Loads jar files from path specified in the CLASSPATH environment variable.

Is a finally block executed when an exception is thrown from a try block that does not have a catch block, and if so, when?

A finally block is executed even if an exception is thrown or propagated to the calling code block.

Output can vary, being either:

When designing an abstract class, why should you avoid calling abstract methods inside its constructor?

This is a problem of initialization order. The subclass constructor will not have had a chance to run yet and there is no way to force it to run it before the parent class. Consider the following example class:

This seems like a good start for an abstract Widget: it allows subclasses to fill in width and height , and caches their initial values. However, look when you spec out a typical subclass implementation like so:

Now we’ve introduced a subtle bug: Widget.cachedWidth and Widget.cachedHeight will always be zero for SquareWidget instances! This is because the this.size = size assignment occurs after the Widget constructor runs.

Avoid calling abstract methods in your abstract classes’ constructors, as it restricts how those abstract methods can be implemented.

What variance is imposed on generic type parameters? How much control does Java give you over this?

Java’s generic type parameters are invariant . This means for any distinct types A and B , G<A> is not a subtype or supertype of G<B> . As a real world example, List<String> is not a supertype or subtype of List<Object> . So even though String extends (i.e. is a subtype of) Object , both of the following assignments will fail to compile:

Java does give you some control over this in the form of use-site variance . On individual methods, we can use ? extends Type to create a covariant parameter. Here’s an example:

Even though longs is a List<Long> and not List<Number> , it can be passed to sum .

Similarly, ? super Type lets a method parameter be contravariant . Consider a function with a callback parameter:

forEachNumber allows Callback<Object> to be a subtype of Callback <Number> , which means any callback that handles a supertype of Number will do:

Note, however, that attempting to provide a callback that handles only Long (a subtype of Number ) will rightly fail:

Liberal application of use-site variance can prevent many of the unsafe casts that often appear in Java code and is crucial when designing interfaces used by multiple developers.

What are static initializers and when would you use them?

A static initializer gives you the opportunity to run code during the initial loading of a class and it guarantees that this code will only run once and will finish running before your class can be accessed in any way.

They are useful for performing initialization of complex static objects or to register a type with a static registry, as JDBC drivers do.

Suppose you want to create a static, immutable Map containing some feature flags. Java doesn’t have a good one-liner for initializing maps, so you can use static initializers instead:

Within the same class, you can repeat this pattern of declaring a static field and immediately initializing it, since multiple static initializers are allowed.

If one needs a Set , how do you choose between HashSet vs. TreeSet ?

At first glance, HashSet is superior in almost every way: O(1) add , remove and contains , vs. O(log(N)) for TreeSet .

However, TreeSet is indispensable when you wish to maintain order over the inserted elements or query for a range of elements within the set.

Consider a Set of timestamped Event objects. They could be stored in a HashSet , with equals and hashCode based on that timestamp. This is efficient storage and permits looking up events by a specific timestamp, but how would you get all events that happened on any given day? That would require a O(n) traversal of the HashSet , but it’s only a O(log(n)) operation with TreeSet using the tailSet method:

If Event happens to be a class that we cannot extend or that doesn’t implement Comparable , TreeSet allows us to pass in our own Comparator :

Generally speaking, TreeSet is a good choice when order matters and when reads are balanced against the increased cost of writes.

What are method references, and how are they useful?

Method references were introduced in Java 8 and allow constructors and methods (static or otherwise) to be used as lambdas. They allow one to discard the boilerplate of a lambda when the method reference matches an expected signature.

For example, suppose we have a service that must be stopped by a shutdown hook. Before Java 8, we would have code like this:

With lambdas, this can be cut down considerably:

However, stop matches the signature of Runnable.run ( void return type, no parameters), and so we can introduce a method reference to the stop method of that specific SomeBusyService instance:

This is terse (as opposed to verbose code) and clearly communicates what is going on.

Method references don’t need to be tied to a specific instance, either; one can also use a method reference to an arbitrary object, which is useful in Stream operations. For example, suppose we have a Person class and want just the lowercase names of a collection of people:

A complex lambda can also be pushed into a static or instance method and then used via a method reference instead. This makes the code more reusable and testable than if it were “trapped” in the lambda.

So we can see that method references are mainly used to improve code organization, clarity and terseness.

How are Java enums more powerful than integer constants? How can this capability be used?

Enums are essentially final classes with a fixed number of instances. They can implement interfaces but cannot extend another class.

This flexibility is useful in implementing the strategy pattern, for example, when the number of strategies is fixed. Consider an address book that records multiple methods of contact. We can represent these methods as an enum and attach fields, like the filename of the icon to display in the UI, and any corresponding behaviour, like how to initiate contact via that method:

We can dispense with switch statements entirely by simply using instances of ContactMethod :

This is just the beginning of what can be done with enums. Generally, the safety and flexibility of enums means they should be used in place of integer constants, and switch statements can be eliminated with liberal use of abstract methods.

What does it mean for a collection to be “backed by” another? Give an example of when this property is useful.

If a collection backs another, it means that changes in one are reflected in the other and vice-versa.

For example, suppose we wanted to create a whitelist function that removes invalid keys from a Map . This is made far easier with Map.keySet , which returns a set of keys that is backed by the original map. When we remove keys from the key set, they are also removed from the backing map:

retainAll writes through to the backing map, and allows us to easily implement something that would otherwise require iterating over the entries in the input map, comparing them against allowedKey , etcetera.

Note, it is important to consult the documentation of the backing collection to see which modifications will successfully write through. In the example above, map.keySet().add(value) would fail, because we cannot add a key to the backing map without a value.

What is reflection? Give an example of functionality that can only be implemented using reflection.

Reflection allows programmatic access to information about a Java program’s types. Commonly used information includes: methods and fields available on a class, interfaces implemented by a class, and the runtime-retained annotations on classes, fields and methods.

Examples given are likely to include:

  • Annotation-based serialization libraries often map class fields to JSON keys or XML elements (using annotations). These libraries need reflection to inspect those fields and their annotations and also to access the values during serialization.
  • Model-View-Controller frameworks call controller methods based on routing rules. These frameworks must use reflection to find a method corresponding to an action name, check that its signature conforms to what the framework expects (e.g. takes a Request object, returns a Response ), and finally, invoke the method.
  • Dependency injection frameworks lean heavily on reflection. They use it to instantiate arbitrary beans for injection, check fields for annotations such as @Inject to discover if they require injection of a bean, and also to set those values.
  • Object-relational mappers such as Hibernate use reflection to map database columns to fields or getter/setter pairs of a class, and can go as far as to infer table and column names by reading class and getter names, respectively.

A concrete code example could be something simple, like copying an object’s fields into a map:

Such tricks can be useful for debugging, or for utility methods such as a toString method that works on any class.

Aside from implementing generic libraries, direct use of reflection is rare but it is still a handy tool to have. Knowledge of reflection is also useful for when these mechanisms fail.

However, it is often prudent to avoid reflection unless it is strictly necessary, as it can turn straightforward compiler errors into runtime errors.

Nested classes can be static or non-static (also called an inner class). How do you decide which to use? Does it matter?

The key difference between is that inner classes have full access to the fields and methods of the enclosing class. This can be convenient for event handlers, but comes at a cost: every instance of an inner class retains and requires a reference to its enclosing class.

With this cost in mind, there are many situations where we should prefer static nested classes. When instances of the nested class will outlive instances of the enclosing class, the nested class should be static to prevent memory leaks. Consider this implementation of the factory pattern:

At a glance, this design looks good: the WidgetParserFactory hides the implementation details of the parser with the nested class WidgetParserImpl . However, WidgetParserImpl is not static, and so if WidgetParserFactory is discarded immediately after the WidgetParser is created, the factory will leak, along with all the references it holds.

WidgetParserImpl should be made static, and if it needs access to any of WidgetParserFactory ’s internals, they should be passed into WidgetParserImpl ’s constructor instead. This also makes it easier to extract WidgetParserImpl into a separate class should it outgrow its enclosing class.

Inner classes are also harder to construct via reflection due to their “hidden” reference to the enclosing class, and this reference can get sucked in during reflection-based serialization, which is probably not intended.

So we can see that the decision of whether to make a nested class static is important, and that one should aim to make nested classes static in cases where instances will “escape” the enclosing class or if reflection on those nested classes is involved.

What is the difference between String s = "Test" and String s = new String("Test") ? Which is better and why?

In general, String s = "Test" is more efficient to use than String s = new String("Test") .

In the case of String s = "Test" , a String with the value “Test” will be created in the String pool. If another String with the same value is then created (e.g., String s2 = "Test" ), it will reference this same object in the String pool.

However, if you use String s = new String("Test") , in addition to creating a String with the value “Test” in the String pool, that String object will then be passed to the constructor of the String Object (i.e., new String("Test") ) and will create another String object (not in the String pool) with that value. Each such call will therefore create an additional String object (e.g., String s2 = new String("Test") would create an addition String object, rather than just reusing the same String object from the String pool).

There is more to interviewing than tricky technical questions, so these are intended merely as a guide. Not every “A” candidate worth hiring will be able to answer them all, nor does answering them all guarantee an “A” candidate. At the end of the day, hiring remains an art, a science — and a lot of work .

Tired of interviewing candidates? Not sure what to ask to get you a top hire?

Let Toptal find the best people for you.

Our Exclusive Network of Java Developers

Looking to land a job as a Java Developer?

Let Toptal find the right job for you.

Job Opportunities From Our Network

Submit an interview question

Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of Toptal, LLC.

Looking for Java Developers?

Looking for Java Developers ? Check out Toptal’s Java developers.

Shane Freed, Accomplished Java Freelancer.

Shane Freed

Shane is a Java developer with 25 years of experience building enterprise apps and specializes in writing maintainable, extensible, SOLID code. While 95% of Shane's experience is in the Java realm, his passion is full-stack development with Angular. Shane's served in many different roles, including architect, team lead, lead developer, and individual contributor. While Shane doesn't always have to lead a project, his USMC background makes him perfect for lead roles and mentoring.

Kevin Roll, Toptal Java Developer.

Kevin is a software developer with over 30 years of experience across a wide range of platforms. He specializes in object-oriented design, database persistence, and mobile development. Kevin has worked on enterprise Java and Android applications for the Air Force Research Laboratory, built an app to automate aircraft maintenance, and consulted on iRobot’s defense division. He has a passion for code quality and good design, with a particular interest in projects that involve aviation or finance.

Rene Hartmann, Java Engineer.

Rene Hartmann

Rene is a goal-driven agile developer with 15+ years of experience designing and implementing successful, scalable, and performing Java-based solutions. He is keen on writing clean and maintainable code and is mainly interested in working with high-performance, scalable, low-latency distributed applications. Rene believes efficient working processes, mentoring, and teamwork are crucial for successfully developing and deploying solutions.

Toptal Connects the Top 3% of Freelance Talent All Over The World.

Join the Toptal community.


Scenario Based Java 8 Coding Interview Questions (For Experienced)

Generally, most websites cover basic Java 8 coding problems , But when you appear in the interview as an experience, Interviewer asks scenario-based coding questions. This question might not be simple if you have not practiced it well.

So to solve this, I have collected and prepared multiple Java 8 scenario-based tough questions. That is not simple. To solve this problem you have to think in-depth and apply different Java 8 concepts in it.

Also all listed below problem is important for all types of MNCs exams. So Please go through it one by one and solve it. First, try to solve it on your own before referring to the solution.

Scenario 1:

Employee Management System

We have a list of employees with (name, age, salary). Your task is to write a program to find the average salary of employees older than 30 using Java 8.

Scenario 2:

Student Grades System

There is a list of students with their (name, grades). We have to find the name of the student who has the highest grade.

Scenario 3:

Product Inventory Management

Suppose in a Product Inventory We have a list of products with (name, price, quantity). You have to calculate the total cost of all products which are in stock.

Scenario 4:

Library Management

There are multiple records of books with (title, author, publication year). We have to write Java 8 code to filter all books that were published after 2010.

Scenario 5:

Data Transformation

Here we are moving to the next topic to see some new concepts of Data Transformation using Java 8. We have Given a list of strings and we have to convert them to uppercase using Java 8 streams.

Scenario 6:

Filtering and Sorting on Data

For the given list of elements, perform Filtering and Sorting on the elements. Write a java 8 program to perform operations like filter out the odd numbers from list and sort the remaining ones in ascending order.

Scenario 7:

Perform Word Count for the given paragraph and print the occurrences of each word using a Java Map and Java 8.

Scenario 8:

Transaction Management

For the given transaction data with (payer, payee, amount), calculate the total amount received by each payee. Here you have to use the grouping and Summing concept of Java 8.

Scenario 9:

Stream Chaining

Given a list of strings, filter out the ones containing a specific substring and then concatenate them into a single string.

Scenario 10:

Prime number

Print the list of all prime numbers in the given range using Java 8.

Below is Some problem that you can try to solve on your own. Later we will Provide the solutions But before you can try by yourself.

Scenario 11:

Sales Management

In the retail marketplace, there are multiple transactions that happen from time to time. We have to perform the data analysis over the revenue.

For the Given list of sales transactions (transactionID, productID, quantity, price), you have to find the top N products (by revenue) sold in the last 3 months using Java 8.

Here N is the number of products that you want.

Scenario 12:

Given Employee details, you have to sort the employee details on basis of employees name using java 8.

Download Interview guide PDF

  • Java Interview Questions

Download PDF

Do you have what it takes to ace a Java Interview? We are here to help you in consolidating your knowledge and concepts in Java . Before we begin, let's understand what Java is all about.

What is Java? 

Java is a high-level programming language that was developed by James Gosling in the year 1982. It is based on the principles of object-oriented programming and can be used to develop large-scale applications. 

The following article will cover all the popular Core Java interview questions, String Handling interview questions, Java 8 interview questions, Java multithreading interview questions, Java OOPs interview questions, Java exception handling interview questions, collections interview questions, and some frequently asked Java coding interview questions.

Go through all the important questions to enhance your chances of performing well in the Java Interviews. The questions will revolve around the basic, core & advanced fundamentals of Java.

So, let’s dive deep into the plethora of useful Java Technical Interview Questions and Answers categorised into the following sections:

  • Java interview questions for Freshers

Java Intermediate Interview Questions

Java interview questions for experienced, java programming interview questions.

Join our community and share your recent Java interview experiences.

Java Interview Questions for Freshers

1. why is java a platform independent language.

Java language was developed so that it does not depend on any hardware or software because the compiler compiles the code and then converts it to platform-independent byte code which can be run on multiple systems.

  • The only condition to run that byte code is for the machine to have a runtime environment (JRE) installed in it.

2. Why is Java not a pure object oriented language?

Java supports primitive data types - byte, boolean, char, short, int, float, long, and double and hence it is not a pure object oriented language .

3. Difference between Heap and Stack Memory in java. And how java utilizes this.

Stack memory is the portion of memory that was assigned to every individual program. And it was fixed. On the other hand, Heap memory is the portion that was not allocated to the java program but it will be available for use by the java program when it is required, mostly during the runtime of the program.

Java Utilizes this memory as - 

  • When we write a java program then all the variables, methods, etc are stored in the stack memory.
  • And when we create any object in the java program then that object was created in the heap memory. And it was referenced from the stack memory.

Example- Consider the below java program :

For this java program. The stack and heap memory occupied by java is -

case study questions in java

Main and PrintArray is the method that will be available in the stack area and as well as the variables declared that will also be in the stack area. 

And the Object (Integer Array of size 10) we have created, will be available in the Heap area because that space will be allocated to the program during runtime. 

4. Can java be said to be the complete object-oriented programming language?

It is not wrong if we claim that Java is the complete object-oriented programming language because everything in Java is under the classes and we can access them by creating the objects.

But we can even say that Java is not a completely object-oriented programming language because it has the support of primitive data types like int, float, char, boolean, double, etc.

Now for the question: Is Java a completely object-oriented programming language? We can say that - Java is not a pure object-oriented programming language, because it has direct access to primitive data types. And these primitive data types don't directly belong to the Integer classes.

5. How is Java different from C++?

  • C++ is only a  compiled language, whereas Java is compiled as well as an interpreted language.
  • Java programs are machine-independent whereas a c++ program can run only in the machine in which it is compiled. 
  • C++ allows users to use pointers in the program. Whereas java doesn’t allow it. Java internally uses pointers. 
  • C++ supports the concept of Multiple inheritances whereas Java doesn't support this. And it is due to avoiding the complexity of name ambiguity that causes the diamond problem.

Learn via our Video Courses

6. pointers are used in c/ c++. why does java not make use of pointers.

Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause potential errors. Moreover, security is also compromised if pointers are used because the users can directly access memory with the help of pointers.

Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the usage of pointers can make the procedure of garbage collection quite slow and erroneous. Java makes use of references as these cannot be manipulated, unlike pointers.

7. What do you understand by an instance variable and a local variable?

Instance variables are those variables that are accessible by all the methods in the class. They are declared outside the methods and inside the class. These variables describe the properties of an object and remain bound to it at any cost.

All the objects of the class will have their copy of the variables for utilization. If any modification is done on these variables, then only that instance will be impacted by it, and all other class instances continue to remain unaffected.

Local variables are those variables present within a block, function, or constructor and can be accessed only inside them. The utilization of the variable is restricted to the block scope. Whenever a local variable is declared inside a method, the other class methods don’t have any knowledge about the local variable.

case study questions in java

8. What are the default values assigned to variables and instances in java?

  • There are no default values assigned to the variables in java. We need to initialize the value before using it. Otherwise, it will throw a compilation error of ( Variable might not be initialized ). 
  • But for instance, if we create the object, then the default value will be initialized by the default constructor depending on the data type. 
  • If it is a reference, then it will be assigned to null. 
  • If it is numeric, then it will assign to 0.
  • If it is a boolean, then it will be assigned to false. Etc.

9. What do you mean by data encapsulation?

  • Data Encapsulation is an Object-Oriented Programming concept of hiding the data attributes and their behaviours in a single unit.
  • It helps developers to follow modularity while developing software by ensuring that each object is independent of other objects by having its own methods, attributes, and functionalities.
  • It is used for the security of the private properties of an object and hence serves the purpose of data hiding.

case study questions in java

10. Tell us something about JIT compiler.

  • JIT stands for Just-In-Time and it is used for improving the performance during run time. It does the task of compiling parts of byte code having similar functionality at the same time thereby reducing the amount of compilation time for the code to run.
  • First, the Java source code (.java) conversion to byte code (.class) occurs with the help of the javac compiler.
  • Then, the .class files are loaded at run time by JVM and with the help of an interpreter, these are converted to machine understandable code.
  • JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM analyzes the method calls in the .class files and compiles them to get more efficient and native code. It also ensures that the prioritized method calls are optimized.
  • Once the above step is done, the JVM executes the optimized code directly instead of interpreting the code again. This increases the performance and speed of the execution.

case study questions in java

11. Can you tell the difference between equals() method and equality operator (==) in Java?

We are already aware of the (==) equals operator. That we have used this to compare the equality of the values. But when we talk about the terms of object-oriented programming, we deal with the values in the form of objects. And this object may contain multiple types of data. So using the (==) operator does not work in this case. So we need to go with the . equals() method.

Both [(==) and .equals()] primary functionalities are to compare the values, but the secondary functionality is different. 

So in order to understand this better, let’s consider this with the example -

This code will print true. We know that both strings are equals so it will print true. But here (==) Operators don’t compare each character in this case. It compares the memory location. And because the string uses the constant pool for storing the values in the memory, both str1 and str2 are stored at the same memory location. See the detailed Explanation in Question no 73: Link .

case study questions in java

Now, if we modify the program a little bit with -

case study questions in java

Then in this case, it will print false. Because here no longer the constant pool concepts are used. Here, new memory is allocated. So here the memory address is different, therefore ( == ) Operator returns false. But the twist is that the values are the same in both strings. So how to compare the values? Here the .equals() method is used.

.equals() method compares the values and returns the result accordingly.  If we modify the above code with - 

Then it returns true.

equals()  ==
This is a method defined in the Object class.  It is a binary operator in Java.
The .equals() Method is present in the Object class, so we can override our custom .equals() method in the custom class, for objects comparison. It cannot be modified. They always compare the HashCode.
This method is used for checking the equality of contents between two objects as per the specified business logic. This operator is used for comparing addresses (or references), i.e checks if both the objects are pointing to the same memory location.
  • In the cases where the equals method is not overridden in a class, then the class uses the default implementation of the equals method that is closest to the parent class.
  • Object class is considered as the parent class of all the java classes. The implementation of the equals method in the Object class uses the == operator to compare two objects. This default implementation can be overridden as per the business logic.

12. How is an infinite loop declared in Java?

Infinite loops are those loops that run infinitely without any breaking conditions. Some examples of consciously declaring infinite loop is:

  • Using For Loop:
  • Using while loop:
  • Using do-while loop:

13. Briefly explain the concept of constructor overloading

Constructor overloading is the process of creating multiple constructors in the class consisting of the same name with a difference in the constructor parameters. Depending upon the number of parameters and their corresponding types, distinguishing of the different types of constructors is done by the compiler.

case study questions in java

Three constructors are defined here but they differ on the basis of parameter type and their numbers.

14. Define Copy constructor in java.

Copy Constructor is the constructor used when we want to initialize the value to the new object from the old object of the same class. 

Here we are initializing the new object value from the old object value in the constructor. Although, this can also be achieved with the help of object cloning.

15. Can the main method be Overloaded?

Yes, It is possible to overload the main method. We can create as many overloaded main methods we want. However, JVM has a predefined calling method that JVM will only call the main method with the definition of - 

Consider the below code snippets: 

16. Comment on method overloading and overriding by citing relevant examples.

In Java, method overloading is made possible by introducing different methods in the same class consisting of the same name. Still, all the functions differ in the number or type of parameters. It takes place inside a class and enhances program readability.

The only difference in the return type of the method does not promote method overloading. The following example will furnish you with a clear picture of it.

case study questions in java

Both the functions have the same name but differ in the number of arguments. The first method calculates the area of the rectangle, whereas the second method calculates the area of a cuboid.

Method overriding is the concept in which two methods having the same method signature are present in two different classes in which an inheritance relationship is present. A particular method implementation (already present in the base class) is possible for the derived class by using method overriding. Let’s give a look at this example:

case study questions in java

Both class methods have the name walk and the same parameters, distance, and time. If the derived class method is called, then the base class method walk gets overridden by that of the derived class.

17. A single try block and multiple catch blocks can co-exist in a Java Program. Explain.

Yes, multiple catch blocks can exist but specific approaches should come prior to the general approach because only the first catch block satisfying the catch condition is executed. The given code illustrates the same:

Here, the second catch block will be executed because of division by 0 (i / x). In case x was greater than 0 then the first catch block will execute because for loop runs till i = n and array index are till n-1.

18. Explain the use of final keyword in variable, method and class.

In Java, the final keyword is used as defining something as constant /final and represents the non-access modifier.

  • When a variable is declared as final in Java, the value can’t be modified once it has been assigned.
  • If any value has not been assigned to that variable, then it can be assigned only by the constructor of the class.
  • A method declared as final cannot be overridden by its children's classes.
  • A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn't make sense. Java throws compilation error saying - modifier final not allowed here
  • No classes can be inherited from the class declared as final. But that final class can extend other classes for its usage.

19. Do final, finally and finalize keywords have the same function?

All three keywords have their own utility while programming.

Final: If any restriction is required for classes, variables, or methods, the final keyword comes in handy. Inheritance of a final class and overriding of a final method is restricted by the use of the final keyword. The variable value becomes fixed after incorporating the final keyword. Example:

The second statement will throw an error.

Finally: It is the block present in a program where all the codes written inside it get executed irrespective of handling of exceptions. Example:

Finalize: Prior to the garbage collection of an object, the finalize method is called so that the clean-up activity is implemented. Example:

20. Is it possible that the ‘finally’ block will not be executed? If yes then list the case.

 Yes. It is possible that the ‘finally’ block will not be executed. The cases are-

  • Suppose we use System.exit() in the above statement.
  • If there are fatal errors like Stack overflow, Memory access error, etc.

21. Identify the output of the java program and state the reason.

The above code will generate a compile-time error at Line 7 saying - [error: variable i might already have been initialized] . It is because variable ‘i’ is the final variable. And final variables are allowed to be initialized only once, and that was already done on line no 5.

22. When can you use super keyword?

  • The super keyword is used to access hidden fields and overridden methods or attributes of the parent class.
  • Accessing data members of parent class when the member names of the class and its child subclasses are same.
  • To call the default and parameterized constructor of the parent class inside the child class.
  • Accessing the parent class methods when the child classes have overridden them.
  • The following example demonstrates all 3 cases when a super keyword is used.

23. Can the static methods be overloaded?

Yes! There can be two or more static methods in a class with the same name but differing input parameters.

24. Why is the main method static in Java?

The main method is always static because static members are those methods that belong to the classes, not to an individual object. So if the main method will not be static then for every object, It is available. And that is not acceptable by JVM. JVM calls the main method based on the class name itself. Not by creating the object.

Because there must be only 1 main method in the java program as the execution starts from the main method. So for this reason the main method is static. 

25. Can the static methods be overridden?

  • No! Declaration of static methods having the same signature can be done in the subclass but run time polymorphism can not take place in such cases.
  • Overriding or dynamic polymorphism occurs during the runtime, but the static methods are loaded and looked up at the compile time statically. Hence, these methods cant be overridden.

26. Difference between static methods, static variables, and static classes in java.

  • For example - We have used mathematical functions in the java program like - max(), min(), sqrt(), pow(), etc. And if we notice that, then we will find that we call it directly with the class name. Like - Math.max(), Math.min(), etc. So that is a static method.  And Similarly static variables we have used like (length) for the array to get the length. So that is the static method.
  • Static classes - A class in the java program cannot be static except if it is the inner class. If it is an inner static class, then it exactly works like other static members of the class.

27. What is the main objective of garbage collection?

The main objective of this process is to free up the memory space occupied by the unnecessary and unreachable objects during the Java program execution by deleting those unreachable objects.

  • This ensures that the memory resource is used efficiently, but it provides no guarantee that there would be sufficient memory for the program execution.

28. What is a ClassLoader?

  • Java Classloader is the program that belongs to JRE (Java Runtime Environment). The task of ClassLoader is to load the required classes and interfaces to the JVM when required. 
  • Example- To get input from the console, we require the scanner class. And the Scanner class is loaded by the ClassLoader.

29. What part of memory - Stack or Heap - is cleaned in garbage collection process?

30. what are shallow copy and deep copy in java.

To copy the object's data, we have several methods like deep copy and shallow copy. 

Object for this Rectangle class - Rectangle obj1 = new Rectangle();

  • Shallow copy - The shallow copy only creates a new reference and points to the same object. Example - For Shallow copy, we can do this by -

Now by doing this what will happen is the new reference is created with the name obj2 and that will point to the same memory location.

  • Deep Copy - In a deep copy, we create a new object and copy the old object value to the new object. Example -

Both these objects will point to the memory location as stated below -

case study questions in java

Now, if we change the values in shallow copy then they affect the other reference as well. Let's see with the help of an example - 

We can see that in the above code, if we change the values of object1, then the object2 values also get changed. It is because of the reference.

Now, if we change the code to deep copy, then there will be no effect on object2 if it is of type deep copy. Consider some snippets to be added in the above code.

The above snippet will not affect the object2 values. It has its separate values. The output will be

Now we see that we need to write the number of codes for this deep copy. So to reduce this, In java, there is a method called clone().  

The clone() will do this deep copy internally and return a new object. And to do this we need to write only 1 line of code. That is - Rectangle obj2 = obj1.clone();

1. Apart from the security aspect, what are the reasons behind making strings immutable in Java?

A String is made immutable due to the following reasons:

  • String Pool: Designers of Java were aware of the fact that String data type is going to be majorly used by the programmers and developers. Thus, they wanted optimization from the beginning. They came up with the notion of using the String pool (a storage area in Java heap) to store the String literals. They intended to decrease the temporary String object with the help of sharing. An immutable class is needed to facilitate sharing. The sharing of the mutable structures between two unknown parties is not possible. Thus, immutable Java String helps in executing the concept of String Pool.

case study questions in java

  • Multithreading : The safety of threads regarding the String objects is an important aspect in Java. No external synchronization is required if the String objects are immutable. Thus, a cleaner code can be written for sharing the String objects across different threads. The complex process of concurrency is facilitated by this method.
  • Collections : In the case of Hashtables and HashMaps, keys are String objects. If the String objects are not immutable, then it can get modified during the period when it resides in the HashMaps. Consequently, the retrieval of the desired data is not possible. Such changing states pose a lot of risks. Therefore, it is quite safe to make the string immutable.

2. What is a singleton class in Java? And How to implement a singleton class?

Singleton classes are those classes, whose objects are created only once. And with only that object the class members can be accessed. 

Understand this with the help of an example-:

Consider the water jug in the office and if every employee wants that water then they will not create a new water jug for drinking water. They will use the existing one with their own reference as a glass. So programmatically it should be implemented as -

In the above class, the Constructor is private so we cannot create the object of the class. But we can get the object by calling the method getInstance() . And the getInstance is static so it can be called without creating the object. And it returns the object. Now with that object, we can call getWater() to get the water.

We can get the single object using this getInstance(). And it is static, so it is a thread-safe singleton class. Although there are many ways to create a thread-safe singleton class. So thread-safe classes can also be:

  • When singletons are written with double-checked locking, they can be thread-safe.
  • We can use static singletons that are initialized during class loading. Like we did in the above example.
  • But the most straightforward way to create a thread-safe singleton is to use Java enums.

3. Which of the below generates a compile-time error? State the reason.

  • int[] n1 = new int[0];
  • boolean[] n2 = new boolean[-200];
  • double[] n3 = new double[2241423798];
  • char[] ch = new char[20];

We get a compile-time error in line 3. The error we will get in Line 3 is - integer number too large . It is because the array requires size as an integer. And Integer takes 4 Bytes in the memory. And the number ( 2241423798 ) is beyond the capacity of the integer. The maximum array size we can declare is - ( 2147483647 ).

Because the array requires the size in integer, none of the lines (1, 2, and 4) will give a compile-time error. The program will compile fine. But we get the runtime exception in line 2. The exception is - NegativeArraySizeException . 

Here what will happen is - At the time when JVM will allocate the required memory during runtime then it will find that the size is negative. And the array size can’t be negative. So the JVM will throw the exception.

4. How would you differentiate between a String, StringBuffer, and a StringBuilder?

  • Storage area: In string, the String pool serves as the storage area. For StringBuilder and StringBuffer, heap memory is the storage area.
  • Mutability: A String is immutable, whereas both the StringBuilder and StringBuffer are mutable.
  • Efficiency: It is quite slow to work with a String. However, StringBuilder is the fastest in performing operations. The speed of a StringBuffer is more than a String and less than a StringBuilder. (For example appending a character is fastest in StringBuilder and very slow in String because a new memory is required for the new String with appended character.)
  • Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer are used whereas a String is not used. However, StringBuilder is suitable for an environment with a single thread, and a StringBuffer is suitable for multiple threads. Syntax:

5. Using relevant properties highlight the differences between interfaces and abstract classes.

  • Availability of methods: Only abstract methods are available in interfaces, whereas non-abstract methods can be present along with abstract methods in abstract classes.
  • Variable types : Static and final variables can only be declared in the case of interfaces, whereas abstract classes can also have non-static and non-final variables.
  • Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do not promote multiple inheritances.
  • Data member accessibility: By default, the class data members of interfaces are of the public- type. Conversely, the class members for an abstract class can be protected or private also.
  • Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the converse is not true;

Abstract class example:

Interface example:

6. Is this program giving a compile-time error? If Yes then state the reason and number of errors it will give. If not then state the reason.

The above program will give a compile-time error. The compiler will throw 2 errors in this.

  • [Illegal Combination of modifiers: abstract and final] at line 1.
  • [Cannot inherit from final ‘InterviewBit’] at line 4.

It is because abstract classes are incomplete classes that need to be inherited for making their concrete classes. And on the other hand, the final keywords in class are used for avoiding inheritance. So these combinations are not allowed in java.

7. What is a Comparator in java?

Consider the example where we have an ArrayList of employees like( EId, Ename, Salary), etc. Now if we want to sort this list of employees based on the names of employees. Then that is not possible to sort using the Collections.sort() method. We need to provide something to the sort() function depending on what values we have to perform sorting. Then in that case a comparator is used.

Comparator is the interface in java that contains the compare method. And by overloading the compare method, we can define that on what basis we need to compare the values. 

8. In Java, static as well as private method overriding is possible. Comment on the statement.

The statement in the context is completely False. The static methods have no relevance with the objects, and these methods are of the class level. In the case of a child class, a static method with a method signature exactly like that of the parent class can exist without even throwing any compilation error.

The phenomenon mentioned here is popularly known as method hiding, and overriding is certainly not possible. Private method overriding is unimaginable because the visibility of the private method is restricted to the parent class only. As a result, only hiding can be facilitated and not overriding.

9. What makes a HashSet different from a TreeSet?

Although both HashSet and TreeSet are not synchronized and ensure that duplicates are not present, there are certain properties that distinguish a HashSet from a TreeSet.

  • Implementation: For a HashSet, the hash table is utilized for storing the elements in an unordered manner. However, TreeSet makes use of the red-black tree to store the elements in a sorted manner.
  • Complexity/ Performance: For adding, retrieving, and deleting elements, the time amortized complexity is O(1) for a HashSet. The time complexity for performing the same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the performance of HashSet is faster in comparison to TreeSet.
  • Methods: hashCode() and equals() are the methods utilized by HashSet for making comparisons between the objects. Conversely, compareTo() and compare() methods are utilized by TreeSet to facilitate object comparisons.
  • Objects type: Heterogeneous and null objects can be stored with the help of HashSet. In the case of a TreeSet, runtime exception occurs while inserting heterogeneous objects or null objects.

10. Why is the character array preferred over string for storing confidential information?

In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it continues to stay in the string pool as long as it is not removed in the form of garbage. In other words, a string resides in the heap section of the memory for an unregulated and unspecified time interval after string value processing is executed.

As a result, vital information can be stolen for pursuing harmful activities by hackers if a memory dump is illegally accessed by them. Such risks can be eliminated by using mutable objects or structures like character arrays for storing any variable. After the work of the character array variable is done, the variable can be configured to blank at the same instant. Consequently, it helps in saving heap memory and also gives no chance to the hackers to extract vital data.

11. What do we get in the JDK file?

  • JDK - For making java programs, we need some tools that are provided by JDK (Java Development Kit). JDK is the package that contains various tools, Compiler, Java Runtime Environment, etc.
  • JRE -  To execute the java program we need an environment. (Java Runtime Environment) JRE contains a library of Java classes +  JVM. What are JAVA Classes?  It contains some predefined methods that help Java programs to use that feature, build and execute. For example - there is a system class in java that contains the print-stream method, and with the help of this, we can print something on the console.
  • JVM - (Java Virtual Machine) JVM  is a part of JRE that executes the Java program at the end.  Actually, it is part of JRE, but it is software that converts bytecode into machine-executable code to execute on hardware.

case study questions in java

12. What are the differences between JVM, JRE and JDK in Java?

Criteria JDK  JRE JVM
Abbreviation Java Development Kit Java Runtime Environment Java Virtual Machine
Definition JDK is a complete software development kit for developing Java applications. It comprises JRE, JavaDoc, compiler, debuggers, etc. JRE is a software package providing Java class libraries, JVM and all the required components to run the Java applications. JVM is a platform-dependent, abstract machine comprising of 3 specifications - document describing the JVM implementation requirements, computer program meeting the JVM requirements and instance object for executing the Java byte code and provide the runtime environment for execution.
Main Purpose JDK is mainly used for code development and execution. JRE is mainly used for environment creation to execute the code. JVM provides specifications for all the implementations to JRE.
Tools provided JDK provides tools like compiler, debuggers, etc for code development JRE provides libraries and classes required by JVM to run the program. JVM does not include any tools, but instead, it provides the specification for implementation.
Summary JDK = (JRE) + Development tools JRE = (JVM) + Libraries to execute the application JVM = Runtime environment to execute Java byte code.

13. What are the differences between HashMap and HashTable in Java?

HashMap HashTable
HashMap is not synchronized thereby making it better for non-threaded applications. HashTable is synchronized and hence it is suitable for threaded applications.
Allows only one null key but any number of null in the values. This does not allow null in both keys or values.
Supports order of insertion by making use of its subclass LinkedHashMap. Order of insertion is not guaranteed in HashTable.

14. What is the importance of reflection in Java?

  • The term reflection is used for describing the inspection capability of a code on other code either of itself or of its system and modify it during runtime.
  • Consider an example where we have an object of unknown type and we have a method ‘fooBar()’ which we need to call on the object. The static typing system of Java doesn't allow this method invocation unless the type of the object is known beforehand. This can be achieved using reflection which allows the code to scan the object and identify if it has any method called “fooBar()” and only then call the method if needed.
  • Speed — Method invocations due to reflection are about three times slower than the direct method calls.
  • Type safety — When a method is invoked via its reference wrongly using reflection, invocation fails at runtime as it is not detected at compile/load time.
  • Traceability — Whenever a reflective method fails, it is very difficult to find the root cause of this failure due to a huge stack trace. One has to deep dive into the invoke() and proxy() method logs to identify the root cause.
  • Hence, it is advisable to follow solutions that don't involve reflection and use this method as a last resort.

15. What are the different ways of threads usage?

  • Extending the Thread class
  • Implementing the Runnable interface
  • Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes.
  • start() method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls the run() method for executing the thread in that call stack.

16. What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM?

There are a total of 3 different types of priority available in Java. 

MIN_PRIORITY: It has an integer value assigned with 1. MAX_PRIORITY: It has an integer value assigned with 10. NORM_PRIORITY: It has an integer value assigned with 5.

In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default priority for any thread is NORM_PRIORITY assigned by JVM. 

17. What is the difference between the program and the process?

  • A program can be defined as a line of code written in order to accomplish a particular task. Whereas the process can be defined as the programs which are under execution. 
  • A program doesn't execute directly by the CPU. First, the resources are allocated to the program and when it is ready for execution then it is a process.

18. What is the difference between the ‘throw’ and ‘throws’ keyword in java?

  • The ‘ throw ’ keyword is used to manually throw the exception to the calling method.
  • And the ‘ throws ’ keyword is used in the function definition to inform the calling method that this method throws the exception. So if you are calling, then you have to handle the exception.

Here in the above snippet, the method testExceptionDivide throws an exception. So if the main method is calling it then it must have handled the exception. Otherwise, the main method can also throw the exception to JVM.

And the method testExceptionDivide 'throws’ the exception based on the condition.

19. What are the differences between constructor and method of a class in Java?

Constructor Method
Constructor is used for initializing the object state. Method is used for exposing the object's behavior.
Constructor has no return type. Method should have a return type. Even if it does not return anything, return type is void.
Constructor gets invoked implicitly. Method has to be invoked on the object explicitly.
If the constructor is not defined, then a default constructor is provided by the java compiler. If a method is not defined, then the compiler does not provide it.
The constructor name should be equal to the class name. The name of the method can have any name or have a class name too.
A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn't make sense. Java throws compilation error saying - A method can be defined as final but it cannot be overridden in its subclasses.
Final variable instantiations are possible inside a constructor and the scope of this applies to the whole class and its objects. A final variable if initialised inside a method ensures that the variable cant be changed only within the scope of that method.

20. Identify the output of the below java program and Justify your answer.

The above code will throw the compilation error. It is because the super() is used to call the parent class constructor. But there is the condition that super() must be the first statement in the block. Now in this case, if we replace this() with super() then also it will throw the compilation error. Because this() also has to be the first statement in the block. So in conclusion, we can say that we cannot use this() and super() keywords in the same block.

21. Java works as “pass by value” or “pass by reference” phenomenon?

Java always works as a “pass by value”. There is nothing called a “pass by reference” in Java. However, when the object is passed in any method, the address of the value is passed due to the nature of object handling in Java. When an object is passed, a copy of the reference is created by Java and that is passed to the method. The objects point to the same memory location. 2 cases might happen inside the method:

  • Case 1: When the object is pointed to another location: In this case, the changes made to that object do not get reflected the original object before it was passed to the method as the reference points to another location.

For example:

  • Case 2: When object references are not modified: In this case, since we have the copy of reference the main object pointing to the same memory location, any changes in the content of the object get reflected in the original object.

22. What is the ‘IS-A ‘ relationship in OOPs java?

‘IS-A’ relationship is another name for inheritance. When we inherit the base class from the derived class, then it forms a relationship between the classes. So that relationship is termed an ‘IS-A’ Relationship.

Example - Consider a Television (Typical CRT TV). Now another Smart TV  that is inherited from television class. So we can say that the Smart iv is also a TV. Because CRT TV things can also be done in the Smart TV.

case study questions in java

So here ‘IS-A’ Relationship formed. [ SmartTV ‘IS-A’ TV ] .

23. Which among String or String Buffer should be preferred when there are lot of updates required to be done in the data?

StringBuffer is mutable and dynamic in nature whereas String is immutable. Every updation / modification of String creates a new String thereby overloading the string pool with unnecessary objects. Hence, in the cases of a lot of updates, it is always preferred to use StringBuffer as it will reduce the overhead of the creation of multiple String objects in the string pool.

24. How to not allow serialization of attributes of a class in Java?

  • In order to achieve this, the attribute can be declared along with the usage of transient keyword as shown below:
  • In the above example, all the fields except someInfo can be serialized.

25. What happens if the static modifier is not included in the main method signature in Java?

There wouldn't be any compilation error. But then the program is run, since the JVM cant map the main method signature, the code throws “NoSuchMethodError” error at the runtime.

26. Consider the below program, identify the output, and also state the reason for that.

The output of the above program will be Hello. Main Method . This is because JVM will always call the main method based on the definition it already has. Doesn't matter how many main methods we overload it will only execute one main method based on its declaration in JVM.

27. Can we make the main() thread a daemon thread?

In java multithreading, the main() threads are always non-daemon threads. And there is no way we can change the nature of the non-daemon thread to the daemon thread.

28. What happens if there are multiple main methods inside one class in Java?

The program can't compile as the compiler says that the method has been already defined inside the class.

29. What do you understand by Object Cloning and how do you achieve it in Java?

  • It is the process of creating an exact copy of any object. In order to support this, a java class has to implement the Cloneable interface of java.lang package and override the clone() method provided by the Object class the syntax of which is:
  • In case the Cloneable interface is not implemented and just the method is overridden, it results in CloneNotSupportedException in Java.

30. How does an exception propagate in the code?

When an exception occurs, first it searches to locate the matching catch block. In case, the matching catch block is located, then that block would be executed. Else, the exception propagates through the method call stack and goes into the caller method where the process of matching the catch block is performed. This propagation happens until the matching catch block is found. If the match is not found, then the program gets terminated in the main method.

case study questions in java

31. How do exceptions affect the program if it doesn't handle them?

Exceptions are runtime errors. Suppose we are making an android application with java. And it all works fine but there is an exceptional case when the application tries to get the file from storage and the file doesn’t exist (This is the case of exception in java). And if this case is not handled properly then the application will crash. This will be a bad experience for users.  This is the type of error that cannot be controlled by the programmer. But programmers can take some steps to avoid this so that the application won’t crash. The proper action can be taken at this step.

32. Is it mandatory for a catch block to be followed after a try block?

No, it is not necessary for a catch block to be present after a try block. - A try block should be followed either by a catch block or by a finally block. If the exceptions likelihood is more, then they should be declared using the throws clause of the method.

33. Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below?

finally block will be executed irrespective of the exception or not. The only case where finally block is not executed is when it encounters ‘System.exit()’ method anywhere in try/catch block.

34. Can you call a constructor of a class inside the another constructor?

Yes, the concept can be termed as constructor chaining and can be achieved using this() .

case study questions in java

35. Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain.

In the case of ArrayList, data storing in the form of primitive data types (like int, float, etc.) is not possible. The data members/objects present in the ArrayList have references to the objects which are located at various sites in the memory. Thus, storing of actual objects or non-primitive data types (like Integer, Double, etc.) takes place in various memory locations.

case study questions in java

However, the same does not apply to the arrays. Object or primitive type values can be stored in arrays in contiguous memory locations, hence every element does not require any reference to the next element.

case study questions in java

36. Why does the java array index start with 0?

It is because the 0 index array avoids the extra arithmetic operation to calculate the memory address.

Example - Consider the array and assume each element takes 4-byte memory space. Then the address will be like this -

case study questions in java

Now if we want to access index 4. Then internally java calculates the address using the formula-

[Base Address + (index * no_of_bytes)] . So according to this. The starting address of the index 4 will be - [100 + (4*4)] = 116 . And exactly that's what the address is calculated.  Now consider the same with 1 index Array -

case study questions in java

Now if we apply the same formula here. Then we get - 116 as the starting address of the 4th index. Which is wrong. Then we need to apply formula - [ Base Address + ((index-1) * no_of_bytes)] .

And for calculating this, an extra arithmetic operation has to be performed. And consider the case where millions of addresses need to be calculated, this causes complexity. So to avoid this, ) the index array is supported by java.

37. Why is the remove method faster in the linked list than in an array?

In the linked list, we only need to adjust the references when we want to delete the element from either end or the front of the linked list. But in the array, indexes are used. So to manage proper indexing, we need to adjust the values from the array So this adjustment of value is costlier than the adjustment of references.

Example - To Delete from the front of the linked list, internally the references adjustments happened like this.

case study questions in java

The only thing that will change is that the head pointer will point to the head’s next node. And delete the previous node. That is the constant time operation.

Whereas in the ArrayList, internally it should work like this-

case study questions in java

For deletion of the first element, all the next element has to move to one place ahead. So this copying value takes time. So that is the reason why removing in ArrayList is slower than LinkedList.

38. How many overloaded add() and addAll() methods are available in the List interface? Describe the need and uses.

There are a total of 4 overloaded methods for add() and addAll() methods available in List Interface. The below table states the description of all.

Return Type Method Description
boolean : This method is used for adding the element at the end of the List. The Datatype of the element is of any type it has been initially assigned with. It returns the boolean indicating successfully inserted or not.
void : This method is the overloaded version of add() method. In this, along with the element, the index is also passed to the method for the specific index the value needs to be inserted. 
boolean : This method helps to add all elements at the end of collections from the list received in the parameter. It contains an iterator that helps to iterate the list and add the elements to the collection.
boolean : This is the overloaded method for addAll() method. In this along with the list, we can pass the specified index from which the list elements need to be added.

39. How does the size of ArrayList grow dynamically? And also state how it is implemented internally.

ArrayList is implemented in such a way that it can grow dynamically. We don't need to specify the size of ArrayList. For adding the values in it, the methodology it uses is -

1. Consider initially that there are 2 elements in the ArrayList. [2, 3] .

case study questions in java

2. If we need to add the element into this. Then internally what will happen is-

  • ArrayList will allocate the new ArrayList of Size (current size + half of the current size). And add the old elements into the new. Old - [2, 3],    New - [2, 3, null].

case study questions in java

  • Then the new value will be inserted into it. [2, 3, 4, null]. And for the next time, the extra space will be available for the value to be inserted.

case study questions in java

3. This process continues and the time taken to perform all of these is considered as the amortized constant time. 

This is how the ArrayList grows dynamically. And when we delete any entry from the ArrayList then the following steps are performed -

1. It searches for the element index in the array. Searching takes some time. Typically it’s O(n) because it needs to search for the element in the entire array.

case study questions in java

2. After searching the element, it needs to shift the element from the right side to fill the index.

case study questions in java

So this is how the elements are deleted from the ArrayList internally. Similarly, the search operations are also implemented internally as defined in removing elements from the list (searching for elements to delete).

1. Although inheritance is a popular OOPs concept, it is less advantageous than composition. Explain.

Inheritance lags behind composition in the following scenarios:

  • Multiple-inheritance is not possible in Java. Classes can only extend from one superclass. In cases where multiple functionalities are required, for example - to read and write information into the file, the pattern of composition is preferred. The writer, as well as reader functionalities, can be made use of by considering them as the private members.
  • Composition assists in attaining high flexibility and prevents breaking of encapsulation.
  • Unit testing is possible with composition and not inheritance. When a developer wants to test a class composing a different class, then Mock Object can be created for signifying the composed class to facilitate testing. This technique is not possible with the help of inheritance as the derived class cannot be tested without the help of the superclass in inheritance.
  • The loosely coupled nature of composition is preferable over the tightly coupled nature of inheritance.

Let’s take an example:

In the above example, inheritance is followed. Now, some modifications are done to the Top class like this:

If the new implementation of the Top class is followed, a compile-time error is bound to occur in the Bottom class. Incompatible return type is there for the Top.stop() function. Changes have to be made to either the Top or the Bottom class to ensure compatibility. However, the composition technique can be utilized to solve the given problem:

2. What is the difference between ‘>>’ and ‘>>>’ operators in java?

These 2 are the bitwise right shift operators. Although both operators look similar. But there is a minimal difference between these two right shift operators.

  • ‘>>’ Bitwise Right Shift Operator - This operator shifts each bit to its right position. And this maintains the signed bit.
  • ‘>>>’ Bitwise Right Shift Operator with trailing zero - This operator also shifts each bit to its right. But this doesn’t maintain the signed bit. This operator makes the Most significant bit to 0.

Example- Num1 = 8, Num2 = -8.

So the binary form of these numbers are - 

Num1 = 00000000 00000000 00000000 00001000  Num2 = 11111111 11111111 11111111  11111000

‘>>’ Operator : 8 >> 1 (Shift by one bit) : 

Num1 = 00000000 00000000 00000000 00000100 Num2 = 11111111 11111111 11111111  11111100

‘>>>’ Operator : 8 >>> 1 (Shift by one bit) = 

Num1 = 00000000 00000000 00000000 00000100 Num2 = 01111111 11111111 11111111 11111100

3. What are Composition and Aggregation? State the difference.

Composition, and Aggregation help to build (Has - A - Relationship) between classes and objects. But both are not the same in the end. Let’s understand with the help of an example. 

  • Consider the University as a class that has some departments in it. So the university will be the container object. And departments in it will contain objects. Now in this case, if the container object destroys then the contained objects will also get destroyed automatically.  So here we can say that there is a strong association between the objects. So this Strong Association is called Composition .
  • Now consider one more example. Suppose we have a class department and there are several professors' objects there in the department. Now if the department class is destroyed then the professor's object will become free to bind with other objects. Because container objects (Department) only hold the references of contained objects (Professor’s). So here is the weak association between the objects. And this weak association is called Aggregation .

4. How is the creation of a String using new() different from that of a literal?

When a String is formed as a literal with the assistance of an assignment operator, it makes its way into the String constant pool so that String Interning can take place. This same object in the heap will be referenced by a different String if the content is the same for both of them.

The checking() function will return true as the same content is referenced by both the variables.

case study questions in java

Conversely, when a String formation takes place with the help of a new() operator, interning does not take place. The object gets created in the heap memory even if the same content object is present.

The checking() function will return false as the same content is not referenced by both the variables.

case study questions in java

5. How is the ‘new’ operator different from the ‘newInstance()’ operator in java?

Both ‘ new ’ and ‘ newInstance() ’ operators are used to creating objects. The difference is- that when we already know the class name for which we have to create the object then we use a new operator. But suppose we don’t know the class name for which we need to create the object, Or we get the class name from the command line argument, or the database, or the file. Then in that case we use the ‘ newInstance() ’ operator.

The ‘ newInstance() ’ keyword throws an exception that we need to handle. It is because there are chances that the class definition doesn’t exist, and we get the class name from runtime. So it will throw an exception.

6. Is exceeding the memory limit possible in a program despite having a garbage collector?

Yes, it is possible for the program to go out of memory in spite of the presence of a garbage collector. Garbage collection assists in recognizing and eliminating those objects which are not required in the program anymore, in order to free up the resources used by them.

In a program, if an object is unreachable, then the execution of garbage collection takes place with respect to that object. If the amount of memory required for creating a new object is not sufficient, then memory is released for those objects which are no longer in the scope with the help of a garbage collector. The memory limit is exceeded for the program when the memory released is not enough for creating new objects.

Moreover, exhaustion of the heap memory takes place if objects are created in such a manner that they remain in the scope and consume memory. The developer should make sure to dereference the object after its work is accomplished. Although the garbage collector endeavors its level best to reclaim memory as much as possible, memory limits can still be exceeded.

Let’s take a look at the following example:

7. Why is synchronization necessary? Explain with the help of a relevant example.

Concurrent execution of different processes is made possible by synchronization. When a particular resource is shared between many threads, situations may arise in which multiple threads require the same shared resource.

Synchronization assists in resolving the issue and the resource is shared by a single thread at a time. Let’s take an example to understand it more clearly. For example, you have a URL and you have to find out the number of requests made to it. Two simultaneous requests can make the count erratic.

No synchronization:

case study questions in java

If a thread Thread1 views the count as 10, it will be increased by 1 to 11. Simultaneously, if another thread Thread2 views the count as 10, it will be increased by 1 to 11. Thus, inconsistency in count values takes place because the expected final value is 12 but the actual final value we get will be 11.

Now, the function increase() is made synchronized so that simultaneous accessing cannot take place.

With synchronization:

case study questions in java

If a thread Thread1 views the count as 10, it will be increased by 1 to 11, then the thread Thread2 will view the count as 11, it will be increased by 1 to 12. Thus, consistency in count values takes place.

8. In the given code below, what is the significance of ... ?

  • Ability to provide ... is a feature called varargs (variable arguments) which was introduced as part of Java 5.
  • The function having ... in the above example indicates that it can receive multiple arguments of the datatype String.
  • For example, the fooBarMethod can be called in multiple ways and we can still have one method to process the data as shown below:

9. What will be the output of the below java program and define the steps of Execution of the java program with the help of the below code?

The Output we get by executing this program will be

Static Block 1. Value of j = 0 Static method.  Static Block 2. Value of j = 10 Instance Block 1. Value of i = 0 Instance Block 2. Value of i = 5 Instance method.  Welcome to InterviewBit

This is a java tricky interview question frequently asked in java interviews for the experienced. The output will be like this because, when the java program is compiled and gets executed, then there are various steps followed for execution. And the steps are - 

  • Identification of Static Members from top to bottom.
  • Execution of Static variable assignment and a Static block from top to bottom.
  • Execution of the main method.
  • Identification of Instance Members from top to bottom.
  • Execution of Instance variable assignment and Instance block from top to bottom.
  • Execution of Constructor.

In above steps from 4 to 6, will be executed for every object creation. If we create multiple objects then for every object these steps will be performed.

Now from the above code, the execution will happen like this - 

1. In the step of identification of static members. It is found that -

  • static int j.
  • static block.
  • main method.
  • static method_2.

During identification, the JVM will assign the default value in the static int j variable. Then it is currently in the state of reading and indirectly writing. Because the original value is not assigned.

2. In the next step, it will execute the static block and assign the value in static variables.

  • First static block it will print and because execution from top to bottom and original value in j is not assigned. So it will print the default value of 0.
  • After executing static block 1. It will execute the static method_1 because it is called from the static block 1.
  • Then it will assign the original value of 5 in the j variable. And executes the remaining static block.

3. Now it will execute the main method. In which it will create an object for the class InterviewBit. And then the execution of instances will happen.

4. Identify the instance variables and blocks from top to bottom. 

  • Instance block 1.
  • Instance method_1.

Like a static variable, the instance variable also has been initialized with the default value 0 and will be in the state of reading and writing indirectly.

5. It will execute the instance methods and assign the original value to the instance variable.

  • Prints the Instance block 1. And the current value of i is not assigned till now, so it will print 0.
  • Assign the original value to i. Then print instance block 2. And after that instance method will be called and printed because it is being called in the instance block.

6. And at the last step, the constructor will be invoked and the lines will be executed in the constructor.

This is how the java program gets executed.

10. Define System.out.println().

System.out.println() is used to print the message on the console. System - It is a class present in java.lang package . Out is the static variable of type PrintStream class present in the System class. println() is the method present in the PrintStream class.

So if we justify the statement, then we can say that if we want to print anything on the console then we need to call the println() method that was present in PrintStream class. And we can call this using the output object that is present in the System class.

11. Can you explain the Java thread lifecycle?

Java thread life cycle is as follows:

  • New – When the instance of the thread is created and the start() method has not been invoked, the thread is considered to be alive and hence in the NEW state.
  • Runnable – Once the start() method is invoked, before the run() method is called by JVM, the thread is said to be in RUNNABLE (ready to run) state. This state can also be entered from the Waiting or Sleeping state of the thread.
  • Running – When the run() method has been invoked and the thread starts its execution, the thread is said to be in a RUNNING state.
  • A thread is said to be in a Blocked state if it wants to enter synchronized code but it is unable to as another thread is operating in that synchronized block on the same object. The first thread has to wait until the other thread exits the synchronized block.
  • A thread is said to be in a Waiting state if it is waiting for the signal to execute from another thread, i.e it waits for work until the signal is received.
  • Terminated – Once the run() method execution is completed, the thread is said to enter the TERMINATED step and is considered to not be alive.

The following flowchart clearly explains the lifecycle of the thread in Java.

case study questions in java

12. What could be the tradeoff between the usage of an unordered array versus the usage of an ordered array?

  • The main advantage of having an ordered array is the reduced search time complexity of O(log n) whereas the time complexity in an unordered array is O(n) .
  • The main drawback of the ordered array is its increased insertion time which is O(n) due to the fact that its element has to reordered to maintain the order of array during every insertion whereas the time complexity in the unordered array is only O(1).
  • Considering the above 2 key points and depending on what kind of scenario a developer requires, the appropriate data structure can be used for implementation.

13. Is it possible to import the same class or package twice in Java and what happens to it during runtime?

It is possible to import a class or package more than once, however, it is redundant because the JVM internally loads the package or class only once.

14. In case a package has sub packages, will it suffice to import only the main package? e.g. Does importing of com.myMainPackage.* also import com.myMainPackage.mySubPackage.*?

This is a big NO. We need to understand that the importing of the sub-packages of a package needs to be done explicitly. Importing the parent package only results in the import of the classes within it and not the contents of its child/sub-packages.

15. Will the finally block be executed if the code System.exit(0) is written at the end of try block?

NO. The control of the program post System.exit(0) is immediately gone and the program gets terminated which is why the finally block never gets executed.

16. What do you understand by marker interfaces in Java?

Marker interfaces, also known as tagging interfaces are those interfaces that have no methods and constants defined in them. They are there for helping the compiler and JVM to get run time-related information regarding the objects.

17. Explain the term “Double Brace Initialisation” in Java?

This is a convenient means of initializing any collections in Java. Consider the below example.

In the above example, we see that the stringSets were initialized by using double braces.

  • The first brace does the task of creating an anonymous inner class that has the capability of accessing the parent class’s behavior. In our example, we are creating the subclass of HashSet so that it can use the add() method of HashSet.
  • The second braces do the task of initializing the instances.

Care should be taken while initializing through this method as the method involves the creation of anonymous inner classes which can cause problems during the garbage collection or serialization processes and may also result in memory leaks.

18. Why is it said that the length() method of String class doesn't return accurate results?

  • The length method returns the number of Unicode units of the String. Let's understand what Unicode units are and what is the confusion below.
  • Code Point: This represents an integer denoting a character in the code space.
  • Code Unit: This is a bit sequence used for encoding the code points. In order to do this, one or more units might be required for representing a code point.
  • The code points from the first plane are encoded using one 16-bit code unit
  • The code points from the remaining planes are encoded using two code units.

Now if a string contained supplementary characters, the length function would count that as 2 units and the result of the length() function would not be as per what is expected.

In other words, if there is 1 supplementary character of 2 units, the length of that SINGLE character is considered to be TWO - Notice the inaccuracy here? As per the java documentation, it is expected, but as per the real logic, it is inaccurate.

19. What is the output of the below code and why?

“bit” would have been the result printed if the letters were used in double-quotes (or the string literals). But the question has the character literals (single quotes) being used which is why concatenation wouldn't occur. The corresponding ASCII values of each character would be added and the result of that sum would be printed. The ASCII values of ‘b’, ‘i’, ‘t’ are:

98 + 105 + 116 = 319

Hence 319 would be printed.

20. What are the possible ways of making object eligible for garbage collection (GC) in Java?

First Approach: Set the object references to null once the object creation purpose is served.

Second Approach: Point the reference variable to another object. Doing this, the object which the reference variable was referencing before becomes eligible for GC.

Third Approach: Island of Isolation Approach: When 2 reference variables pointing to instances of the same class, and these variables refer to only each other and the objects pointed by these 2 variables don't have any other references, then it is said to have formed an “Island of Isolation” and these 2 objects are eligible for GC.

21. In the below Java Program, how many objects are eligible for garbage collection?

In the above program, a total of 7 objects will be eligible for garbage collection. Let’s visually understand what's happening in the code.

case study questions in java

In the above figure on line 3, we can see that on each array index we are declaring a new array so the reference will be of that new array on all the 3 indexes. So the old array will be pointed to by none. So these three are eligible for garbage collection. And on line 4, we are creating a new array object on the older reference. So that will point to a new array and older multidimensional objects will become eligible for garbage collection.

22. What is the best way to inject dependency? Also, state the reason.

There is no boundation for using a particular dependency injection. But the recommended approach is - 

Setters are mostly recommended for optional dependencies injection, and constructor arguments are recommended for mandatory ones. This is because constructor injection enables the injection of values into immutable fields and enables reading them more easily.

23. How we can set the spring bean scope. And what supported scopes does it have?

A scope can be set by an annotation such as the @Scope annotation or the "scope" attribute in an XML configuration file. Spring Bean supports the following five scopes:

  • Global-session

24. What are the different categories of Java Design patterns?

Java Design patterns are categorized into the following different types. And those are also further categorized as 

Structural patterns:

Behavioral patterns:

  • Interpreter
  • Template method/ pattern
  • Chain of responsibility
  • Command pattern
  • Iterator pattern
  • Strategy pattern
  • Visitor pattern

J2EE patterns:

  • MVC Pattern
  • Data Access Object pattern
  • Front controller pattern
  • Intercepting filter pattern
  • Transfer object pattern

Creational patterns:

  • Factory method/Template
  • Abstract Factory

25. What is a Memory Leak? Discuss some common causes of it.

The Java Garbage Collector (GC) typically removes unused objects when they are no longer required, but when they are still referenced, the unused objects cannot be removed. So this causes the memory leak problem. Example - Consider a linked list like the structure below -

case study questions in java

In the above image, there are unused objects that are not referenced. But then also Garbage collection will not free it. Because it is referencing some existing referenced object. So this can be the situation of memory leak.

Some common causes of Memory leaks are - 

  • When there are Unbounded caches.
  • Excessive page swapping is done by the operating system.
  • Improper written custom data structures.
  • Inserting into a collection object without first deleting it. etc.

26. Assume a thread has a lock on it, calling the sleep() method on that thread will release the lock?

A thread that has a lock won't be released even after it calls sleep(). Despite the thread sleeping for a specified period of time, the lock will not be released.

1. Check if a given string is palindrome using recursion.

/* * Java program to check if a given inputted string is palindrome or not using recursion. */ import java.util.*; public class InterviewBit { public static void main (String args[]) { Scanner s = new Scanner(System.in); String word = s.nextLine(); System.out.println( "Is " +word+ " palindrome? - " +isWordPalindrome(word)); } public static boolean isWordPalindrome (String word) { String reverseWord = getReverseWord(word); //if word equals its reverse, then it is a palindrome if (word.equals(reverseWord)){ return true ; } return false ; } public static String getReverseWord (String word) { if (word == null || word.isEmpty()){ return word; } return word.charAt(word.length()- 1 ) + getReverseWord(word.substring( 0 , word.length() - 1 )); } }

2. Write a Java Program to print Fibonacci Series using Recursion.

In the above code, we are printing the base 2 Fibonacci values 0 and 1. And then based on the length of Fibonacci to be printed, we are using the helper function to print that.

3. Write a Java program to check if the two strings are anagrams.

The main idea is to validate the length of strings and then if found equal, convert the string to char array and then sort the arrays and check if both are equal.

4. Write a Java Program to find the factorial of a given number.

public class FindFactorial { public static void main (String[] args) { int num = 10 ; long factorialResult = 1l ; for ( int i = 1 ; i <= num; ++i) { factorialResult *= i; } System.out.println( "Factorial: " +factorialResult); } }

5. Given an array of non-duplicating numbers from 1 to n where one number is missing, write an efficient java program to find that missing number.

Idea is to find the sum of n natural numbers using the formula and then finding the sum of numbers in the given array. Subtracting these two sums results in the number that is the actual missing number. This results in O(n) time complexity and O(1) space complexity.

6. Write a Java Program to check if any number is a magic number or not. A number is said to be a magic number if after doing sum of digits in each step and inturn doing sum of digits of that sum, the ultimate result (when there is only one digit left) is 1.

Example, consider the number:

  • Step 1: 163 => 1+6+3 = 10
  • Step 2: 10 => 1+0 = 1 => Hence 163 is a magic number

7. Write a Java program to create and throw custom exceptions.

We have created the exception class named with CustomException and called the base exception constructor with the error message that we want to print. And to avoid handling exceptions in the main method, we have used the throws keyword in the method declaration.

8. Write a Java program to reverse a string.

In the above code, we are storing the last character from the string to the first and the first value to the last in the output character array. And doing the same thing in the loop for the remaining 2nd to n-1 characters. This is how the string will be reversed.

9. Write a Java program to rotate arrays 90 degree clockwise by taking matrices from user input.

In the above code, for rotating the matrix to  90 degrees we are first transposing the matrix so the row becomes the column. And after that, we are reversing each row in the matrix. So this is how the matrix got rotated.

10. Write a java program to check if any number given as input is the sum of 2 prime numbers.

18 = 13 + 5 18 = 11 + 7

In the above code, for any number n , we find all the 2 pairs of numbers that are added together resulting in n . And each checking number if it is prime. If it is prime then we are printing that.

11. Write a Java program for solving the Tower of Hanoi Problem.

In the above code we are first moving the n-1 disk from Tower A to Tower B , then moving that nth disk from Tower A to Tower C , and finally, the remaining n-1 disk from Tower B to Tower C . And we are doing this recursively for the n-1 disk.

12. Implement Binary Search in Java using recursion.

In the above code, we are finding the middle element each time and checking if the element is in the middle or not. If it is not, then we check on which side from the middle it exists. And Recursively searching on the particular subarray. So this way we are reducing the search space by 2 every time. So the search time is very low.

1. Conclusion

Java is one of the simple high-level languages that provides powerful tools and impressive standards required for application development. It was also one of the first languages to provide amazing threading support for tackling concurrency-based problems. The easy-to-use syntax and the built-in features of Java combined with the stability it provides to applications are the main reasons for this language has ever-growing usage in the software community.

Interview Preparation Resources

  • How to Become a Java Developer?
  • How much does a Java Developer earn in India?
  • Java Projects
  • Java Programming Questions for Interview
  • Java 8 Interview Questions
  • Java String Interview Questions
  • Spring Interview Questions
  • Hibernate Interview Questions
  • Java Collections Interview Questions
  • Array Interview Questions
  • Design Patterns Interview Questions
  • Multithreading Interview Questions
  • Java Tutorial
  • Advance Java MCQ
  • Difference Between C++ and Java
  • Difference Between C and Java
  • Difference Between Java and Javascript
  • Hashmap vs Hashtable in Java
  • Kotlin Vs Java
  • Java Vs Python
  • Features of Java 9
  • Java 8 Features
  • Java Frameworks
  • Java Developer Skills
  • Java 11 Features
  • Additional Technical Interview Questions
  • JAVA SE Download

Coding Problems

What is the output of the below code?

What component does the task of bytecode to machine code conversion?

Which of the following happens when the garbage collection process kicks off during the execution of the thread?

What is the functionality of Class.getInstance() ?

What is the output of the below piece of code?

What is the output of the following code?

Which of the following is the functionality of the java interpreter?

What is the component used for compiling, debugging, and executing java programs?

When an object has its own lifecycle and its child object cant belong to another parent object, what is it called?

  • Privacy Policy


  • Practice Questions
  • Programming
  • System Design
  • Fast Track Courses
  • Online Interviewbit Compilers
  • Online C Compiler
  • Online C++ Compiler
  • Online Java Compiler
  • Online Javascript Compiler
  • Online Python Compiler
  • Interview Preparation
  • Sql Interview Questions
  • Python Interview Questions
  • Javascript Interview Questions
  • Angular Interview Questions
  • Networking Interview Questions
  • Selenium Interview Questions
  • Data Structure Interview Questions
  • Data Science Interview Questions
  • System Design Interview Questions
  • Hr Interview Questions
  • Html Interview Questions
  • C Interview Questions
  • Amazon Interview Questions
  • Facebook Interview Questions
  • Google Interview Questions
  • Tcs Interview Questions
  • Accenture Interview Questions
  • Infosys Interview Questions
  • Capgemini Interview Questions
  • Wipro Interview Questions
  • Cognizant Interview Questions
  • Deloitte Interview Questions
  • Zoho Interview Questions
  • Hcl Interview Questions
  • Highest Paying Jobs In India
  • Exciting C Projects Ideas With Source Code
  • Top Java 8 Features
  • Angular Vs React
  • 10 Best Data Structures And Algorithms Books
  • Best Full Stack Developer Courses
  • Best Data Science Courses
  • Python Commands List
  • Data Scientist Salary
  • Maximum Subarray Sum Kadane’s Algorithm
  • Python Cheat Sheet
  • C++ Cheat Sheet
  • Javascript Cheat Sheet
  • Git Cheat Sheet
  • Java Cheat Sheet
  • Data Structure Mcq
  • C Programming Mcq
  • Javascript Mcq

1 Million +

  • Software Developers
  • Java Developers

Java Development Case Studies And Success Stories

by Ideamotive Talent

Take a look at these Java case studies to see how our developers have served clients in numerous industries. With each project analysis, you’ll be able to shape a general impression about our developers, their experience, and their skills. Every time we’re making our best effort to enhance the clients’ business and strengthen their positions on the market.

Here, you’ll discover about:

  • Client’s business, the targets, and challenges they faced during the project’s implementation.
  • What results they expect from our company and why they’ve chosen us.
  • Our detailed step-by-step project analysis, specific methods, technologies, and tools we’ve used to succeed.
  • The major challenges our team has faced, and the solution we’ve chosen to resolve the client’s problem.
  • The final results our team has presented to the clients - what has been changed and the benefits our clients get with the outcome.

Napoli Gang: reinventing food delivery for a European delivery-based restaurant chain

How we developed a fast, scalable mobile solution from scratch for an estimated target audience of 10,000 users.

Napoli Gang

Food Service

im_napoli_gang_2880x1276_hero_desktop-01 (1)

JRPass: Marrying web development and business processes support

How to optimize booking system for a Japanese railway network and increase sales?


TRAVELDUCK: building a marketplace for boutique adventure trips and activities

How we created a fully functional digital marketplace from scratch and helped the Client validate the business model for scaling up.

Travel, Marketplace


There are hundreds of battle-proven experts in our Talent Network.

What our Clients say about us:

We’ve been extremely satisfied. We work with multiple partners, but they’re our main supplier because of the quality of their work.


Håkon Årøen

Co-founder & CTO of Memcare

Ideamotive has a huge pool of talent. Don’t just settle for someone: find a person who understands your project and has the competencies you need.


Julian Peterson

President, Luminate Enterprises

They understand and navigate the industry to deliver an outcome that will truly stand out. Despite a heavily saturated market, they’ve delivered creative solutions that I haven’t seen before.

adam buchanan

Adam Casole-Buchanan

President, Rierra INC

They are very flexible, providing a team of developers on short notice and scaling the size as needed. Their team meets tight deadlines, including some that only give them a few hours to do the work.


Sylvain Bernard

Event Manager, Swiss Federal Institute of Technology Lausanne

Startups , scale-ups and enterprises build their teams with Ideamotive


Other Java developers hiring and business resources:

Java Developers Interview Questions

Java Developer Job Description And Ad

Java Development Company

Java Freelancers

The Business Side of Java Development [Guide]


Business registry data:

[email protected]

Most desired experts

Rated 4.9 / 5.0 by 25 clients for web development, mobile development and design services.

DEV Community

DEV Community

Posted on Mar 23, 2019 • Updated on Jan 28, 2023

50+ Data Structure and Algorithms Problems from Coding Interviews

Disclosure: This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article.

data structure and algorithms interview questions

There are a lot of computer science graduates and programmers applying for programming, coding, and software development roles at startups like Uber and Netflix; big organizations like Amazon , Microsoft , and Google ; and service-based companies like Infosys or Luxsoft, but many of them have no idea of what kind of programming interview questions to expect when you're applying for a job with these companies.

In this article, I'll share some frequently asked programming interview questions from different Job interviews for programmers at different levels of experience,from people who have just graduated from college to programmers with one to two years of experience.

Coding interviews are comprised mainly of d ata structure and algorithm-based questions as well as some of the logical questions such as, How do you swap two integers without using a temporary variable?

I think it's helpful to divide coding interview questions into different topic areas.

The topic areas I've seen most often in interviews are array , linked list , string , binary tree , as well as questions from algorithms like string algorithm, sorting algorithms like quicksort or radix sort , and other miscellaneous ones), and that's what you will find in this article.

It's not guaranteed that you will be asked these coding or data structure and algorithmic questions, but they will give you enough of an idea of the kinds of questions you can expect in a real programming job interview.

Once you have gone through these questions, you should feel confident enough to attend any telephonic or face-to-face interviews.

Btw, there is no point in attempting these questions if you don't have sufficient knowledge of essential Data Structure and Algorithms or you have not touched them for ages.

In that case, you should take a good introductory course like Data Structures and Algorithms: Deep Dive Using Java to refresh your DS and algorithms skills.

best online courses to learn Data Structure and Algorithms

Top 50 Algorithms and Coding Interview Questions

Without any further ado, here is my list of some of the most frequently asked coding interview questions from programming job interviews :

1. Array Coding Interview Questions

An array is the most fundamental data structure, which stores elements at a contiguous memory location. It is also one of the darling topics of interviewers and you will hear a lot of questions about an array in any coding interview , like reversing an array, sorting the array, or searching elements on the array.

The key benefit of an array data structure is that it offers fast O(1) search if you know the index, but adding and removing an element from an array is slow because you cannot change the size of the array once it's created.

In order to create a shorter or longer array, you need to create a new array and copy all elements from old to new.

The key to solving array-based questions is having a good knowledge of array data structure as well as basic programming constructors such as loop, recursion, and fundamental operators.

Here are some tips to solve array based coding problems:

  • array index starts at zero
  • You can use loops to iterate over array
  • array elements are stored in contiguous memory location so you can also access them using pointer arithmetic
  • Array provides O(1) performance for search using index
  • Adding or removing elements are slower in array due to re-sizing

Here are some of the popular array-based coding interview questions for your practice:

  • How do you find the missing number in a given integer array of 1 to 100 ? ( solution )
  • How do you find the duplicate number on a given integer array? ( solution )
  • How do you find the largest and smallest number in an unsorted integer array? ( solution )
  • How do you find all pairs of an integer array whose sum is equal to a given number?( solution )
  • How do you find duplicate numbers in an array if it contains multiple duplicates?( solution )
  • How are duplicates removed from a given array in Java? ( solution )
  • How is an integer array sorted in place using the quicksort algorithm? ( solution )
  • How do you remove duplicates from an array in place? ( solution )
  • How do you reverse an array in place in Java? ( solution )
  • How are duplicates removed from an array without using any library? ( solution )

These questions will not only help you to develop your problem-solving skills but also improve your knowledge of the array data structure.

If you need more advanced questions based upon array then you can see also see The Coding Interview Bootcamp: Algorithms + Data Structures , a Bootcamp style course on algorithms, especially designed for interview preparation to get a job on technical giants like Google, Microsoft, Apple, Facebook, etc.

array coding problems for technical interviews

And, if you feel 10 is not enough questions and you need more practice, then you can also check out this list of 30 array questions .

2. Linked List Programming Interview Questions

A linked list is another common data structure that complements the array data structure. Similar to the array, it is also a linear data structure and stores elements in a linear fashion.

However, unlike the array, it doesn't store them in contiguous locations; instead, they are scattered everywhere in memory, which is connected to each other using nodes.

A linked list is nothing but a list of nodes where each node contains the value stored and the address of the next node.

Because of this structure, it's easy to add and remove elements in a linked list , as you just need to change the link instead of creating the array, but the search is difficult and often requires O(n) time to find an element in the singly linked list.

This article provides more information on the difference between an array and linked list data structures.

It also comes in varieties like a singly linked list, which allows you to traverse in one direction (forward or reverse); a doubly linked list , which allows you to traverse in both directions (forward and backward); and finally, the circular linked list, which forms a circle.

In order to solve linked list-based questions, a good knowledge of recursion is important, because a linked list is a recursive data structure .

If you take one node from a linked list, the remaining data structure is still a linked list, and because of that, many linked list problems have simpler recursive solutions than iterative ones.

Here are some of the most common and popular linked list interview questions and their solutions:

  • How do you find the middle element of a singly linked list in one pass? ( solution )
  • How do you check if a given linked list contains a cycle? How do you find the starting node of the cycle? ( solution )
  • How do you reverse a linked list? ( solution )
  • How do you reverse a singly linked list without recursion? ( solution )
  • How are duplicate nodes removed in an unsorted linked list? ( solution )
  • How do you find the length of a singly linked list? ( solution )
  • How do you find the third node from the end in a singly linked list? ( solution )
  • How do you find the sum of two linked lists using Stack? ( solution )

These questions will help you to develop your problem-solving skills as well as improve your knowledge of the linked list data structure.

If you are having trouble solving these linked list coding questions then I suggest you refresh your data structure and algorithms skill by going through Data Structures and Algorithms: Deep Dive ** Using Java** course.

linked list coding problems and solutions

You can also check out this list of 30 linked list interview questions for more practice questions.

3. String Coding Interview Questions

Along with array and linked list data structures, a string is another popular topic on programming job interviews. I have never participated in a coding interview where no string-based questions were asked.

A good thing about the string is that if you know the array, you can solve string-based questions easily because strings are nothing but a character array .

So all the techniques you learn by solving array-based coding questions can be used to solve string programming questions as well.

Here is my list of frequently asked string coding questions from programming job interviews:

  • How do you print duplicate characters from a string? ( solution )
  • How do you check if two strings are anagrams of each other? ( solution )
  • How do you print the first non-repeated character from a string? ( solution )
  • How can a given string be reversed using recursion? ( solution )
  • How do you check if a string contains only digits? ( solution )
  • How are duplicate characters found in a string? ( solution )
  • How do you count a number of vowels and consonants in a given string? ( solution )
  • How do you count the occurrence of a given character in a string? ( solution )
  • How do you find all permutations of a string? ( solution )
  • How do you reverse words in a given sentence without using any library method? ( solution )
  • How do you check if two strings are a rotation of each other? ( solution )
  • How do you check if a given string is a palindrome? ( solution )

These questions help improve your knowledge of string as a data structure. If you can solve all these String questions without any help then you are in good shape.

For more advanced questions, I suggest you solve problems given in the Algorithm Design Manual by Steven Skiena , a book with the toughest algorithm questions.

String coding problems for programming interviews

If you need more practice, here is another list of 20 string coding questions .

4. Binary Tree Coding Interview Questions

So far, we have looked at only the linear data structure, but all information in the real world cannot be represented in a linear fashion, and that's where tree data structure helps.

The tree data structure is a data structure that allows you to store your data in a hierarchical fashion. Depending on how you store data, there are different types of trees, such as a binary tree , where each node has, at most, two child nodes.

Along with its close cousin binary search tree , it's also one of the most popular tree data structures. Therefore, you will find a lot of questions based on them, such as how to traverse them, count nodes, find depth, and check if they are balanced or not.

A key point to solving binary tree questions is a strong knowledge of theory, like what is the size or depth of the binary tree, what is a leaf, and what is a node, as well as an understanding of the popular traversing algorithms, like pre-, post-, and in-order traversal.

Here is a list of popular binary tree-based coding questions from software engineer or developer job interviews:

  • How is a binary search tree implemented? ( solution )
  • How do you perform preorder traversal in a given binary tree?( solution )
  • How do you traverse a given binary tree in preorder without recursion?( solution )
  • How do you perform an inorder traversal in a given binary tree?*( solution )
  • How do you print all nodes of a given binary tree using inorder traversal without recursion? ( solution )
  • How do you implement a postorder traversal algorithm? ( solution )
  • How do you traverse a binary tree in postorder traversal without recursion?( solution )
  • How are all leaves of a binary search tree printed?( solution )
  • How do you count a number of leaf nodes in a given binary tree?( solution )
  • How do you perform a binary search in a given array?( solution )

If you feel that your understanding of binary tree coding is inadequate and you can't solve these questions on your own, I suggest you go back and pick a good data structure and algorithm course like From 0 to 1: Data Structures & Algorithms in Java .

binary tree coding problems for interviews

If you need some more recommendations, here is my list of useful data structure algorithm books and courses to start with.

5. Miscellaneous Coding Interview Questions

Apart from data structure-based questions, most of the programming job interviews also ask algorithms , software design , bit manipulation, and general logic-based questions, which I'll describe in this section.

It's important that you practice these concepts because sometimes they become tricky to solve in the actual interview. Having practiced them before not only makes you familiar with them but also gives you more confidence in explaining the solution to the interviewer.

  • How is a bubble sort algorithm implemented? ( solution )
  • How is an iterative quicksort algorithm implemented? ( solution )
  • How do you implement an insertion sort algorithm? ( solution )
  • How is a merge sort algorithm implemented? ( solution )
  • How do you implement a bucket sort algorithm?( solution )
  • How do you implement a counting sort algorithm?( solution )
  • How is a radix sort algorithm implemented?( solution )
  • How do you swap two numbers without using the third variable? ( solution )
  • How do you check if two rectangles overlap with each other? ( solution )
  • How do you design a vending machine? ( solution )

If you need more such coding questions you can take help from books like Cracking The Code Interview , by Gayle Laakmann McDowell which presents 189+ Programming questions and solution. A good book to prepare for programming job interviews in a short time.

coding interview questions for beginners

By the way, the more questions you solve in practice, the better your preparation will be. So, if you think 50 is not enough and you need more, then check out these additional 50 programming questions for telephone interviews and these books and courses for more thorough preparation.

Now You're Ready for the Coding Interview

These are some of the most common questions outside of data structure and algorithms that help you to do really well in your interview.

I have also shared a lot of these questions on my blog , so if you are really interested, you can always go there and search for them.

These common coding, data structure, and algorithm questions are the ones you need to know to successfully interview with any company, big or small, for any level of programming job.

If you are looking for a programming or software development job, you can start your preparation with this list of coding questions.

This list provides good topics to prepare and also helps assess your preparation to find out your areas of strength and weakness.

Good knowledge of data structure and algorithms is important for success in coding interviews and that's where you should focus most of your attention.

Further Learning Data Structures and Algorithms: Deep Dive Using Java Master the Coding Interview: Data Structures + Algorithms by Andrei Negaoie Grokking the Coding Interview: Patterns for Coding Questions Algorithms and Data Structures - Part 1 and 2 10 Books to Prepare Technical Programming/Coding Job Interviews 10 Algorithm Books Every Programmer Should Read Top 5 Data Structure and Algorithm Books for Java Developers From 0 to 1: Data Structures & Algorithms in Java Data Structure and Algorithms Analysis --- Job Interview

Closing Notes

Thanks, You made it to the end of the article ... Good luck with your programming interview! It's certainly not going to be easy, but by following this roadmap and guide, you are one step closer to becoming a DevOps engineer .

If you like this article, then please share it with your friends and colleagues, and don't forget to follow javinpaul on Twitter!

P.S. --- If you need some FREE resources, you can check out this list of free data structure and algorithm courses to start your preparation.

Top comments (16).


Templates let you quickly answer FAQs or store snippets for re-use.

iamshadmirza profile image

  • Location Bengaluru, India
  • Work Full Stack Developer at Hashnode
  • Joined Mar 6, 2019

This article is like a Gold mine for me. Thanks a lot

  • Joined Sep 16, 2018

Thanks Mohd Shad Mirza

aershov24 profile image

  • Location Perth, Western Australia
  • Education Moscow Aviation Institute
  • Work Founder at FullStack.Cafe
  • Joined Jul 14, 2018

Thanks a lot for the article, it's very helpful! For more Data Structures and Coding Interview Questions check my blog posts on fullstack.cafe . Hope it will help anyone to crack your next coding interview!

gofacademy profile image

  • Location New Delhi
  • Joined Feb 23, 2022

GOF Academy is one of the Best IIT, Neet Coaching Institute in Kalu Sarai, Live Coaching Classes For Neet Preparation. Enquire Now For Admission Fees gofacademy.in/iit-coaching-in-kalu...

Are you preparing for competitive exams like IIT, NEET, NTSE, Olympiads, KVPY, UPSC or JEE? You must be looking for best coaching institute in Delhi, which can guide you in your competitive exam preparation. Aspirant must opt for GOF Academy that serves as the best IIT Coaching institutes in Delhi providing one stop exam solutions with study material, test series, and lectures. Our highly experienced faculties put in great efforts to clear the concept in aspirant’s mind with their short tricks. With the utmost support of lecturers and state of the art educational infrastructures, we are able to provide high-quality engineering education. If you searching for coaching institute in Delhi for IIT-JEE, NEET and foundation course, Call at 8700484442 to book your slot. Admission open, Limited Seats. Visit gofacademy.in

fatema110 profile image

  • Location Mumbai
  • Education CSE Undegrad Student at Mumbai University
  • Joined Sep 14, 2020

Thanks a lot

mackensonrgina2 profile image

  • Joined Jun 9, 2021

Hello. How can I initialize objects like Arrays, List in a constructor?

yogeshwarvhatkar profile image

  • Location Pune
  • Education BE IT, MBA Systems Mgmt.
  • Work Technical Lead at BNT Soft Pvt Ltd.
  • Joined Feb 22, 2020

Thanks for sharing.

siriusjt99 profile image

Thanks for your content!

ukantjadia profile image

  • Email [email protected]
  • Location India
  • Education Sir Padampat Singhania University
  • Work Student | Most of the time i am teacher to myself. ( A Strict one)
  • Joined Oct 8, 2021


bitpunchz profile image

  • Joined Jan 23, 2019

another awesome article :D

let me know what you think about this:


Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

fullstackjava profile image

How to Integrate Embedded MongoDB for Unit Testing in a Spring Application

FullStackJava - Jun 23

labby profile image

7 Captivating C++ Programming Challenges from LabEx 🧠

Labby - Jun 19

lenormor profile image

The Advantages of Gantt Charts in JavaScript for Project Management

Gaetan Gasoline - Jun 18

vuyokazimkane profile image

Mastering SQL Databases: In-Depth Guide

Vuyokazi Mkane - Jul 2

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Case Study in java

Could anyone provide me information where I can find the case study for java coding and design practice.

Basically looking for a case studies which resemble to the real time application like pet Store application, flight search application.

TylerH's user avatar

  • 1 sounds like homework. more details, on what you want to accomplish here, is required. –  Nishant Commented Jan 4, 2011 at 6:29
  • Hi Nishant, I am looking to learn the java concepts like multi thread, collections from a business point of view. Like for a given scenario what collection class to use. –  Kamal Commented Jan 4, 2011 at 7:03
  • Something worth nothing is that "real time" has a specific meaning and is not the same real world. The Pet Store application isn't real-time and possibly not that close to a real-world application either. ;) –  Peter Lawrey Commented Jan 4, 2011 at 7:08
  • @Peter- I mean case studies which will help me the to learn how to apply the java concepts for best result. –  Kamal Commented Jan 4, 2011 at 7:19
  • If you want real world code, I suggest you look at some of the popular open source packages. e.g. download.java.net/openjdk/jdk6 java-sources.net This should ive you a few million lines of code. –  Peter Lawrey Commented Jan 4, 2011 at 17:08

The Design Patterns Java Companion teaches good design practices with the help of small Java applications. (Not sure if the free online copy of this book is legal or not).

Vijay Mathew's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged java or ask your own question .

  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Mathematical Realism and 0=1
  • How to POSIX-ly ignore "warning: command substitution: ignored null byte in input"?
  • How do I know that my saddle fits me
  • What is the best epoch to evaluate the test images?
  • Does there exist a Dehn filling of an irreducible 3-manifold with toroidal boundaries which is still irreducible?
  • How are Boggarts created?
  • How do we define addition?
  • Different letters, different grids
  • Signature of Rav Ovadia Hedaya
  • a question about silicon diode
  • Paid for checked bag: will I have to pay if they force me to gate-check it?
  • Why does black have a higher win rate in Exchange French?
  • Mathematica integral wrong
  • We have differing types of infinity; do we also have differing types of randomness?
  • Simulate slow disks in KVM to see effect of LVM cache in test setup
  • Can a big mass defect make the mass negative?
  • MOSFET Datasheet Confusion
  • Beginner level password generator optimization
  • Directions of puff pastry folds
  • Is "sinnate" a word? What does it mean?
  • Why does Google Maps only rotate 90º but not 180º when I rotate my iPhone?
  • Have human infant foreskins been put into commercial cosmetic products?
  • Recommend an essay, article, entry, author, or branch of philosophy that addresses the futility of arguing for or against free will
  • Coincidence between coefficients of tanh(tan(x/2) and Chow ring computations?

case study questions in java

Javatpoint Logo

Java Tutorial

Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.


You need to load stock exchange security codes with price from a database and cache them for performance. The security codes need to be refreshed say every 30 minutes. This cached data needs to be populated and refreshed by a single writer thread and read by several reader threads. How will you ensure that your read/write solution is scalable and thread safe?

The java.util.concurrent.locks package provides classes that implement read/write locks where the read lock can be executed in parallel by multiple threads and the write lock can be held by only a single thread. The ReadWriteLock interface maintains a pair of associated locks, one for read-only and one for writing. The readLock( ) may be held simultaneously by multiple reader threads, while the writeLock( ) is exclusive. In general, this implementation improves performance and scalability when compared to the mutex locks (i.e. via synchronized key word) when

If you have a requirement to generate online reports or feed files by pulling out millions of historical records from a database, what questions will you ask, and how will you go about designing it?

Designing a system is all about asking the right questions to gather requirements.

Online Vs Offline? Should we restrict the online reports for only last 12 months of data to minimise the report size and to get better performance, and provide reports/feeds for the data older than 12 months via offline processing? For example, Bank statements for last 12 months via online & for transactions older than 12 months via offline asynchronous processing without blocking the customer from browsing rest of the website. Reports can be generated asynchronously and once ready can be emailed or downloaded via a URL at a later time.

What report generation framework to use like Jasper Reports, Open CSV, XSL-FO with Apache FOP, etc depending on the required output formats?

How to handle exceptional scenarios? send an error email, use a monitoring system like Tivoli or Nagios to raise production support tickets on failures, etc?

Security requirements. Are we sending feed/report with PII (i.e. Personally Identifiable Information) data via email? Do we need proper access control to restrict who can generate which online reports? Should we password protect the email attachments? Are there any compliance or regulatory requirements like PCI (i.e. Payment Card Industry), GDPR (i.e. General Data Protection Regulation), ACCC (i.e. Australian Competition and Consumer Commission), etc depending on the jurisdictions served by the application?

Should we schedule the offline reports to run during off peak time? For example, enter all the requests for a report into a "Request" table and then schedule a process to run at say midnight to refer to all pending requests in the "Request" table to generate and store the relevant reports in an outbox for the customers to download. An email can be sent to clients with the report URL to download the report.

Archival and purging straggles of the historical reports. What is the report retention period for the requirements relating to auditing and compliance purpose? How big are the files?

An online application with a requirement to produce time consuming reports or a business process (e.g. re-balancing accounts, aggregating hierarchical information, etc) could benefit from making these long running operations asynchronous. Once the reports or the long running business process is completed, the outcome can be communicated to the user via emails or asynchronously refreshing the web page via techniques known as "server push (JEE Async Servlet)" or "client pull (Refresh meta tag)". A typical example would be

We need to find and change a text from 'Client' to 'Customer' in 350+ html files.

Reference counting where a shared resource is incremented or decremented. The increment/decrement operations must be thread safe. For example, a counter that keeps track of the number of active logged in users by incrementing the count when users log in and decrementing the count when the users log out. Sometimes you want to allow a finite number of concurrent accesses say 3 users at a time.

is a single key to an object (E.g. a toilet). One person can have the key and occupy the toilet at the time. When finished, the person gives (or releases) the key to the next person in the queue. In Java, every object has a mutex and only a single thread can get hold of a mutex.

Is a number of free identical toilet keys. For example, having 3 toilets with identical locks and keys. The semaphore count is set to 3 at beginning and then the count is decremented as people are acquiring the key to the toilets. If all toilets are full, i.e. there are no free keys left, the semaphore count is 0. Now, when one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.

We are asked to design an application, which validates data with 100+ rules to comply with the government compliance requirements and tax laws. These compliance requirements can change and the application need to quickly and easily adapt to changing requirements.

Harness the power of Rules Engines like Drools. Drools is a popular open source business rules and work flow engine. It helps you externalise the rules in database tables or excel spreadsheets as opposed to embedding within the Java code. The rules are executed in the form of when given a ($condition) then execute the ($consequence). The business will be the custodian of these rules that can be easily viewed on an excel spreadsheet or via querying the database tables. A GUI could be built to maintain these rules that reside in a database.

We have a requirement to maintain a history of insertion, modification, and deletion to the "Customer" table. How will you go about accomplishing this?

There is a list of students with their (name, grades). We have to find the name of the student who has the highest grade.

We have Given a list of strings and we have to convert them to uppercase using Java 8 streams.

For the given list of elements, perform Filtering and Sorting on the elements. Write a Java 8 program to perform operations like filter out the odd numbers from list and sort the remaining ones in ascending order.

For the given transaction data with (payer, payee, amount), calculate the total amount received by each payee. Here you have to use the grouping and Summing concept of Java 8.

In the retail marketplace, there are multiple transactions that happen from time to time. We have to perform the data analysis over the revenue.

For the Given list of sales transactions (transactionID, productID, quantity, price), we have to find the top N products (by revenue) sold in the last 3 months using Java 8.

Here, N is the number of products that we want.

Given Employee details, we have to sort the employee details on basis of employee's name using Java 8.


  • Send your Feedback to [email protected]

Help Others, Please Share


Learn Latest Tutorials

Splunk tutorial


Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial



Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

Prepare for your exams

  • Guidelines and tips

Study with the several resources on Docsity

Earn points by helping other students or get them with a premium plan

Prepare for your exams with the study notes shared by other students like you on Docsity

The best documents sold by students who completed their studies

Summarize your documents, ask them questions, convert them into quizzes and concept maps

Clear up your doubts by reading the answers to questions asked by your fellow students

Earn points to download

For each uploaded document

For each given answer (max 1 per day)

Choose a premium plan with all the points you need

Study Opportunities

Connect with the world's best universities and choose your course of study

Ask the community for help and clear up your study doubts

Discover the best universities in your country according to Docsity users

Free resources

Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors

From our blog

JAVA Programming, Case Study - Computer Science, Study notes of Computers and Information technologies

Case study specification of entity classes naming link operations implementing links implementing actions implementing hiding Imp class world class stage class testing the package

Typology: Study notes

Limited-time offer

Uploaded on 09/06/2011


48 documents

On special offer

Related documents

Partial preview of the text.

Lecture notes

Study notes

Document Store

Latest questions

Biology and Chemistry

Psychology and Sociology

United States of America (USA)

United Kingdom

Sell documents

Seller's Handbook

How does Docsity work

United States of America

Terms of Use

Cookie Policy

Cookie setup

Privacy Policy

Sitemap Resources

Sitemap Latest Documents

Sitemap Languages and Countries

Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved


  1. Strings In Java Coursera Quiz Answers at rachelestone blog

    case study questions in java

  2. Guidance for Answering Case Study Questions in Exam: Tips for

    case study questions in java

  3. Exploring Case Study Methods in Qualitative Research

    case study questions in java

  4. FNSFMB514

    case study questions in java

  5. 6 Lectureu00 iHuman case study best copy Questions And Answers Graded

    case study questions in java

  6. Ethical Dilemma in Healthcare: Case Study Analysis

    case study questions in java




  3. 14 case study questions cbse 2023 paper maths class10| previous year case study maths Questions

  4. CBSE CLASS X Polynomials Case Study Questions

  5. Case Study Questions for Class 10 Social Science. Class 10 Case studies Part 10

  6. 10 Questions That Come Every Year in Class 10 Science Exam! #CBSEBoardExam2024 📝🔬


  1. Review these 50 questions to crack your Java programming interview

    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? ( answer) hint: bytecode and Java Virtual Machine. 2) What is ClassLoader in Java? ( answer) hint: part of JVM that loads bytecodes for classes.

  2. 18 Java scenarios based interview Questions and Answers

    Full list of Java scenarios based interview questions are covered at Judging your Java experience via scenarios based interview Q&As. #1. Caching. Q01.Scenario: You need to load stock exchange security codes with price from a database and cache them for performance. The security codes need to be refreshed say every 30 minutes.

  3. case-study · GitHub Topics · GitHub

    A case-study that shows how the Smart Contract Locator (SCL), the Smart Contract Description Language (SCDL), and the Smart Contract Invocation Protocol (SCIP) can be used in combination to support the integration of heterogeneous multi-blockchain setups into client applications. ... This is All Case Study for Basic Programming ( Java, Kotlin ...

  4. List of Examples and Case Studies

    O'Reilly members experience books, live events, courses curated by job role, and more from O'Reilly and nearly 200 top publishers. List of Examples and Case Studies 2.1 Welcome 2.2 Drawing a flag 2.3 Curio Store 2.4 Displaying a warning 2.5 Curio shop table 2.6 Fleet timetables 3.1 Math class investigation …. - Selection from Java Gently ...

  5. case-study · GitHub Topics · GitHub

    This is All Case Study for Basic Programming ( Java, Kotlin, Python, HTML, JS, etc ) javascript kotlin java dart swift case-study Updated Jun 9, 2022; Java; championswimmer / low-level-design-problem Sponsor Star 52. Code Issues Pull requests Case studies (with solution codes) for Low Level System Design problems ...

  6. Java.io in nutshell: 22 case studies

    Case 1: Two constants in File. Case 2: Delete a file. Case 3: Create a directory. Case 4: List files and directories in a given directory. Case 5: Tests whether a file is a file. Case 6: Write to a RandomAccessFile. Case 7: Write bytes to a file. Case 8: Append bytes to a file. Case 9: Read bytes from a file.

  7. The Java Interview Prep Handbook

    Java is well-known for its robustness in Object-Oriented Programming (OOP), and it provides a comprehensive foundation essential for developers at every level. This handbook offers a detailed pathway to help you excel in Java interviews. It focuses on delivering insights and techniques relevant to roles in esteemed big tech companies, ensuring ...

  8. Java Programming Case Study Examples

    Java Programming Case Study Examples. Here are some excellent case study examples that demonstrate the skills and expertise of top Java programmers: Google Maps: Google Maps is one of the most popular navigation applications in the world. It is built using Java and provides real-time traffic updates, street views, and satellite imagery.

  9. Java Interview Preparation Guide

    You cannot skip this question if your resume says you work on Java 8. In the linked tutorial, I will show you the correct scenarios, which will help you crack some complex interview questions and case studies. 1.11. Enum interview questions. The enum has been a core building block for a long time. They can be seen in the most popular Java ...

  10. 50 Java Interview Questions + 30 Scenario Based Q&A

    50 interview questions and answers. 1. What is Java? Java is a high-level, object-oriented programming language. It is a general-purpose concurrent and class-based language that is designed to have as few implementation dependencies as possible.

  11. Crack the top 40 Java coding interview questions

    Java remains a popular language across the world. Especially in financial fields, Java's scalability and efficiency keep it in-demand with interviewers in a variety of famous companies like Goldman Sachs, eBay, and Google.. Today, we'll help you prepare for your upcoming coding interview at these and other popular eCommerce companies by reviewing the top 40 Java questions asked by ...

  12. 21 Essential Java Interview Questions

    21 Essential Java Interview Questions. *. Toptal sourced essential questions that the best Java developers and engineers can answer. Driven from our community, we encourage experts to submit questions and offer feedback. is an exclusive network of the top freelance software developers, designers, finance experts, product managers, and project ...

  13. 42 Advanced Java Interview Questions For Senior Developers

    Though, in this case, the sub-class must also be declared as abstract. Abstract classes can implement interfaces without even providing the implementation of interface methods. Variables declared in a Java interface is by default final. An abstract class may contain non-final variables. Members of a Java interface are public by default.

  14. Java

    Java - Case Studywatch more videos at https://www.tutorialspoint.com/videotutorials/index.htmLecture By: Mr. Tushar Kale, Tutorials Point India Private Limited

  15. Popular Java Interview Questions: 20 Pros Share How to Prepare

    To test for equality, you'd have to use the String.equals () function. The difference is between identity and equality. The confusion comes because == can also be used to compare primitives. To prepare for a question like this, you should have good fundamentals regarding pointers (or references in Java) and OOP.

  16. Scenario Based Java 8 Coding Interview Questions (For Experienced)

    Generally, most websites cover basic Java 8 coding problems, But when you appear in the interview as an experience, Interviewer asks scenario-based coding questions. This question might not be simple if you have not practiced it well. So to solve this, I have collected and prepared multiple Java 8 scenario-based tough questions.

  17. Core Java Interview Questions and Answers (2024)

    Go through all the important questions to enhance your chances of performing well in the Java Interviews. The questions will revolve around the basic, core & advanced fundamentals of Java. So, let's dive deep into the plethora of useful Java Technical Interview Questions and Answers categorised into the following sections:

  18. Java Coding Interview Questions

    Complexity Analysis: The time complexity of the program is O (n), where n is the input number serving the power of number y. The space complexity of the program is O (1) because the program is not using any extra space. Corner Cases: We have to take care of cases when power is negative. 5) A string is given.

  19. Java Development Case Studies And Success Stories

    Java Development Case Studies And Success Stories. Take a look at these Java case studies to see how our developers have served clients in numerous industries. With each project analysis, you'll be able to shape a general impression about our developers, their experience, and their skills. Every time we're making our best effort to enhance ...

  20. 50+ Data Structure and Algorithms Problems from Coding Interviews

    Top 50 Algorithms and Coding Interview Questions. Without any further ado, here is my list of some of the most frequently asked coding interview questions from programming job interviews: 1. Array Coding Interview Questions. An array is the most fundamental data structure, which stores elements at a contiguous memory location.

  21. Case Study in java

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams Create a free Team. Teams. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. ... Could anyone provide me information where I can find the case study for java coding and design practice.

  22. Scenario Based Questions in Java

    Scenario 9: Transaction Management. For the given transaction data with (payer, payee, amount), calculate the total amount received by each payee. Here you have to use the grouping and Summing concept of Java 8. TransactionAnalyzer.java. import java.util.Arrays;

  23. JAVA Programming, Case Study

    Download JAVA Programming, Case Study - Computer Science and more Computers and Information technologies Study notes in PDF only on Docsity! Java case study, slide 1 Case Study: Stage in Java Ian Holyer Java case study, slide 2 Stage in Java The Stage project is a nice implementation example Here, we'll discuss an implementation in Java to sort out the Object Oriented aspects Later we'll look ...