Transact-SQL
Reinforcement Learning
R Programming
React Native
Python Design Patterns
Python Pillow
Python Turtle
Verbal Ability
Interview Questions
Company Questions
Artificial Intelligence
Cloud Computing
Data Science
Machine Learning
Data Structures
Operating System
Computer Network
Compiler Design
Computer Organization
Discrete Mathematics
Ethical Hacking
Computer Graphics
Software Engineering
Web Technology
Cyber Security
C Programming
Control System
Data Mining
Data Warehouse
Learn Java and Programming through articles, code examples, and tutorials for developers of all levels.
Join my Newsletter, its FREE
50+ java coding problems from programming job interviews.
good questions, thanks
Feel free to comment, ask questions if you have any doubt.
Java is an object-oriented programming language and computing platform first released by Sun Microsystems in 1995.
During an interview it does not matter whatever framework you know, the initial stage of the interview is always based on the programming sense, coding skills, and problem-solving capabilities. To test these, all the interviewers start interview from core programming problems and most of these programming problems are from core java concepts. Here, in this article, I have tried to put some initial level of Java programming questions to get through an interview process. These programs are helpful to both freshers and experienced Java professionals.
Keep an eye on this page as I will be regularly adding and updating more and more interview questions.
Write a Java program to find the largest sum of the contiguous subarray in a given Array. The given array might contain negative elements too and hence we need to find out a contiguous sub-array whose sum would be maximum....
Given a 2D matrix of N X N. Write a Java program to rotate the matrix in a clockwise direction by 90 degrees. The 0th row of the given matrix will be transformed to the nth column, the 1st row will be transformed to the n-1 column, and so on. Below is its representation....
For any given array of length n, rotating it by elements d means moving its first d elements either at the end of the array or moving the last d elements to the beginning of the array....
Writing a Java program to find first non-repeated character in a String is a common programming interview question to test the usage of Set interface provided in Java collection framework....
Writing a Java program to find first non-repeated character in a String is a common programming interview question. For example, the first non-repeated character in the String 'devglan for developers' is 'g'....
Write a java program to find a missing number in an Array of length N-1 containing elements from 1 to N. The trick to find the missing number is using the mathematical formula of Sum of Series....
When you are learning Java, network programming can be a great source of practicing Java. In this program, we will see how we can compare two different files in Java. Comparing files in java also can help you to differentiate between the local and the remote files. You can quickly identify the duplicate lines, which allows you to remove the file entirely. First, we will be comparing the files using BufferedReader but this way of comparing files is not memory efficient and requires more execution time. Hence, we will be using a highly advanced technique called memory mapping using RandomAccessFile from java.io package....
Write a java program to print 1 to 10 without using any loop.This can be achieved by using recursion in Java.Following is the sample code....
Write a java program to reverse an array in place without using any second array.Here, we can loop till the middle index of the array and swap the first element with last element, swap the second element with second last element until we reach the middle of the array....
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as madam. Write a java program to find the longest palindrome present in a given string. For example, in the string abcba , the longest palindrome is abcba and similarly in abcmadamcbamadam , the longest palindrome is abcmadamcba ....
Write a java program to find the second largest number in an array.There are multiple ways to achieve this. We can sort any given array in a descending order and pick the second index element.The main concept here is to sort the given array.This can be achieved via Arrays.sort() or Collection.sort() and once the given array is sorted the second largest number can be easily found....
In many java interviews, it is asked this question to compare two strings and remove the common character from the given strings to check the programming aptitude.For example, suppose there are two string, s1 = "abcfgh" and s2 = "aasdf" and after removal of common character the value of s1 and s2 becomes bcgh and sd respectivly. Following is the java program to remove the common characters from any given strings....
A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.Write a java program to check if a given number is a perfect number or not....
Given two string s1 and s2 then write a java program to check if s1 is the rotation of another string s2.Here rotation means, each character of s2 must be the same character of s1 but only thing is that the character in s2 can be present at any random position. Following is the java program to check if a given string is a rotation of another string....
Write a Java program to find LCM of a given two numbers.LCM stands for Lowest Common Multiple. LCM of a two given number a and b is the smallest positive integer that is divisible by both a and b.For example the LCM of 4 and 6 is 12. Following is the java program to find LCM using while and for loop....
Two words are said to be anagrams, if both the words contain same set of characters with all original letters exactly once. For example, the word program can be re-arranged as grampor and these both words form an anagram. Following is a java program to check if a string is anagram or not. There are two ways for this test - One is using equals() method provided in Arrays class and another by comparing each character of he words....
A matrix is a rectangular array of numbers or expressions arranged in rows and columns.Below is the java program to add two 2D matrices.We can change the dimension variables accordingly for 3D and 4D matrix....
Binary search is one of the famous and fundamental algorithm in computer science which solves a large number of problems in developing applications and APIs. It uses divide and conquer approach to find out the element.Here, we will be writing a sample program in java that implements binary search.The given array is a sorted array of n elements and we have to search the position a given element inside the array....
Write a program to find factorial of a given number is a common java program asked in any interview to freshers.The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example factorial of 4 is 4*3*2 = 24.There are 2 ways to find a factorial of a given number - One by using for loop and the other using recursion.Following java program uses for loop to find factorial of a given number....
Write a java program to reverse a given string using recursion without using any predefined function.This program checks the understanding of recursion in programming language and also checks the programming sense.Here, the method reverseString() is called recursively to revrse a given string.Following is the complete program....
Write a java program to find all the permutations of any given string.Permutation is the each of several possible ways in which a set or number of things can be ordered or arranged.Order matters in case of Permutation.For example, the permutation of ab will be ab and ba.Following is the java program to find permutation of a given string....
Write a java program to reverse a given number by using only numeric operators.Suppose, if you are given an input of 4567 then the output should be 7654.In the program below, we have only used the modulus or remainder and / operator.Following is the complete program....
Write a java program to find the sum of all the prime numbers less than a given natural number N. The main purpose of this interview question is to check the programming sense and capabilities to check how good you are to convert existing logic into code. The question is mostly asked to freshers.The only main logic in this program is to find the prime numbers.Prime number is a number that is greater than 1 and divided by 1 or itself.For reminder, 2 is also a prime number....
In java interview, this program can be asked in a multiple ways such as write program to find max repeated words or duplicate words or the count of each duplicate words.Whatever the question, the main programming concept is the same to count the occurrence of each word in a .txt file. To solve this programmatically, we can use Map implementation in Java that does not allow any duplicate key and at the end of iteration we can find out the count.Following is the complete program.Here, we are using java 8 Lambda operator during sorting....
In many java interviews especially for freshers, it is asked to write program to find max two numbers from a given array.This kind of program is good to check the programming sense as this program does not use any inbuilt java sorting functions or predefined data structures or collections.It simply uses java iterations and programming sense to swap in between the numbers and find the solution.Following is the implementation....
This java interview program is about finding lines with max character from a file in descending order.In this case, we will be using buffered reader to read a file and use java provided data structure TreeSet to hold the line and it's character length as it automatically maintains ascending order.Following is the program to find two lines with max characters in descending order....
In the java interview, you will be asked to find the middle index or position of a given array where sum of numbers preceding the index is equals to sum of numbers succeeding the index.There are two ways to solve this problem.One is to use 2 for loops - one starting from the last index to the middle index and another starting from start index to middle index. Another way to solve it by using while loop - the while loop should stop when the start index crosses the end index. Following is the program to achieve this using while loop....
While dealing with string, many of the time it is required to find or remove duplicate character from a string.Following is the java program to find duplicate or repeated characters from a given string.The program also results the count of the duplicate characters....
Java program to find distinct words from file is a very common question in java interview.In the following program, we will be using BufferedReader to read a file and then retain distinct words from it. To achieve this, we will be using Set to store all the words from a file and since, set dos not allow duplicates, we can easily find the distinct words.Following is the complete java program for this....
Fibonacci numbers are the numbers in which each number is the sum of the two preceding numbers.For example 1, 1, 2, 3, 5, 8, 13, 21, 34, ...The first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence.In most of the java interview, itapos;s a common programming question to check a given number is fibonacci number or not....
Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits.For example 371 is an Armstrong number as 3^3+7^3+1^3 = 371. It is also sometimes called as narcissistic number or pluperfect digital invariant (PPDI). Following is the java program to test if a given number is an armstrong number or not....
In an interview for a big tech company, I was asked if I’d ever resolved a fight — and the exact way I went about handling it. I felt blindsided, and I stammered my way through an excuse of an answer.
It’s a familiar scenario to fellow technical job seekers — and one that risks leaving a sour taste in our mouths. As candidate experience becomes an increasingly critical component of the hiring process, recruiters need to ensure the problem-solving interview questions they prepare don’t dissuade talent in the first place.
Interview questions designed to gauge a candidate’s problem-solving skills are more often than not challenging and vague. Assessing a multifaceted skill like problem solving is tricky — a good problem solver owns the full solution and result, researches well, solves creatively and takes action proactively.
It’s hard to establish an effective way to measure such a skill. But it’s not impossible.
We recommend taking an informed and prepared approach to testing candidates’ problem-solving skills . With that in mind, here’s a list of a few common problem-solving interview questions, the science behind them — and how you can go about administering your own problem-solving questions with the unique challenges of your organization in mind.
Evaluating a candidates’ problem-solving skills while using coding challenges might seem intimidating. The secret is that coding challenges test many things at the same time — like the candidate’s knowledge of data structures and algorithms, clean code practices, and proficiency in specific programming languages, to name a few examples.
Problem solving itself might at first seem like it’s taking a back seat. But technical problem solving lies at the heart of programming, and most coding questions are designed to test a candidate’s problem-solving abilities.
Here are a few examples of technical problem-solving questions:
This well-known challenge, which asks the interviewee to find the maximum and minimum sum among an array of given numbers, is based on a basic but important programming concept called sorting, as well as integer overflow. It tests the candidate’s observational skills, and the answer should elicit a logical, ad-hoc solution.
This problem tests the candidate’s knowledge of a variety of programming concepts, like 2D arrays, sorting and iteration. Organizing colored balls in containers based on various conditions is a common question asked in competitive examinations and job interviews, because it’s an effective way to test multiple facets of a candidate’s problem-solving skills.
This is a tough problem to crack, and the candidate’s knowledge of concepts like strings and dynamic programming plays a significant role in solving this challenge. This problem-solving example tests the candidate’s ability to think on their feet as well as their ability to write clean, optimized code.
Based on a technique used for searching pairs in a sorted array ( called the “two pointers” technique ), this problem can be solved in just a few lines and judges the candidate’s ability to optimize (as well as basic mathematical skills).
This is a problem of moderate difficulty and tests the candidate’s knowledge of strings and searching algorithms, the latter of which is regularly tested in developer interviews across all levels.
Testing a candidate’s problem-solving skills goes beyond the IDE . Everyday situations can help illustrate competency, so here are a few questions that focus on past experiences and hypothetical situations to help interviewers gauge problem-solving skills.
Key Insight : This question offers insight into the candidate’s research skills. Ideally, they would begin by identifying the problem, interviewing stakeholders, gathering insights from the team, and researching what tools exist to best solve for the team’s challenges and goals.
Key Insight: Prevention is often better than cure. The ability to recognize a problem before it occurs takes intuition and an understanding of business needs.
Key Insight: Sometimes, all the preparation in the world still won’t stop a mishap. Thinking on your feet and managing stress are skills that this question attempts to unearth. Like any other skill, they can be cultivated through practice.
Key Insight: Creativity can manifest in many ways, including original or novel ways to tackle a problem. Methods like the 10X approach and reverse brainstorming are a couple of unique approaches to problem solving.
Key Insight: “Ask for forgiveness, not for permission.” It’s unconventional, but in some situations, it may be the mindset needed to drive a solution to a problem.
Key Insight: According to Compass Partnership , “self-awareness allows us to understand how and why we respond in certain situations, giving us the opportunity to take charge of these responses.” It’s easy to get overwhelmed when faced with a problem. Candidates showing high levels of self-awareness are positioned to handle it well.
Key Insight: Everybody makes mistakes. But owning up to them can be tough, especially at a workplace. Not only does it take courage, but it also requires honesty and a willingness to improve, all signs of 1) a reliable employee and 2) an effective problem solver.
Key Insight: With the rise of empathy-driven development and more companies choosing to bridge the gap between users and engineers, today’s tech teams speak directly with customers more frequently than ever before. This question brings to light the candidate’s interpersonal skills in a client-facing environment.
Key Insight: Knowing when you need assistance to complete a task or address a situation is an important quality to have while problem solving. This questions helps the interviewer get a sense of the candidate’s ability to navigate those waters.
Key Insight: Conflict resolution is an extremely handy skill for any employee to have; an ideal answer to this question might contain a brief explanation of the conflict or situation, the role played by the candidate and the steps taken by them to arrive at a positive resolution or outcome.
If you’re a job seeker, chances are you’ll encounter this style of question in your various interview experiences. While problem-solving interview questions may appear simple, they can be easy to fumble — leaving the interviewer without a clear solution or outcome.
It’s important to approach such questions in a structured manner. Here are a few tried-and-true methods to employ in your next problem-solving interview.
S ituation, T ask, A ction, and R esult is a great method that can be employed to answer a problem-solving or behavioral interview question. Here’s a breakdown of these steps:
A very similar approach to the STAR method, SOAR stands for S ituation, O bstacle, A ction, and R esults .
Traditionally used as a method to make effective presentations, the P oint, R eason, E xample, P oint method can also be used to answer problem-solving interview questions.
Generic problem-solving interview questions go a long way in gauging a candidate’s skill level, but recruiters can go one step further by customizing these problem-solving questions according to their company’s service, product, vision, or culture.
Here are some tips to do so:
Over 2,500 companies and 40% of developers worldwide use HackerRank to hire tech talent and sharpen their skills.
Study these essential Java interview questions and answers to prepare for upcoming technical interviews and land the Java job you want.
Need to interview a Java developer for a freelance project or job? Here are 37 essential Java interview questions and answers provided by some of our top Java experts here at Arc.
Although technical interviews can’t gauge how well a candidate would perform on a real-life project, this is still an integral part of the hiring process. Here are some Java interview questions that you can ask a developer to evaluate their understanding of the language.
Intermediate java interview questions.
Looking to hire the best remote developers? Explore HireAI to see how you can:
⚡️ Get instant candidate matches without searching ⚡️ Identify top applicants from our network of 300,000+ devs with no manual screening ⚡️ Hire 4x faster with vetted candidates (qualified and interview-ready)
Try HireAI and hire top developers now →
String is an immutable class. In older JDKs the recommendation when programmatically building a String was to use StringBuffer since this was optimized to concatenate multiple Strings together.
However, the methods StringBuffer were marked as synchronized, which meant that there was a performance penalty, hence StringBuilder was introduced to provide a non-synchronized way to efficiently concatenate and modify Strings .
This is one of those Java interview questions where some people will be thinking what!? But, I’ve met a lot of Java developers who’ve not run a Java application outside of an IDE for years.
final is a Java keyword used to indicate that either a method can not override in a subclass, or a class can not be extended or a field can not be modified. finalize is a method that gets called on an instance of an Object when it is garbage collected. finally is a Java keyword used in exception handling to indicate a block of code that should always be run whether an exception is thrown or not.
This is a tricky Java interview question… it doesn’t have to be!
Garbage Collection simply cleans up unused memory when an object goes out of scope and is no longer needed. However, an application could create a huge number of large objects that causes an OutOfMemoryError.
A ClassNotFoundException means the class file for a requested class is not on the classpath of the application. A NoClassDefFoundErrormeans that the class file existed at runtime, but for some reason the class could not be turned into a Class definition.
A common cause is an exception being thrown in static initialization blocks.
Struggling with interview prep? Meet senior developers from Amazon, Microsoft, and Google now on Codementor. They’ll help you tackle coding challenges, practice interviews, and sharpen your skills in live 1:1 sessions. Book a session with our interview prep experts today! Your first 15 minutes are free.
Explore our other software development interview questions and answers to prep for your next remote job.
It isn’t accurate because it will only account for the number of characters within the String. In other words, it will fail to account for code points outside of what is called the BMP (Basic Multilingual Plane), that is, code points with a value of U+10000 or greater.
The reason is historical: when Java was first defined, one of its goal was to treat all text as Unicode; but at this time, Unicode did not define code points outside of the BMP. By the time Unicode defined such code points, it was too late for char to be changed.
This means that code points outside the BMP are represented with two chars in Java, in what is called a surrogate pair . Technically, a char in Java is a UTF-16 code unit.
The correct way to count the real numbers of characters within a String, i.e. the number of code points, is either:
or, with Java 8:
Because of Double.NaN (literally: “Not a Number”).
will print false .
The most accurate way to tell whether two double values are equal to one another is to use Double.compare() and test against 0, as in:
There are, in fact, two problems:
While the second problem is rarely a concern, the first certainly is a concern.
For instance, in most Windows installations, the default charset is CP1252 ; but on Linux installations, the default charset will be UTF-8.
As such, such a simple string as “é” will give a different result for this operation depending on whether this code is run on Windows or Linux.
The solution is to always specify a Charset, as in, for instance:
The what is the problem with this code? question is one of the most popular Java interview questions, but it’s not necessarily going to be this one above, of course. Be prepared to do some detective work to identify the issue.
Also, keep in mind: while the problem may be exception handling, method overloading, an access specifier issue, or something else, it could also be nothing at all! This is one of those trick Java interview questions where the answer will rely on your gut that everything is perfect with the code already.
The JIT is the JVM’s mechanism by which it can optimize code at runtime.
JIT means Just In Time. It is a central feature of any JVM. Among other optimizations, it can perform code inlining, lock coarsening or lock eliding, escape analysis etc.
The main benefit of the JIT is on the programmer’s side: code should be written so that it just works; if the code can be optimized at runtime, more often than not, the JIT will find a way.
(On a more advanced note: the JIT is such a complex piece of machinery that it makes it complicated to do accurate performance benchmarks for JVM code; this is why such frameworks as JMH exist.)
prints 0 . Why? How do you make this code print 0.5 instead?
The problem here is that this expression:
has integer literals on both sides of the operator: 1 and 2 . As a consequence, an integer division will be performed, and the result of 1 divided by 2 in an integer division is 0 .
In order for the result to be a double as expected, at least one operand of the operation needs to be a double. For instance:
In this code:
what is the inferred type of the method reference System.out::println?
It is an IntConsumer .
IntStream.range(0, 10) returns an IntStream , and IntStream defines a .forEach() method accepting an IntConsumer as an argument, whose prototype is:
System.out is a PrintStream , and a PrintStream has a method named println which takes an int as an argument and returns void. This matches the signature of an IntConsumer , hence the result.
The problem is that the Stream returned by Files.lines() is not closed.
This should be used instead:
Stream extends BaseStream , and BaseStream extends AutoCloseable . While this has no influence on streams you obtain from collections for instance, the stream returned by Files.lines() is I/O bound. Neglecting to close it correctly may lead to a resource leak if an error occurs while processing the stream.
Consider the following piece of code: (Question provided by Francis Galiegue)
What will be the contents of the list after this operation and why?
The contents will be:
The reason is that there are two removal operations on a List:
The JVM will always select the most specific overload of a method; and here we pass an int as an argument, the code therefore removes the element at index 2.
To remove the _element_ 2 from the list, the following needs to be written:
This is my go-to first interview question. It helps me gauge a candidate’s ability to understand a problem and write an algorithm to solve it.
If someone has not solved the problem before, I expect to see some code with loops and if/then’s. Maybe some HashMaps . I look for the ability to break down the problem to see what you need to check, what the edge cases are, and whether the code meets those criteria.
The naive solution is often to loop through the letters of the first string and see if they’re all in the second string. The next thing to look for is that the candidate should also do that in reverse too (check string 1 for string 2’s letters)? The next thing to look for is, what about strings with duplicate letters, like VASES?
If you can realize that these are all required and create a functional, non-ridiculous solution, I am happy.
Of course, one can solve it trivially by sorting and comparing both strings. If someone catches this right away, they usually have seen the problem before. But that’s a good sign that someone cares enough to do prep work. Then we can tackle a harder problem.
The details of the implementation are not important; what’s important is that the candidate understands what they need to do, and also understands why their solution works or doesn’t work. If the candidate can demonstrate this, they’re on the right track.
Here is one way to implement a better solution, comparing sorted strings:
The only obligation is that for any objects o1 and o2 then if o1.equals(o2) is true then o1.hashCode() == o2.hashCode() is true.
Note that this relationship goes only one way: for any o1, o2 of some class C, where none of o1 and o2 are null, then it can happen that o1.hashCode() == o2.hashCode() is true BUT o1.equals(o2) is false.
No. Enum types are final by design.
Creation of an enum is guaranteed to be threadsafe. However, the methods on an enum type are not necessarily threadsafe
Objects are stored on the heap. Variables are a reference to the object.
Local variables are stored on the stack.
A classic example of escaping references.
When an object of Bar is created, the super constructor in Foo gets called first, which in turn calls the ‘overridden’ doSomething method.
The doSomething method passes the this instance to the class Zoom . Zoom now can use the ‘ this ‘ instance before it is created entirely. BAD!!!
When a member variable is accessed by multiple threads and want the value of a volatile field to be visible to all readers (other threads in particular) after a write operation completes on it.
Keep in mind that, although Java is already an object-oriented programming language, you may want to ask questions about object-oriented programming that are more theoretical, conceptual, and outside general Java programming.
Consider including the following additional core Java interview questions on OOP:
If threads are being used and a number of threads have to go through a synchronized section of code, only one of them may be executed at a time. This is used to make sure shared variables are not updated by multiple threads.
ConcurrentHashMap is thread-safe; that is the code can be accessed by single thread at a time while HashMap is not thread-safe. ConcurrentHashMap does not allow NULL keys while HashMap allows it.
By defining equals() and hashCode() consistently, the candidate can improve the usability of classes as keys in hash-based collections such as HashMap .
A service is a function that is well-defined, self-contained, and does not depend on the context or state of other services.
One may call System.gc() when profiling an application to search for possible memory leaks. All the profilers call this method just before taking a memory snapshot.
The marker interface in Java is an interface with no field or methods. In other words, it an empty interface in java is called a marker interface. An example of a marker interface is a Serializable, Clonable, and Remote interface. These are used to indicate something to the compiler or JVM.
Annotations allow one to achieve the same purpose of conveying metadata about the class to its consumers without creating a separate type for it. Annotations are more powerful, too, letting programmers pass more sophisticated information to classes that “consume” it.
A checked exception is an exception that must be catch, they are checked by the compiler. An unchecked exception is mostly runtime exception, and is not required to be catch. In general, use checked exception when the situation is recoverable (retry, display reasonable error message).
When += is used, that’s a compound statement and the compiler internally casts it. Whereas in the first case, the compiler straightaway shouts at you since it is a direct statement.
Compiler behavior and statement types can be confusing, so questions like this will test a candidate’s grasp of these concepts.
Extending classes may cause ambiguity problems. On the other hand, in terms of interfaces, the single method implementation in one class can serve more than one interface.
Be sure you ask about multithreading, as it’s one of Java’s most important features. Here are a few Java multithreading questions you want to ask:
You can also explore HireAI to skip the line and:
⚡️ Get instant candidate matches without searching ⚡️ Identify top applicants from our network of 250,000+ devs with no manual screening ⚡️ Hire 4x faster with vetted candidates (qualified and interview-ready)
31. why doesn’t the following code generate a nullpointerexception even when the instance is null .
There is no need for an instance while invoking a static member or method since static members belong to a class rather than an instance.
A null reference may be used to access a class (static) variable without causing an exception.
JVM’s cache behavior can be confusing, so this question tests that concept. The second output is true as we are comparing the references because the JVM tries to save memory when the Integer falls within a range (from -128 to 127).
At point 2, no new reference of type Integer is created for ‘d’. Instead of creating a new object for the Integer type reference variable ‘d’, it is only assigned with a previously created object referenced by ‘c’. All of these are done by JVM.
34. how do you reverse string("java programming") without using iteration and recursion, 35. give real-world examples of when to use an arraylist and when to use linkedlist ..
ArrayList is preferred when there are more get(int) , or when search operations need to be performed as every search operation runtime is O(1) .
If an application requires more insert(int) and delete(int) operations, then LinkedList is preferred, as LinkedList does not need to maintain back and forth to preserve continued indices as arraylist does. Overall this question tests the proper usage of collections.
This question tests the proper usage of collection iterators. One can only use ListIterator to traverse Lists , and cannot traverse a Set using ListIterator .
What’s more, one can only traverse in a forward direction using Iterator s. Using ListIterator , one can traverse a List in both the directions (forward and backward).
One cannot obtain indexes while using Iterator . Indexes can be obtained at any point of time while traversing a list using ListIterator . The methods nextIndex() and previousIndex() are used for this purpose.
They enable stronger type checks at compile time.
A Java compiler applies strong type checking to generic code, and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
Hopefully, you’ve found these interview questions useful when vetting Java developers.
Keep in mind that the technical interview is just one portion of the hiring process. Whether you’re hiring freelance or full-time Java developers, you also want to evaluate their soft skills like communication, problem-solving, time management, and more.
The Arc team publishes insightful articles and thought leadership pieces related to software engineering careers and remote work. From helping entry-level developers land their first junior role to assisting remote workers struggling with working from home to guiding mid-level programmers as they seek a leadership position, Arc covers it all and more!
1. Write a program to read a weekday number and print weekday name using switch statement
2. Write a program to read gender(M/F) and print the corresponding gender using a switch statement
3. Write a program to Check whether a character is a vowel or consonant using switch statement
4. Write a program to Check whether the number is even or odd using switch statement
5. Write a program to Find the number of days in a month using a switch statement
6. Write a program to create simple calculator using switch Statement
7. Write a program to print remark according to the grade obtained using switch statement
8. Write a program to Menu driven program using switch statement ( Find addition, subtraction, multiplication and division of to integer numbers )
9. Write a program to check whether a person is eligible to vote or Not using switch statement
10. Write a program to find the Maximum of Two Numbers using switch statement
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions
Java collections interview questions, download pdf, what is collection in java.
In Java , a collection is a framework that provides an architecture for storing and manipulating a collection of objects. In JDK 1.2, a new framework called "Collection Framework" was created, which contains all of the collection classes and interfaces.
Collections in Java are capable of doing any data operations such as searching, sorting, insertion, manipulation, and deletion.
A single unit of objects in Java is referred to as a collection. The two basic “root” interfaces of Java collection classes are the Collection interface (java.util.Collection) and the Map interface(java.util.Map). Many interfaces (Set, List, Queue, Deque) and classes are available in the Java Collection framework (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
Need for the Collection framework:-
Prior to the introduction of Collection Framework (or JDK 1.2), the standard techniques for aggregating Java objects (or collections) were Arrays, Vectors, or Hash Tables. There was no common interface for all of these collections. As a result, while the basic goal of all the collections is the same, their implementation was specified independently and there was no correlation between them. Furthermore, users find it challenging to remember all of the various methods, syntax, and constructors included in each collection class.
1. differentiate between hashset and treeset. when would you prefer treeset to hashset.
Following are the differences between HashSet and TreeSet:-
Following are the cases when TreeSet is preferred to HashSet :
Collection : In the java.util.package, there is an interface called a collection. It's used to represent a collection of separate objects as a single entity. It's equivalent to the container in the C++ programming language. The collection framework's root interface is referred to as the collection. It has a number of classes and interfaces for representing a collection of individual objects as a single unit. The key sub-interfaces of the collection interface are List, Set, and Queue. Although the map interface is part of the Java collection framework, it does not inherit the interface's collection. The Collection interface's most significant functions are add(), remove(), clear(), size(), and contains().
Collections : The java.util.package has a utility class called Collections. It defines various utility methods for working with collections, such as sorting and searching. All of the methods are static. These techniques give developers much-needed convenience, allowing them to interact with Collection Framework more successfully. It provides methods like sort() to sort the collection elements in the normal sorting order, and min() and max() to get the minimum and maximum value in the collection elements, respectively.
Collection | Collections |
---|---|
It's used to represent a collection of separate objects as a single entity. | It defines a number of useful methods for working with collections. |
It is an interface. | It is a utility class. |
Since Java 8, the Collection is an interface with a static function. Abstract and default methods can also be found in the Interface. | It only has static methods in it. |
The entire collection framework hierarchy is made up of four fundamental interfaces: Collection, List, Set, Map, and two specific interfaces for sorting called SortedSet and SortedMap. The java.util package contains all of the collection framework's interfaces and classes. The following diagram depicts the Java collection structure.
Here, e denotes extends, i denotes implements
Following are the advantages of the Collection framework:-
Consistent API : The API has a core set of interfaces like Collection, Set, List, or Map, and all the classes (ArrayList, LinkedList, Vector, and so on) that implement these interfaces have some common set of methods.
Cuts programming effort : Instead of worrying about the Collection's design, a programmer may concentrate on how best to use it in his program. As a result, the fundamental principle of Object-oriented programming (i.e. abstraction) has been applied successfully.
Improves program speed and quality by offering high-performance implementations of useful data structures and algorithms, as the programmer does not have to worry about the optimum implementation of a certain data structure in this scenario. They can simply use the best implementation to improve the performance of their program significantly.
The collection framework has several interfaces, each of which is used to store a different sort of data. The interfaces included in the framework are listed below.
1. Iterable Interface : This is the collection framework's primary interface. The iterable interface is extended by the collection interface. As a result, all interfaces and classes implement this interface by default. This interface's main purpose is to provide an iterator for the collections. As a result, this interface only has one abstract method, the iterator.
2. Collection Interface : The collection framework's classes implement this interface, which extends the iterable interface. This interface covers all of the basic methods that every collection has, such as adding data to the collection, removing data from the collection, clearing data, and so on. All of these methods are incorporated in this interface because they are used by all classes, regardless of their implementation style. Furthermore, including these methods in this interface guarantees that the method names are consistent across all collections. In summary, we may conclude that this interface lays the groundwork for the implementation of collection classes.
3. List Interface : The collection interface has a child interface called the list interface. This interface is devoted to list data, in which we can store all of the objects in an ordered collection. This also allows for the presence of redundant data. Various classes, such as ArrayList, Vector, Stack, and others, implement this list interface. We can create a list object with any of these classes because they all implement the list.
4. Queue Interface : A queue interface, as the name implies, follows the FIFO (First In First Out) order of a real-world queue line. This interface is for storing all elements in which the order of the elements is important. When we try to shop at a store, for example, the bills are issued on a first-come, first-served basis. As a result, the individual whose request is first in line receives the bill first. PriorityQueue, Deque, ArrayDeque, and other classes are available. Because all of these subclasses implement the queue, we can use any of them to create a queue object.
5. Deque Interface : It differs slightly from the queue data structure. Deque, also known as a double-ended queue, is a data structure in which elements can be added and removed from both ends. The queue interface is extended by this interface. ArrayDeque is the class that implements this interface. Because this class implements the deque, we can use it to create a deque object.
6. Set Interface : A set is an unordered group of objects in which duplicate values cannot be kept. This collection is utilised when we want to avoid duplication of things and only keep the ones that are unique. Various classes, such as HashSet, TreeSet, LinkedHashSet, and others, implement this set interface. We can create a set object with any of these classes because they all implement the set.
7. Sorted Set Interface : This interface resembles the set interface in appearance. The only difference is that this interface provides additional methods for maintaining element ordering. The sorted set interface is an extension of the set interface that is used to manage sorted data. TreeSet is the class that implements this interface. We can create a SortedSet object using this class because it implements the SortedSet interface.
ArrayList | LinkedList |
---|---|
The elements of this class are stored in a dynamic array. This class now supports the storage of all types of objects thanks to the addition of generics. | The elements of this class are stored in a doubly-linked list. This class, like the ArrayList, allows for the storage of any type of object. |
The List interface is implemented by this class. As a result, this serves as a list. | The List and Deque interfaces are both implemented by this class. As a result, it can be used as both a list and a deque. |
Because of the internal implementation, manipulating an ArrayList takes longer. Internally, the array is scanned and the memory bits are shifted whenever we remove an element. | Because there is no concept of changing memory bits in a doubly-linked list, manipulating it takes less time than manipulating an ArrayList. The reference link is changed after traversing the list. |
This class is more useful when the application requires data storage and access. | This class is more useful when the application requires data manipulation. |
Following are the differences between ArrayList and Vector in java :
The List interface is used to keep track of an ordered collection. It is the Collection's child interface. It is an ordered collection of objects that allows for the storage of duplicate values. The insertion order is preserved in a list, which enables positional access and element insertion.
The set interface is part of java.util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It's an interface for using the mathematical set. This interface inherits the Collection interface's methods and adds a feature that prevents duplicate elements from being inserted.
Set | List |
---|---|
It is an unordered sequence. | It is an ordered sequence. |
Duplicate elements are not permitted in Set. | Duplicate elements are allowed in the list |
Access to items from a certain position is not permitted. | Elements can be accessed based on their position. |
A null element can only be stored once. | It is possible to store several null elements. |
In Java's Collection framework, iterators are used to obtain elements one by one. It can be used on any type of Collection object. We can execute both read and remove operations using Iterator. Iterator must be used whenever we want to iterate elements in all Collection framework implemented interfaces, such as Set, List, Queue, and Deque, as well as all Map interface implemented classes. The only cursor accessible for the entire collection framework is the iterator.
ListIterator is only useful for classes that implement List collections, such as array lists and linked lists. It can iterate in both directions. When we wish to enumerate List elements, we must use ListIterator. This cursor has additional methods and capabilities than the iterator.
Iterator | ListIterator |
---|---|
Only has the ability to traverse components in a Collection in a forward direction. | In both forward and backward orientations, can traverse components in a Collection. |
Iterators cannot be used to obtain indexes. | It offers methods to get element indexes at any time while traversing List, such as next Index() and previous Index(). |
It aids in the traversal of Maps, Lists, and Sets. | Only List may be traversed, not the other two. |
It throws a Concurrent Modification Exception since it can't add elements. | At any time, you can quickly add elements to a collection. |
next(), remove(), and has Next are some of the Iterator's functions (). | next(), previous(), has Next(), has Previous(), and add() are some of the List Iterator's methods |
Array and Collection are equivalent in terms of storing object references and manipulating data, but they differ in a number of ways. The following are the primary distinctions between an array and a Collection:
Array | Collection |
---|---|
Arrays have a set size, which means that once we build one, we can't change it to meet our needs. | Collection are naturally grow-able and can be customized to meet our needs. We can change its size as per our requirement. |
When it comes to performance, Arrays are the preferred to Collection. | Considering performance, Collection are not preferred to Arrays. |
Only homogeneous data type elements can be stored in arrays. | Both homogeneous and heterogeneous components can be stored in a collection. |
Because arrays have no underlying data structure, there is no ready-made method support. | Any collection class is built on a standard data structure, and so there is ready-made method support for every demand as a performance. These methods can be used directly, and we are not responsible for their implementation. |
Objects and primitives can both be stored in arrays. | Only object types can be stored in a collection. |
When it comes to memory, Arrays are not preferred to Collection. | Considering memory, Collection are preferred to Arrays. |
We can add null elements in a HashSet but we cannot add null elements in a TreeSet. The reason is that TreeSet uses the compareTo() method for comparing and it throws a NullPointerException when it encounters a null element.
When the objects are meant to be processed in order of priority, a PriorityQueue is used. A Queue is known to follow the First-In-First-Out method, however, there are occasions when the components of the queue must be handled in order of priority, which is where the PriorityQueue comes into play. The priority heap is the foundation of the PriorityQueue. The members of the priority queue are ordered according to natural ordering or by a Comparator provided at queue construction time.
Serializable, Iterable<E>, Collection<E>, Queue<E> interfaces are implemented by the PriorityQueue class in Java.
Following are some of the best practices while using Java Collections :
The Set interface is provided by the Java.util package. The set interface is established by extending the collection interface. We can't add the same element to it since it won't let us. Because it contains elements in a sorted order, it does not keep the insertion order. The Set interface in Java is used to build the mathematical Set.
Map is similar to Set in that it is used to store a collection of objects as a single entity. A key-value pair is used to store each object. Because each value is associated with a unique key, we can quickly obtain the value using just the key.
Set | Map |
---|---|
It cannot have values that are repeated. It is not possible to add the same elements to a set. Only the unique value is stored in each class that implements the Set interface. | It is possible for different keys to have the same value. The map has a unique key and values that are repeated. |
Using the keyset() and entryset() methods, we can quickly iterate the Set items. | It is not possible to iterate across map elements. To iterate the elements, we must convert Map to Set. |
The Set interface does not keep track of insertion order. Some of its classes, such as LinkedHashSet, however, keep the insertion order. | The Map does not keep track of the insertion sequence. Some Map classes, such as TreeMap and LinkedHashMap, do the same thing. |
HashSet is a Set Interface implementation that does not allow duplicate values. The essential point is that objects stored in HashSet must override equals() and hashCode() methods to ensure that no duplicate values are stored in our set.
HashMap is a Map Interface implementation that maps a key to a value. In a map, duplicate keys are not permitted.
HashSet | HashMap |
---|---|
It implements the Set Interface. | It implements the Map Interface. |
It does not allow duplicate values. | The key needs to be unique while two different keys can have the same value. |
While adding an element it requires only one object as a parameter. | While adding an entry, it requires two object values, the and the as the parameter. |
Internally, HashSet uses HashMap to add entries. The key K in a HashSet is the argument supplied in the add(Object) method. For each value supplied in the add(Object) method, Java assigns a dummy value. | There is no concept of duplicate values. |
It is slower than HashMap. | It is faster than HashSet. |
It uses the add() method for adding elements. | It uses the put() method for adding data elements. |
The default load factor size is 0.75 . The default capacity is calculated by multiplying the initial capacity by the load factor.
Following are the differences between Arrays and ArrayLists in Java :
With the help of Collections.unmodifiableList() method, we can easily make an ArrayList read-only. This function takes a changeable ArrayList as an input and returns the ArrayList's read-only, unmodified view.
We can see that as we try to add an element to a read-only ArrayList we get an exception thrown.
1. why do we need synchronized arraylist when we have vectors (which are synchronized) in java.
Following are the reasons why we need synchronized ArrayLists even though we have Vectors :
BlockingQueue is an interface that has been included along with a number of other concurrent Utility classes such as ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrayList, and so on. In addition to queueing, the BlockingQueue interface enables flow control by adding blocking if either BlockingQueue is full or empty.
A thread attempting to enqueue an element in a full queue will be blocked until another thread clears the queue, either by dequeuing one or more elements or by clearing the queue entirely. It also prevents a thread from deleting from an empty queue until another thread inserts an item. A null value is not accepted by BlockingQueue. Implementations of the Java BlockingQueue interface are thread-safe. BlockingQueue's methods are all atomic and use internal locks or other forms of concurrency management.
There are two types of BlockingQueue in Java. They are as follows :
Unbounded Queue : The blocked queue's capacity will be set to Integer. MAX VALUE. An unbounded blocking queue will never block since it has the potential to grow to a very big size. As you add more pieces, the size of the queue grows.
Bounded Queue : The bounded queue is the second type of queue. In the case of a bounded queue, the capacity of the queue can be passed to the constructor when the blocking queue is created.
If the collection's structure is changed, Fail-Fast iterators immediately throw ConcurrentModificationException. While a thread is iterating over a collection, structural alteration includes adding or deleting any element. Fail-safe Iterator classes include ArrayList Iterator and HashMap Iterator. Fail-fast iterators use an internal indicator called modCount, which is updated each time a collection is modified, to determine if the collection has been structurally modified or not. When a fail-fast iterator gets the next item (through the next() method), it checks the modCount flag, and if it discovers that the modCount has been changed after the iterator was generated, it throws a ConcurrentModificationException.
If a collection is structurally updated while iterating over it, fail-safe iterators don't throw any exceptions. Because they operate on a clone of the collection rather than the original collection, they are referred to as fail-safe iterators. Fail-safe Iterators include the CopyOnWriteArrayList and ConcurrentHashMap classes.
Fail-Fast | Fail-Safe |
---|---|
These types of iterators do not allow modifying the collection while iterating over it. | These types of iterators allow modifying the collection while iterating over it. |
It throws ConcurrentModificationException if the collection is modified while iterating over it. | No exception is thrown if the collection is modified while iterating over it. |
It uses the original collection while traversing the elements. | It uses a copy of the original collection while traversing over it. |
No extra memory is required in this case. | Extra memory is required in this case. |
RandomAccess, like the Serializable and Cloneable interfaces, is a marker interface. There are no methods defined in any of these marker interfaces. Rather, they designate a class as having a specific capability.
The RandomAccess interface indicates whether or not a given java.util.List implementation supports random access. This interface seeks to define a vague concept: what does it mean to be fast? A simple guide is provided in the documentation: The List has fast random access if repeated access using the List.get( ) method is faster than repeated access using the Iterator.next( ) method.
Repeated access using List.get( ):
Repeated access using Iterator.next( ):
Iterator : Because it can be applied to any Collection object, it is a universal iterator. We can execute both read and remove operations using Iterator. It's an enhanced version of Enumeration that adds the ability to remove an element from the list.
Enumeration : An enumeration (or enum) is a data type that is defined by the user. It's mostly used to give integral constants names, which make a program easier to comprehend and maintain. Enums are represented in Java (since 1.5) through the enum data type.
Iterator | Enumeration |
---|---|
Iterator is a universal cursor since it works with all collection classes. | Because it only applies to legacy classes, enumeration is not a universal cursor. |
Iterators can make changes (for example, the delete() method removes an element from a Collection during traversal). | The Enumeration interface is a read-only interface, which means you can't make any changes to the Collection while traversing its elements. |
The remove() method is available in the Iterator class. | The remove() method is not available in the enumeration. |
Iterator is not a legacy interface. Iterator can traverse HashMaps, LinkedLists, ArrayLists, HashSets, TreeMaps, and TreeSets. | Enumeration is a legacy interface for traversing Hashtables and Vectors. |
The key and value pair are both strings in the properties object. The java.util.Properties class is a Hashtable subclass.
It can be used to calculate the value of a property based on its key. The Properties class has methods for reading and writing data to and from the properties file. It can also be used to obtain a system's attributes.
Advantage of the Properties file :
If the information in a properties file is modified, no recompilation is required: You don't need to recompile the java class if any information in the properties file changes. It is used to keep track of information that needs to be updated frequently.
Let us first create a properties file named “info.properties” having the following content :
user = success
password = determination
Let us now create a java class to read data from the properties file
Following are the differences between HashMap and HashTable :
The objects used as keys must implement the hashCode and equals methods in order to successfully save and retrieve objects from a HashTable. These methods cannot be implemented by null because it is not an object. HashMap is a more advanced and improved variant of Hashtable.HashMap was invented after HashTable to overcome the shortcomings of HashTable.
An ArrayList can be synchronized using the following two ways :
Here, a thread-safe variant of ArrayList is created. T represents generic.
All mutative actions (e.g. add, set, remove, etc.) are implemented by generating a separate copy of the underlying array in this thread-safe variation of ArrayList. It accomplishes thread safety by generating a second copy of List, which differs from how vectors and other collections achieve thread-safety.
Even if copyOnWriteArrayList is modified after an iterator is formed, the iterator does not raise ConcurrentModificationException because the iterator is iterating over a separate copy of ArrayList while a write operation is occurring on another copy of ArrayList.
Comparable | Comparator |
---|---|
A single sorting sequence is provided by Comparable. To put it another way, we can sort the collection by a single attribute such as id, name, or price. | Multiple sorting sequences are available in the Comparator. To put it another way, we can sort the collection based on different criteria such as id, name, and price. |
To sort elements, Comparable provides the compareTo() method. | To order elements, the Comparator provides the compare() method. |
It is present in the java.lang package. | It is present in the java.util package. |
The original class is affected by Comparable, i.e. the real class is changed. | The original class is unaffected by the comparator, i.e. the real class is unaffected. |
The Collections.sort(List) method can be used to sort Comparable type list members. | The Collections.sort(List, Comparator) method can be used to sort the list components of the Comparator type. |
If Map extends the Collection Interface, "Key-value pairs" can be the only element type for this type of Collection, although this provides a very limited (and not really useful) Map abstraction. You can't inquire what value a specific key corresponds to, and you can't delete an entry without knowing what value it corresponds to.
The three "Collection view procedures" on Maps represent the fact that Maps can be viewed as Collections (of keys, values, or pairs) (keySet, entrySet, and values). While it is theoretically feasible to see a List as a Map mapping indices to items, this has the unfortunate side effect of changing the Key associated with every element in the List prior to the deleted member. This is the reason why Collection can not be made to extend the Map Interface either.
HashMap | TreeMap |
---|---|
The Java HashMap implementation of the Map interface is based on hash tables. | Java TreeMap is a Map interface implementation based on a Tree structure. |
The Map, Cloneable, and Serializable interfaces are implemented by HashMap. | NavigableMap, Cloneable, and Serializable interfaces are implemented by TreeMap. |
Because HashMap does not order on keys, it allows for heterogeneous elements. | Because of the sorting, TreeMap allows homogenous values to be used as a key. |
HashMap is quicker than TreeMap because it offers O(1) constant-time performance for basic operations such as to get() and put(). | TreeMap is slower than HashMap because it performs most operations with O(log(n)) performance, such as add(), remove(), and contains(). |
A single null key and numerous null values are allowed in HashMap. | TreeMap does not allow null keys, however multiple null values are allowed. |
To compare keys, it uses the Object class's equals() method. It is overridden by the Map class's equals() function. | It compares keys using the compareTo() method. |
HashMap does not keep track of any sort of order. | The elements are arranged in chronological sequence (ascending). |
When we don't need a sorted key-value pair, we should use the HashMap. | When we need a key-value pair in sorted (ascending) order, we should use the TreeMap. |
1. given an array in java, convert it to a collection..
We can convert an array to a collection using the asList() method of the Arrays class in Java.
We use the hasMoreElements and the nextElement methods of the Enumeration class to iterate through the HashMap.
We notice that the order of the values is not the same as that of the order in which we inserted the key-value pair in the hashtable. This is because the elements of a Hashtable are not guaranteed to be in any particular sequence. The hashtable's implementation divides values into multiple buckets based on their Hashcode and internal implementation, which means that the same values may appear in a different order on different machines, runs, or versions of the framework. This is because Hashtables are designed to retrieve data by key rather than by order.
We use the shuffle() method of the Collections class.
We use the clone() method of the TreeSet class to clone one TreeSet into another.
We use the values() function of the HashMap to get the collection view.
We use the addAll() method of the ArrayList class to add the contents of both the given arraylists into a new arraylist.
Basics of Java
Java Developer Skills
Java Developer Salary
ArrayList vs LinkedList
The enumeration returned by Vector is which of the following type :
Which of the following iterators can throw a Concurrent Modification Exception?
What is the default number of segments in a Concurrent Hash Map?
Which one of the following represents the default capacity of Vector?
In which of the following packages, are all of the collection classes present?
Which of the following methods can be used to convert an object to a list?
When resized, the size of the ArrayList increases by
Which of the following Map classes must be preferred in a multi-threading environment considering performance constraints?
The Vector class extends which of the following :
Which of the following must be preferred in a multi-threading environment considering performance constraints?
Which of the following guarantees type-safety in a collection?
When resized, the size of the Vector increases by
Which of the following methods can be used to set every element of the List to a specified value?
Which of the following interfaces is not a part of Java’s collection framework?
Which of the following Set classes must be preferred in a multi-threading environment considering performance constraints?
1 Million +
Java solved programs problems with solutions.
Java Solved programs —-> Java is a powerful general-purpose programming language. It is fast, portable and available in all platforms.
This page contains the Java solved programs/examples with solutions, here we are providing most important programs on each topic . These Java examples cover a wide range of programming areas in Computer Science.
Every example program includes the description of the program, Java code as well as output of the program. All examples are compiled and tested on a Windows system.
These examples can be as simple and basic as “Hello World” program to extremely tough and advanced Java programs. Here is the List of Java solved programs/examples with solutions (category wise) and detailed explanation.
Java basic solved programs.
If you found any error or any queries related to the above programs or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach up to you in short interval.
Thanks for reading the post….
No related posts.
nice web but plz add creating account
please solve the qustion
Create a menu-based java program for the following queues operations using linked list :
Create a menu-based java program for the following queues operations using array:
Design a flowchart of the java program that accepts 3 integer values and display the lowest and the highest given value.
hello i need help
Write a program to input two arrays of size ‘m’ each. Find the sum of the elements of the two arrays in the same index and store it in the 3rd array in reverse order.
wtf………….
Create the class such that it reset the value of the object it is used to null its after uses in all cases using in finally statement in java exception handling
Enter a four-digit number. Break it down into numbers. Compose a new number in which from the original number all even digits less than 8 are increased by 2, and 8 is replaced by 0(java program)
Write a program that reads in from the user a character (ch), an integer (n) and another character (operator). This operator is an indication of the operation applied to (ch) and (n) entered as follows: – When (operator) character entered is ‘p’ or ‘P’, your program displays the character that comes after (ch) entered in (n) positions. – When (operator) character entered is ‘s’ or ‘S’, your program displays the character that precedes (ch) entered with (n) positions. – When (operator) character entered is ‘m’ or ‘M’, your program displays the character resulting of the multiplication of the value of … Read more »
anyone know how to solve that question
implement a multithreaded UDP server and client in java using JDK open source library 1 Client will send a number to server on tcp packet(continuous stream) 2.Server will acknowledge the request with sending back the same number(echo) 3.Client will maintain a data structure which stores un acknowledged numbers from server
class A { int a; String b; boolean c; A()//default { a=100; b=”pawan”; c=true; } void Disp() { System.out.print(a+” “+b+” “+c); } } class B { public static void main(String []arga){ A r=new A(); r.Disp(); } }
public class TicketCost ( public static void main(String[] args) ( I Declare variables int age; double cost; String msge;
Because each question on the Math section deals with different numbers and mathematical scenarios, it's not as simple as the Reading and Writing section to identify exactly what each question stem will look like. You can still use the descriptions in this section to determine which math domains and skills you want to focus on in the Student Question Bank.
Related topics.
Lakethia Clark stands in her son's bedroom in her home in Tuscaloosa, Alabama. Clark will soon open her own home-based child care business. Claire Harbage/NPR hide caption
TUSCALOOSA, Ala. — Lakethia Clark has spent most of her adult life taking care of children, first at a church day care and later in a child care center. She loves children, but after 15 years, she was getting paid too little and looking after too many kids.
So like many child care workers, she quit. Clark became a housekeeper at a hospital, which paid better, but she missed her old profession.
"It kind of broke my heart," she says. "I miss my babies."
She had long thought about starting her own child care business but always found the licensing process and the startup costs daunting.
Today, however, Clark is getting ready to return to a line of work she loves — on her own terms. She's starting her own small business, caring for as many as six children. And she's doing it right in her own home.
For months, she has been working hard to turn her three-bedroom ranch house and her tree-lined backyard into a children's wonderland.
Clark is among the first participants in a program called 3by3. It's the brainchild of Holly Glasgow, a longtime child development educator at Shelton State Community College.
Her vision for the program: dramatically growing the number of small, home-based child care businesses, formally known as family child care homes. It's a program that could prove important for Alabama, by providing more child care options to help boost the state's workforce.
Home-based child care is not new, but Glasgow's exhaustive efforts to provide wrap-around training and guidance, elevating the often invisible child care workforce, have drawn attention and even visitors from states including Colorado and California.
The initiative is one of many being piloted around the U.S. as federal and state governments, along with the business community, have come to recognize child care as essential to economic growth.
Clark has a collection of books in her son's room and will add more once she begins caring for kids out of her home. Claire Harbage/NPR hide caption
It's an especially pressing issue in Alabama, a state with one of the country's lowest labor force participation rates.
To get her program going, Glasgow got creative, "blending and braiding" funding from a number of sources, including the federal Workforce Innovation and Opportunity Act, which aims to help job seekers move into high-quality careers.
Other funders include the Chamber of Commerce of West Alabama as well as the Women's Foundation of Alabama, a philanthropic organization focused on accelerating economic opportunity for women.
"It's an interesting narrative shift, that child care isn't just on the mom," says Lillian Brand, vice president of external affairs at the Women’s Foundation of Alabama. "It's really on the entire economy in order to keep us all moving forward."
Child care needs are severely unmet.
The need for more child care is evident in the numbers. Glasgow estimates Tuscaloosa County has over 12,000 children under age 5 but just over 3,000 child care spots.
Some of those spots are at the community-based pre-K center on the campus of Shelton State, which Glasgow oversees.
While a couple of kids paint pictures at an arts and crafts station, others check in on caterpillars on their journey of metamorphosis. Across the room, more children take turns playing customer and shopkeeper in a make-believe flower shop.
"Happy, healthy, safe is our goal," says Glasgow.
Holly Glasgow talks to children in the pre-K program she directs on the campus of Shelton State Community College in Tuscaloosa. Given the high cost of building child care centers like this one, Glasgow is focused on developing another model of child care — family child care homes. Claire Harbage/NPR hide caption
She would love for every young child in Alabama to have a spot at a center like this one. But she knows that's impossible. The main impediment is cost.
When an Alabama nonprofit foundation approached her with a fundraising proposal and asked how many child care centers could be built with $10 million, she told them: less than one.
"They were floored," she says.
So instead, Glasgow is focusing her efforts on family child care homes. She believes these small businesses can achieve the same level of quality as larger centers but at a much lower cost and in a way that may better suit Tuscaloosa's working parents.
Among the top employers in this region are hospitals and manufacturers, including Mercedes-Benz and the food company Smucker's, which has been recruiting workers for a brand-new plant not far away.
Glasgow points out that these employers need workers around the clock, but few child care providers offer care in the evenings, on weekends and overnight.
Family child care homes, which are typically run by women who care for their own children and a handful of others, can be more flexible with their hours. They can also provide a more homelike environment, which many parents who work overnight shifts prefer, Glasgow says.
"Your kids still go to bed in a bedroom," she says. "They still have breakfast at the kitchen table."
The first cohort of 3by3 participants wrapped up their coursework this spring. This included five intensive weeks of classes on child development, health and safety, and how to run a small business.
On top of that, there are the home visits.
Glasgow visits the home of Lakethia Clark to help her reconfigure her living quarters into play areas for children. Claire Harbage/NPR hide caption
On a recent sunny morning, Glasgow headed to Clark's home on a corner lot to help her reimagine her living quarters as play and learning spaces and to ensure that everything is up to code.
Glasgow works quickly, whipping out a laser measuring tool as she sketches a floor plan.
"Miss Holly ... that lady is awesome," says a smiling Clark.
Clark lays out her vision for her formal living room: one sofa moved to the side, another one taken out to make room for children's tables, a couple of carpets, and shelves for toys and books.
"I can't wait to put stuff on the walls," she says.
Clark jumped at the opportunity to open her own home-based child care business. She expects to receive her license sometime this summer. Claire Harbage/NPR hide caption
Glasgow has $5,000 to $10,000 to spend on furniture and supplies for each new family child care home. Paths for Success, the nonprofit foundation that originally approached Glasgow about building child care centers, provides the health and safety materials, including fire extinguishers, hardwired smoke detectors, flashlights, and cribs and cots.
It's the assist Clark needed to get her business off the ground. Before now, she says, her finances always got in the way.
Although she had worked in child care for years, Clark's hourly wage never topped $13.50 an hour. For a while, she worked a second job at Taco Casa to save enough money for the down payment on her house.
Now, she is looking forward to becoming a small-business owner. There are tax benefits, including being able to deduct part of her mortgage as a business expense. She may qualify for a new Alabama tax credit for child care providers.
Best of all, she'll get to be her own boss.
Glasgow works with Clark to reimagine Clark's living room as a play and learning space. Claire Harbage/NPR hide caption
Looking out over her spacious, shady backyard, she imagines children covering her wooden fence with chalk drawings, something she loved watching kids do at her last child care job.
"The owners of the day care used to get so mad," she says, laughing. "It's just artwork! It's going to disappear."
Already, parents she knew from her old job have been calling her, hoping to send her their younger kids.
"They know what type of worker I was," she says. "They know I always put the kids first."
With all her paperwork submitted, Clark is hoping to get final clearance this summer, in time to welcome kids into her home.
Insertion sort in different languages.
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is a stable sorting algorithm, meaning that elements with equal values maintain their relative order in the sorted output.
Insertion sort is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. Then, you pick a card from the unsorted group and put it in the right place in the sorted group.
Insertion sort is a simple sorting algorithm that works by building a sorted array one element at a time. It is considered an ” in-place ” sorting algorithm, meaning it doesn’t require any additional memory space beyond the original array.
To achieve insertion sort, follow these steps:
Consider an array having elements : {23, 1, 10, 5, 2} First Pass: Current element is 23 The first element in the array is assumed to be sorted. The sorted part until 0th index is : [23] Second Pass: Compare 1 with 23 (current element with the sorted part). Since 1 is smaller, insert 1 before 23 . The sorted part until 1st index is: [1, 23] Third Pass: Compare 10 with 1 and 23 (current element with the sorted part). Since 10 is greater than 1 and smaller than 23 , insert 10 between 1 and 23 . The sorted part until 2nd index is: [1, 10, 23] Fourth Pass: Compare 5 with 1 , 10 , and 23 (current element with the sorted part). Since 5 is greater than 1 and smaller than 10 , insert 5 between 1 and 10 . The sorted part until 3rd index is : [1, 5, 10, 23] Fifth Pass: Compare 2 with 1, 5, 10 , and 23 (current element with the sorted part). Since 2 is greater than 1 and smaller than 5 insert 2 between 1 and 5 . The sorted part until 4th index is: [1, 2, 5, 10, 23] Final Array: The sorted array is: [1, 2, 5, 10, 23]
To deepen your understanding of sorting algorithms like insertion sort and other essential data structures, consider enrolling in our comprehensive course, Tech Interview 101 – From DSA to System Design . This course covers data structures and algorithms from basic to advanced levels , ensuring you have a solid foundation to excel in technical exams and interviews. Building this knowledge is crucial for your success in the tech industry.
Time Complexity: O(N^2) Auxiliary Space: O(1)
Time complexity of insertion sort.
Insertion sort is commonly used in situations where:
Q1. What are the Boundary Cases of the Insertion Sort algorithm?
Insertion sort takes the maximum time to sort if elements are sorted in reverse order. And it takes minimum time (Order of n) when elements are already sorted.
Q2. What is the Algorithmic Paradigm of the Insertion Sort algorithm?
The Insertion Sort algorithm follows an incremental approach.
Q3. Is Insertion Sort an in-place sorting algorithm?
Yes, insertion sort is an in-place sorting algorithm.
Q4. Is Insertion Sort a stable algorithm?
Yes, insertion sort is a stable sorting algorithm.
Q5. When is the Insertion Sort algorithm used?
Insertion sort is used when number of elements is small. It can also be useful when the input array is almost sorted, and only a few elements are misplaced in a complete big array.
Similar reads.
IMAGES
VIDEO
COMMENTS
Write Hello World Program in Java. The solution to the Problem is mentioned below: Java // Java Program to Print ... We hope these exercises have helped you understand Java better and you can solve beginner to advanced-level questions on Java programming. Solving these Java programming exercise questions will not only help you master theory ...
The best way we learn anything is by practice and exercise questions. Here you have the opportunity to practice the Java programming language concepts by solving the exercises starting from basic to more complex exercises. It is recommended to do these exercises by yourself first before checking the solution.
Here is a big list of Java programs for Job Interviews. As I said, it includes questions from problem-solving, linked list, array, string, matrix, bitwise operators and other miscellaneous parts of programming. Once you are gone through these questions, you can handle a good number of questions on real Job interviews. 1. Fibonacci series
Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and performance. In this article, we will provide 200+ Core Java Interview Questions tailored for both freshers and experienced professionals with 3, 5, and 8 years of experience.
Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.
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 ...
Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.
Complete your Java coding practice with our online Java practice course on CodeChef. Solve over 180 coding problems and challenges to get better at Java. Courses. Learn Python 10 courses. Learn C++ 9 ... Multiple Choice Question: Easy: CodeChef Learn Problem Solving: 287: Multiple Choice Question: Easy: Learning SQL: 339: Multiple Choice ...
It has been 8 years since Java 8 was released. I have already shared the Java 8 Interview Questions and Answers and also Java 8 Stream API Interview Questions and Answers.You can also find the Java 8 — Real-Time Coding Interview Questions and Answers.. In this tutorial, I will be sharing the top Java 8 coding and programming interview questions and answers.
Java Problem Solving Questions. This skill corresponds to the developer's ability to evaluate and resolve a problem by writing an efficient algorithm in Java. Any developers should be able to solve simple problems but advanced analytical skills and logical reasoning are essential when your are hiring Java R&D developers. Problem Solving ...
Algorithm-based questions are a staple of any modern coding interview, as they demonstrate your problem-solving and critical thinking skills. To make sure you don't get caught off guard in your next Java interview, we've put together 15 of the most common algorithm coding questions used by most tech companies and recruiters across the industry. ...
In this article, we dealt with a variety of Java programming questions categorized as basic programs, control statements, Arrays, Strings, OOPs, and much more that are frequently asked in interviews and exams. Each Java program will give you a different approach to solving a particular problem in Java.
How Edabit Works. This is an introduction to how challenges on Edabit work. In the Code tab above you'll see a starter function that looks like this: public static boolean returnTrue () { } All you have to do is type return true; between the curly braces { } and then click the Check button. If you did this correctly, the button will turn re ...
These questions cover more specific concepts and language-specific knowledge, and are also meant to be solved in a collaborative IDE. You can access the sample inputs, sample outputs, and base code for each question by clicking the solve problem links. Java Regex. Solve Problem. Write a class called MyRegex which will contain a string pattern.
Related: Java Interview Questions for Experienced Programmers 13. How do you reverse a string in Java? There's no reverse utility provided in Java. Hiring managers might ask this question to determine your knowledge of Java and your problem-solving skills. You can create a character array from the string and iterate it from the end to the ...
Java Interview Questions and Answers. The pressure to perform well in an interview can feel overwhelming. Despite your knowledge and experience, nervousness could get in the way of putting your best foot forward. But, if you know the questions to expect and how to answer them, you can relax and focus on showcasing what you know and what you can do.
Java is a popular programming language that is used to develop a wide variety of applications. One of the best ways to learn Java is to practice writing programs. Many resources are available online and in libraries to help you find Java practice programs. When practising Java programs, it is important to focus on understanding the concepts ...
1. For a given array of integers (positive and negative) find the largest sum of a contiguous sequence. 2. Algorithm: Implement a queue using 2 stacks (solution) 3. Algorithm: Integer division without the division operator (/) (solution) 4. How to print All permutations of a Given String in Java ( solution) 5.
Java Interview Programming Questions and Answers. Java is an object-oriented programming language and computing platform first released by Sun Microsystems in 1995. During an interview it does not matter whatever framework you know, the initial stage of the interview is always based on the programming sense, coding skills, and problem-solving ...
Here are a few examples of technical problem-solving questions: 1. Mini-Max Sum. This well-known challenge, which asks the interviewee to find the maximum and minimum sum among an array of given numbers, is based on a basic but important programming concept called sorting, as well as integer overflow.
This article delves into five common Java interview problems, providing both starter code and detailed solutions to enhance your understanding and problem-solving skills. Array Rotation. Problem ...
More Important Basic Questions for Java Developers. Keep in mind that, although Java is already an object-oriented programming language, you may want to ask questions about object-oriented programming that are more theoretical, conceptual, and outside general Java programming. ... problem-solving, time management, and more. You can also explore ...
Java : Switch Statement - Exercises and Solution. 1. Write a program to read a weekday number and print weekday name using switch statement. View Solution. 2. Write a program to read gender (M/F) and print the corresponding gender using a switch statement. View Solution.
Before you leave, take this Java Collections Interview Questions interview guide with you. Download PDF exit . Get a Free ... Before we use a collection, we must choose the most relevant collection for the problem we are seeking to solve. If we pick the wrong one, our program may still run, but it will be inefficient. On the other hand, if we ...
Java Solved programs —-> Java is a powerful general-purpose programming language. It is fast, portable and available in all platforms. This page contains the Java solved programs/examples with solutions, here we are providing most important programs on each topic. These Java examples cover a wide range of programming areas in Computer Science.
Domain: Problem-Solving and Data Analysis Skill: Evaluating statistical claims—Observational studies and experiments Solve real-world and mathematical problems about area, perimeter, surface area, or volume of a geometric figure, and use scale factors to calculate changes to length and area.
A project in Alabama seeks to drastically grow the number of home-based child care options. It could help the state's workforce, especially during nontraditional hours.
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is a stable sorting algorithm, meaning that elements with equal values maintain their relative order in the sorted output.. Insertion sort is like sorting playing cards in your hands.