FailSafe does not throws any exception but instead, it creates a copy of the collection to iterate.
HashMap | TreeMap |
---|---|
Hasmap uses a hashtable in order to store key-value pairs. | Treemap uses Red-black trees to store key-value pair. |
Hashmap does not maintain any specific order for key-value pairs. | Treemap maintains a natural ordering based on the keys. |
Order of iteration is not guaranteed in the hashmap. | Iteration is of sorted order based on keys. |
Hashmaps are faster for retrieval compared to Treemap. | Retrieval in Treemap is slower as it uses tree traversal to find keys. |
Hashmap is implemented by using an Array of linked list. | TreeMap is implemented using a Red-black Tree. |
Hashmap uses the equals() method of the Object class to compare keys. | TreeMap uses compareTo() method to compare keys. |
Queue | Deque |
---|---|
The queue is a linear Data structure that is used to store a collection of elements. | Deque also known as a Double-ended queue is also a linear data structure that stores a collection of elements with operations to remove and add from both ends. |
Elements in the queue can only be inserted at the end of the data structure. | Elements can be inserted from both ends of the data structure. |
Queue can be implemented using Array or Linked List. | Dequeue can be implemented using Circular Array or Doubly Linked List. |
Queues are generally used to implement a waiting list or task queue. | Deque is used to implement a stack or dequeuing elements from both ends. |
|
|
HashSet | TreeSet |
---|---|
HashSet is unordered. | TreeSet is based on natural ordering. |
HashSet allows null elements. | TreeSet does not allow null elements. |
HashSet is Implemented by the HashSet class. | TreeSet is Implemented by TreeSet class. |
HashSet<String> hs = new HashSet<>(); | TreeSet<String> ts = new TreeSet<>(); |
Q1. what is a java developer’s salary in india.
According to various resources, The average salary of a Java Backend Developer is more than 14 lakhs per annum which is 30% higher than any other developer role . Here you can also check our latest course on Java Backend Development !
A Java developer writes code, designs software solutions, and builds applications using the Java programming language. They collaborate with teams, solve problems, and ensure code quality for efficient and reliable software development.
A Java developer should have a strong understanding of core Java concepts such as object-oriented programming, data types, control structures, and exception handling. Additionally, knowledge of frameworks like Spring, Hibernate, and web development technologies like Servlets and JSP is beneficial. Other than Technical Skills Problem-solving, debugging, and critical thinking skills are also highly valued.
To prepare for a Java interview, start by reviewing fundamental Java concepts and practice coding exercises. Study common interview questions related to core Java, data structures, algorithms, and multithreading from GeeksforGeeks Interview Section . Additionally, brush up on design patterns, database connectivity, and web development frameworks. Practising coding challenges on platforms like GeekforGeeks Practice Portal can also be helpful.
To stand out in a Java interview, demonstrate a deep understanding of Java concepts and practical applications. Showcase your problem-solving skills by explaining your approach to complex scenarios and providing efficient solutions. Additionally, highlight any relevant projects or contributions you’ve made to the Java community. Showing enthusiasm, good communication, and a willingness to learn can also leave a positive impression.
Similar reads.
Javarevisited
Learn Java, Programming, Spring, Hibernate throw tutorials, examples, and interview questions
Nice collection of interview question
Good Programmas
Good collection
Do you know any other books recommended for coding interviews?
I used: "Cracking the Coding Interview" by Gayle Laakmann McDowell "TOP 30 Java Interview Coding Tasks" by Matthew Urban "Elements of Programming Interviews in Java" by Adnan Aziz, Tsung-Hsien Lee, Amit Prakash "Coding Interview Questions" by Narasimha Karumanchi
nice collection of questions. Thank you.
Really helpful ! Thanks !
String palindrome is found with error.unable to view it
Hello @Unknown, can you give more details? you mean you can't see the solution?
Ah got it, the link is incorrect, I'll correct it.
perfect ...thank you,Guys!
Thanks! for help,guys.
Very nice.. But I need a differential and integral problems in java If any one think about it reply me... We'll discuss about it😊😊😊
Nice thank you
It's very much benificial for us
My problem with this type of question is that most of them do not reflect the types of problems you encounter on the job. A good java programmer knows how to perform task needed by the job. A DB centric application will manipulate many data results efficiently. That might mean knowing lists, iterations, or using lombok. A realtime application will be more focused on things like concurrency. I've used Java professionally since it was in beta nad have never had to shift bits.
Hello Bill, interview and real work is always different. It's part of the culture we have. I think asking these kind of question is to check if people have good fundamental knowledge or not. This is important for engineering a solution rather than just coding. For example, if you know about paging, swap memory, virtual memory you will be better equipped to solve memory related problems of Java application. Just my 2 cent.
Can u plzz help me in solving the below pattern-: 55555 54444 54333 54322 54321
@Unknown, I can give you an hint, use two for loop and a combination of system.out.println() and system.print() to print this pattern
@Unknown public static void main(String[] s) { int i=55555; int r=1111; System.out.println(i); for(int j=0;j<4;j++) { i=i-r; System.out.println(i); r=r/10; }
@Unknown public static void main(String []args){ String num = ""; for(int i = 5; i>=1; i--){ num += i; //System.out.print(i); for(int j = 1; j<=i; j++){ System.out.print(i); } if(i != 1){ System.out.print("\n"+num); } } }
what are the modifiers applicable in java main method
5432 is the answer of program
Very helpful this kind of coding to pass in coding test
Num value is 5
*** * ** ** * *** Please slove this program
Reverse String ..... public class Reve { public static void main(String [] args) { String s="hello java"; String s1=" "; for(int i=s.length()-1;i>=0;i--) { s1=s1+s.CharAt(); } System.out.println("Original String : "+s); System.out.println("Reverse String : "+s1); } }
Can you please add Dynamic Programming Interview questions on this list?
1st non Repeating character and Binary Search were asked.
Any newsletter would you recommend for coding interview preparation?
Preparing for java and spring boot interview.
Get new posts by email:.
Java stdin and stdout i easy java (basic) max score: 5 success rate: 96.83%, java if-else easy java (basic) max score: 10 success rate: 91.38%, java stdin and stdout ii easy java (basic) max score: 10 success rate: 92.78%, java output formatting easy java (basic) max score: 10 success rate: 96.54%, java loops i easy java (basic) max score: 10 success rate: 97.66%, java loops ii easy java (basic) max score: 10 success rate: 97.32%, java datatypes easy java (basic) max score: 10 success rate: 93.70%, java end-of-file easy java (basic) max score: 10 success rate: 97.91%, java static initializer block easy java (basic) max score: 10 success rate: 96.12%, cookie support is required to access hackerrank.
Seems like cookies are disabled on this browser, please enable them to open this website
How to solve these java coding challenges, why codegym is the best platform for your java code practice.
Practice java code online with codegym.
In Java programming, commands are essential instructions that tell the computer what to do. These commands are written in a specific way so the computer can understand and execute them. Every program in Java is a set of commands. At the beginning of your Java programming practice , it’s good to know a few basic principles:
Here is an example of the command:
The command System.out.println("Hello, World!"); tells the computer to display the text inside the quotation marks.
If you want to display a number and not text, then you do not need to put quotation marks. You can simply write the number. Or an arithmetic operation. For example:
Command to display the number 1.
A command in which two numbers are summed and their sum (10) is displayed.
As we discussed in the basic rules, a command cannot exist on its own in Java. It must be within a method, and a method must be within a class. Here is the simplest program that prints the string "Hello, World!".
We have a class called HelloWorld , a method called main() , and the command System.out.println("Hello, World!") . You may not understand everything in the code yet, but that's okay! You'll learn more about it later. The good news is that you can already write your first program with the knowledge you've gained.
Attention! You can add comments in your code. Comments in Java are lines of code that are ignored by the compiler, but you can mark with them your code to make it clear for you and other programmers.
Single-line comments start with two forward slashes (//) and end at the end of the line. In example above we have a comment //here we print the text out
You can read the theory on this topic here , here , and here . But try practicing first!
Explore the Java coding exercises for practicing with commands below. First, read the conditions, scroll down to the Solution box, and type your solution. Then, click Verify (above the Conditions box) to check the correctness of your program.
The two main types in Java are String and int. We store strings/text in String, and integers (whole numbers) in int. We have already used strings and integers in previous examples without explicit declaration, by specifying them directly in the System.out.println() operator.
In the first case “I am a string” is a String in the second case 5 is an integer of type int. However, most often, in order to manipulate data, variables must be declared before being used in the program. To do this, you need to specify the type of the variable and its name. You can also set a variable to a specific value, or you can do this later. Example:
Here we declared a variable called a but didn't give it any value, declared a variable b and gave it the value 5 , declared a string called s and gave it the value Hello, World!
Attention! In Java, the = sign is not an equals sign, but an assignment operator. That is, the variable (you can imagine it as an empty box) is assigned the value that is on the right (you can imagine that this value was put in the empty box).
We created an integer variable named a with the first command and assigned it the value 5 with the second command.
Before moving on to practice, let's look at an example program where we will declare variables and assign values to them:
In the program, we first declared an int variable named a but did not immediately assign it a value. Then we declared an int variable named b and "put" the value 5 in it. Then we declared a string named s and assigned it the value "Hello, World!" After that, we assigned the value 2 to the variable a that we declared earlier, and then we printed the variable a, the sum of the variables a and b, and the variable s to the screen
This program will display the following:
We already know how to print to the console, but how do we read from it? For this, we use the Scanner class. To use Scanner, we first need to create an instance of the class. We can do this with the following code:
Once we have created an instance of Scanner, we can use the next() method to read input from the console or nextInt() if we should read an integer.
The following code reads a number from the console and prints it to the console:
Here we first import a library scanner, then ask a user to enter a number. Later we created a scanner to read the user's input and print the input out.
This code will print the following output in case of user’s input is 5:
More information about the topic you could read here , here , and here .
See the exercises on Types and keyboard input to practice Java coding:
Conditions and If statements in Java allow your program to make decisions. For example, you can use them to check if a user has entered a valid password, or to determine whether a number is even or odd. For this purpose, there’s an 'if/else statement' in Java.
The syntax for an if statement is as follows:
Here could be one or more conditions in if and zero or one condition in else.
Here's a simple example:
In this example, we check if the variable "age" is greater than or equal to 18. If it is, we print "You are an adult." If not, we print "You are a minor."
Here are some Java practice exercises to understand Conditions and If statements:
In Java, a "boolean" is a data type that can have one of two values: true or false. Here's a simple example:
The output of this program is here:
In addition to representing true or false values, booleans in Java can be combined using logical operators. Here, we introduce the logical AND (&&) and logical OR (||) operators.
So the output of this program is:
More information about the topic you could read here , and here .
Here are some Java exercises to practice booleans:
With loops, you can execute any command or a block of commands multiple times. The construction of the while loop is:
Loops are essential in programming to execute a block of code repeatedly. Java provides two commonly used loops: while and for.
1. while Loop: The while loop continues executing a block of code as long as a specified condition is true. Firstly, the condition is checked. While it’s true, the body of the loop (commands) is executed. If the condition is always true, the loop will repeat infinitely, and if the condition is false, the commands in a loop will never be executed.
In this example, the code inside the while loop will run repeatedly as long as count is less than or equal to 5.
2. for Loop: The for loop is used for iterating a specific number of times.
In this for loop, we initialize i to 1, specify the condition i <= 5, and increment i by 1 in each iteration. It will print "Count: 1" to "Count: 5."
Here are some Java coding challenges to practice the loops:
An array in Java is a data structure that allows you to store multiple values of the same type under a single variable name. It acts as a container for elements that can be accessed using an index.
What you should know about arrays in Java:
In this example, we create an integer array, assign values to its elements, and access an element using indexing.
In Java, methods are like mini-programs within your main program. They are used to perform specific tasks, making your code more organized and manageable. Methods take a set of instructions and encapsulate them under a single name for easy reuse. Here's how you declare a method:
In this example, we have a main method (the entry point of the program) and a customMethod that we've defined. The main method calls customMethod, which prints a message. This illustrates how methods help organize and reuse code in Java, making it more efficient and readable.
In this example, we have a main method that calls the add method with two numbers (5 and 3). The add method calculates the sum and returns it. The result is then printed in the main method.
All composite types in Java consist of simpler ones, up until we end up with primitive types. An example of a primitive type is int, while String is a composite type that stores its data as a table of characters (primitive type char). Here are some examples of primitive types in Java:
Simple types are grouped into composite types, that are called classes. Example:
We declared a composite type Person and stored the data in a String (name) and int variable for an age of a person. Since composite types include many primitive types, they take up more memory than variables of the primitive types.
See the exercises for a coding practice in Java data types:
String is the most popular class in Java programs. Its objects are stored in a memory in a special way. The structure of this class is rather simple: there’s a character array (char array) inside, that stores all the characters of the string.
String class also has many helper classes to simplify working with strings in Java, and a lot of methods. Here’s what you can do while working with strings: compare them, search for substrings, and create new substrings.
Example of comparing strings using the equals() method.
Also you can check if a string contains a substring using the contains() method.
You can create a new substring from an existing string using the substring() method.
More information about the topic you could read here , here , here , here , and here .
Here are some Java programming exercises to practice the strings:
In Java, objects are instances of classes that you can create to represent and work with real-world entities or concepts. Here's how you can create objects:
First, you need to define a class that describes the properties and behaviors of your object. You can then create an object of that class using the new keyword like this:
It invokes the constructor of a class.If the constructor takes arguments, you can pass them within the parentheses. For example, to create an object of class Person with the name "Jane" and age 25, you would write:
Suppose you want to create a simple Person class with a name property and a sayHello method. Here's how you do it:
In this example, we defined a Person class with a name property and a sayHello method. We then created two Person objects (person1 and person2) and used them to represent individuals with different names.
Here are some coding challenges in Java object creation:
Static classes and methods in Java are used to create members that belong to the class itself, rather than to instances of the class. They can be accessed without creating an object of the class.
Static methods and classes are useful when you want to define utility methods or encapsulate related classes within a larger class without requiring an instance of the outer class. They are often used in various Java libraries and frameworks for organizing and providing utility functions.
You declare them with the static modifier.
Static Methods
A static method is a method that belongs to the class rather than any specific instance. You can call a static method using the class name, without creating an object of that class.
In this example, the add method is static. You can directly call it using Calculator.add(5, 3)
Static Classes
In Java, you can also have static nested classes, which are classes defined within another class and marked as static. These static nested classes can be accessed using the outer class's name.
In this example, Student is a static nested class within the School class. You can access it using School.Student.
More information about the topic you could read here , here , here , and here .
See below the exercises on Static classes and methods in our Java coding practice for beginners:
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.
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).
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.
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.
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.
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.
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:
Finalize Method:
Access Modifiers in Java:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 .
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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.
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.
Key points in the comments:.
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.
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.
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.
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.
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.
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.
The JMM also addresses the concept of safe publication, ensuring that objects are fully constructed and visible to other threads after their creation.
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.
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:
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).
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.
\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.
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.
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.
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.
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.
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.
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 .
Unboxing is the reverse process, where the Java compiler automatically converts an object of a wrapper type to its corresponding primitive type.
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 .
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.
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.
@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.
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.
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.
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:
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:
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.
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.
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.
Usage and advantages:.
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.
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.
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.
Java I/O streams are broadly categorized into two types:
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.
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.
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.
Unlike languages where memory management is manual (like C/C++), Java provides automatic memory management through its garbage collector, which runs in the background.
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).
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.
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.
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.
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.
Java NIO is particularly effective in environments that require high-performance and low latency, such as:
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:
Buffers in NIO are essential for data transfer, acting as temporary storage for data during I/O operations. Their key operations include:
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.
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.
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.
Let's break down the implementation using the Observer pattern in the context of a newsletter system:
Step 2: create the observer abstract class (subscriber), step 3: create concrete observer classes.
EmailSubscriber.java
SMSSubscriber.java
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.
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
Utilize tools like SonarQube, FindBugs, or PMD to statically analyze code for patterns that could lead to memory leaks.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
Visit LunarTech's website for these resources and more information on the bootcamp .
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.
Read more posts .
If this article was helpful, share it .
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Java methods, java classes, java file handling, java how to's, java reference, java examples, java exercises.
You can test your Java skills with W3Schools' Exercises.
We have gathered a variety of Java exercises (with answers) for each Java Chapter.
Try to solve an exercise by editing some code, or show the answer to see what you've done wrong.
You will get 1 point for each correct answer. Your score and total score will always be displayed.
Start Java Exercises ❯
If you don't know Java, we suggest that you read our Java Tutorial from scratch.
Get certified by completing the course
If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]
If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]
Top references, top examples, get certified.
I created this website to help developers improve their programming skills by practising simple coding exercises. The target audience is Software Engineers, Test Automation Engineers, or anyone curious about computer programming. The primary programming language is Java, as it is mature and easy to learn, but you can practice the same problems in any other language (Kotlin, Python, Javascript, etc.).
Easy, moderate or challenging.
From a list of coding exercises commonly found in interviews.
No IDE, no auto-correct... just like the whiteboard interview question.
Typically 3-5 unit tests that verify your code.
Don't have an account? Sign up
Forgot your password?
Already have an account? Login
Have you read our submission guidelines?
Go back to Sign In
To land the job, it helps to review common and challenging Java interview questions. After all, the class-based, general-purpose, object-oriented programming language is one of the most widely used programming languages in the world .
We prepared these Java interview questions with answers from experts. Expect to cover the basics with beginner-friendly topics and much more advanced challenges with specific code to help professional Software Developers and Android Applications Developers.
Remember that, with a plethora of great features , the programming language is preferred not only by seasoned experts but also by those new to the programming world. Our interview questions start with basic Java concepts and progress to much more difficult challenges.
Whether you're seeking a new gig or hiring to expand your team, read on to review the best Java interview questions for 2024.
We also recommend you brush up on your Java skills with this Java Cheat Sheet before starting your Java interview preparation.
We have divided these interview questions into several sections. Check the breakdown below to review basic, advanced, OOPs, exception handling, and programming Java interview questions. We also have specific examples of code. Review the coding Java interview questions section for reference.
1. what is java.
Java is an object-oriented, high-level, general-purpose programming language originally designed by James Gosling and further developed by the Oracle Corporation. It is one of the most popular programming languages in the world .
JVM is a program that interprets the intermediate Java byte code and generates the desired output. It is because of bytecode and JVM that programs written in Java are highly portable.
The following are the various features of the Java programming language:
You may want to check out detailed explanations of Java features here .
In Just-in-Time compilation, the required code is executed at run time. Typically, it involves translating bytecode into machine code and then executing it directly. It allows for high performance. The JIT compiler is enabled by default in Java and gets activated as soon as a method is called.
It then compiles the bytecode of the Java method into native machine code.
After that, the JVM calls the compiled code directly instead of interpreting it.
|
|
|
|
| Java Virtual Machine | Java Runtime Environment | Java Development Kit |
| It provides a runtime environment to execute Java bytecode. | It is a set of software tools used for developing Java applications. | It is a software development environment used to develop Java applications. |
| It is a runtime instance created when we run a Java class. | It exists physically. | It exists physically. |
| Its implementation is known as JRE | It is the implementation of JVM | It is an implementation of any one of the below given Java Platforms released by Oracle Corporation: Standard Edition Java Platform Enterprise Edition Java Platform Micro Edition Java Platform |
JIT compiler runs after the program is executed and compiles the code into a faster form, hosting the CPU's native instructing set. JIT can access dynamic runtime information, whereas a standard compiler doesn't and can make better optimizations like inlining functions that are used frequently.
A Java IDE is a software that allows Java developers to easily write as well as debug Java programs. It is basically a collection of various programming tools, accessible via a single interface, and several helpful features, such as code completion and syntax highlighting.
Codenvy, Eclipse, and NetBeans are some of the most popular Java IDEs .
Java does not depend on any particular hardware or software because it is compiled by the compiler and then converted into byte code. Byte code is platform-independent and can run on multiple systems. The only requirement is that Java needs a runtime environment, i.e., JRE, which is a set of tools used for developing Java applications.
The concept of assigning a variable of one data type to a variable of another data type. This is not possible for the boolean data type. There are two types: implicit and explicit.
The different types of typecasting are:
After execution, the variable i will contain only 3 and not the decimal portion.
long l = 123456789;
byte b = ( byte ) l; // byte is of not the same range as long so there will be loss of data.
Access modifiers are predefined keywords in Java that are used to restrict the access of a class, method, constructor, and data member in another class. Java supports four access modifiers:
|
|
|
|
|
Same class | yes | yes | yes | yes |
Same package subclass | yes | no | yes | yes |
Same package non-subclass | yes | no | yes | yes |
Different package subclass | no | no | yes | yes |
Different package non-subclass | no | no | no | yes |
The local variables are not initialized to any default value, neither primitives nor object references.
13. what is object-oriented programming .
OOPs is a programming paradigm centered around objects rather than functions. It is not a tool or a programming language, it is a paradigm that was designed to overcome the flaws of procedural programming .
There are many languages that follow OOPs concepts — some popular ones are Java, Python, and Ruby. Some frameworks also follow OOPs concepts, such as Angular.
The following are the various OOPS Concepts:
Decision Making Java Interview Questions
|
|
Used with both loop and switch statement. | Used with only loop statements. |
It terminates the loop or switch block. | It does not terminate but skips to the next iteration. |
16. what is an object.
An instance of a Java class is known as an object. Two important properties of a Java object are behavior and state . An object is created as soon as the JVM comes across the new keyword.
A class is a collection of objects of similar data types. Classes are user-defined data types and behave like built-in types of a programming language.
Syntax of a class:
Example of Class:
A class has two sections: one declares variables, and the other declares methods. These are called instance variables and instance methods, respectively. They are termed so because every time a class is instantiated, a new copy of each of them is created.
Variables and methods can be created that are common to all objects and accessed without using a particular object by declaring them static. Static members are also available to be used by other classes and methods.
A constructor is a method that has the same name as that of the class to which it belongs. As soon as a new object is created, a constructor corresponding to the class gets invoked. Although the user can explicitly create a constructor, it is created on its own as soon as a class is created. This is known as the default constructor. Constructors can be overloaded.
If an explicitly-created constructor has a parameter, then it is necessary to create another constructor without a parameter.
Variables that are only accessible to the method or code block in which they are declared are known as local variables. Instance variables, on the other hand, are accessible to all methods in a class.
While local variables are declared inside a method or a code block, instance variables are declared inside a class but outside a method. Even when not assigned, instance variables have a value that can be null, 0, 0.0, or false. This isn't the case with local variables that need to be assigned a value, where failing to assign a value will yield an error. Local variables are automatically created when a method is called and destroyed as soon as the method exits. For creating instance variables, the new keyword must be used.
Method overriding in Java allows a subclass to offer a specific implementation of a method that has already been provided by its parent or superclass. Method overriding happens if the subclass method and the Superclass method have:
Overloading is the phenomenon when two or more different methods (method overloading) or operators (operator overloading) have the same representation. For example, the + operator adds two integer values but concatenates two strings. Similarly, an overloaded function called Add can be used for two purposes
Unlike method overriding, method overloading requires two overloaded methods to have the same name but different arguments. The overloaded functions may or may not have different return types.
The final keyword in Java is a non-access modifier that applies only to a class, method, or variable. It serves a different purpose based on the context where it is used.
24. draw a comparison between array and arraylist..
An array necessitates stating the size during the time of declaration, while an array list doesn't necessarily require size as it changes size dynamically. To put an object into an array, there is the need to specify the index. However, no such requirement is in place for an array list. While an array list is parameterized, an array is not parameterized.
String variables are stored in a constant string pool. With the change in the string reference, it becomes impossible to delete the old value. For example, if a string has stored a value "Old," then adding the new value "New" will not delete the old value. It will still be there, however, in a dormant state. In a Stringbuffer, values are stored in a stack. With the change in the string reference, the new value replaces the older value. The Stringbuffer is synchronized (and therefore, thread-safe) and offers slower performance than the StringBuilder, which is also a Stringbuffer but is not synchronized. Hence, performance is faster in Stringbuilder than the Stringbuffer.
The string pool is a collection of strings stored in the heap memory refers to. Whenever a new object is created, it is checked if it is already present in the string pool. If it is already present, then the same reference is returned to the variable, otherwise a new object is created in the string pool, and the respective reference is returned.
27. what do you know about interfaces.
A Java interface is a template that has only method declarations and not method implementations. It is a workaround for achieving multiple inheritances in Java. Some worth remembering important points regarding Java interfaces are:
There are several differences between an Abstract class and an Interface in Java, summed up as follows:
An abstract class in Java is a class that can't be instantiated. Such a class is typically used for providing a base for subclasses to extend as well as implementing the abstract methods and overriding or using the implemented methods defined in the abstract class.
To create an abstract class, it needs to be followed by the abstract keyword. Any abstract class can have both abstract as well as non-abstract methods. A method in Java that only has the declaration and not implementation is known as an abstract method. Also, an abstract method name is followed by the abstract keyword. Any concrete subclass that extends the abstract class must provide an implementation for abstract methods.
If a subclass or child class has two parent classes, that means it inherits the properties from two base classes; it has multiple inheritances. Java does not have multiple inheritances as in case the parent classes have the same method names. Then at runtime, it becomes ambiguous, and the compiler is unable to decide which method to execute from the child class.
31. what are packages in java state some advantages..
Packages are Java's way of grouping a variety of classes and/or interfaces together. The functionality of the objects decides how they are grouped. Packagers act as "containers" for classes.
Enlisted below are the advantages of Packages:
32. how do you make a thread in java give examples..
To make a thread in Java, there are two options:
A disadvantage of using the thread class is that it becomes impossible to extend any other classes.
Nonetheless, it is possible to overload the run() method in the class
The yield() method belongs to the thread class. It transfers the currently running thread to a runnable state and also allows the other threads to execute. In other words, it gives equal priority threads a chance to run. Because yield() is a static method, it does not release any lock.
The thread lifecycle has the following states and follows the following order:
In Java, it is possible to extend only one class. Hence, the thread class is only extended when no other class needs to be extended. If it is required for a class to extend some other class than the thread class, then we need to use the Runnable interface.
The notify() method is used for sending a signal to wake up a single thread in the waiting pool. Contrarily, the notifyAll() method is used for sending a signal to wake up all threads in a waiting pool.
There are several fundamental differences between a process and a thread, stated as follows:
We use the join() method for joining one thread with the end of the currently running thread. It is a non-static method and has an overloaded version. Consider the example below:
The main thread starts execution in the example mentioned above. As soon as the execution reaches the code t.start(), then the thread t starts its stack for execution. The JVM switches between the main thread and the thread there. Once the execution reaches the t.join(), then the thread t alone is executed and allowed to complete its task. Afterwards, the main thread resumes execution.
There are three methods in Java to stop the execution of a thread:
40. what are the various types of exceptions how do you handle them.
Java has provision for two types of exceptions:
Exceptions in Java are handled in two ways:
Declaring the throws keyword: We can declare the exception using throws keyword at the end of the method. For example:
Using try/catch: Any code segment that is expected to yield an exception is surrounded by the try block. Upon the occurrence of the exception, it is caught by the catch block that follows the try block. For example:
Yes, it is possible to write several catch blocks under a single try block. However, the approach needs to be from specific to general. The following example demonstrates it:
While the throws keyword allows declaring an exception, the throw keyword is used to explicitly throw an exception.
Checked exceptions can't be propagated with throw only, but throws allow doing so without the need for anything else.
The throws keyword is followed by a class, whereas the throw keyword is followed by an instance. The throw keyword is used within the method, but the throws keyword is used with the method signature.
Furthermore, it is not possible to throw multiple exceptions, but it is possible to declare multiple exceptions.
There are two crucial exception handling keywords in Java, followed by the third keyword final, which may or may not be used after handling exceptions.
If and when a code segment has chances of having an abnormality or an error, it is placed within a try block. When the exception is raised, it is handled and caught by the catch block.
The try block must have a catch() or a final() or both blocks after it.
When an exception is raised in the try block, it is handled in the catch block.
This block is executed regardless of the exception. It can be placed either after try{} or catch {} block.
The method at the top of the stack throws an exception if it is not caught. It moves to the next method and goes on until caught.
The stack of the above code is:
If an exception occurred in the add() method is not caught, then it moves to the method addition(). It is then moved to the main() method, where the flow of execution stops. It is called Exception Propagation.
46. is an empty file name with .java extension a valid file name.
Yes, Java permits us to save our java file by .java only. It is compiled by javac and run by the java class name. Here’s an example:
To compile: javac.java
To run: Java Any
47. what are collections what are their constituents.
A group of objects in Java is known as collections. Java.util package contains, along with date and time facilities, internationalization, legacy collection classes, etc., the various classes and interfaces for collecting. Alternatively, collections can be considered as a framework designed for storing the objects and manipulating the design in which the objects are stored. You can use collections to perform the following operations on objects:
Following are the various constituents of the collections framework:
HashMap in Java is a map-based collection class, used for storing key & value pairs. It is denoted as HashMap<Key, Value> or HashMap<K, V> HashTable is an array of a list, where each list is called a bucket.
Values contained in a HashTable are unique and depend on the key. Methods are not synchronized in HashMap, while key methods are synchronized in HashTable.
However, HashMap doesn't have thread safety, while HashTable has the same.
For iterating values, HashMap uses an iterator and HashTable uses an enumerator. HashTable doesn't allow anything that is null, while HashMap allows one null key and several null values.
In terms of performance, HashTable is slow. Comparatively, HashMap is faster.
A Java Map is an object that maps keys to values. It can't contain duplicate keys, and each key can map to only one value. In order to determine whether two keys are the same or distinct, Map makes use of the equals() method. There are 4 types of Map in Java, described as follows:
A priority queue, like a regular queue, is an abstract data type, but it has a priority associated with each element contained by it.
The element with the high priority is served before the element with low priority in a priority queue. Elements in a priority queue are ordered either according to the comparator or naturally. The order of the elements in a priority queue represents their relative priority.
In Java, a set is a collection of unique objects. It uses the equals() method to determine whether two objects are the same or not. The various types of set in Java Collections are:
53. what are the various types of garbage collectors in java.
The Java programming language has four types of garbage collectors:
If several threads try to access a single block of code, then there is an increased chance of producing inaccurate results. Synchronization is used to prevent this. Using the synchronization keyword makes a thread need a key to access the synchronized code. Simply, synchronization allows only one thread to access a block of code at a time. Each Java object has a lock, and every lock has only one key. A thread can access a synchronized method only if it can get the key to the lock of the object. The following example demonstrates synchronization:
Note : It is recommended to avoid implementing synchronization for all methods. This is because when only one thread can access the synchronized code, the next thread needs to wait. Consequently, it results in slower performance of the program.
Note : The execute() method needs to be used only in a scenario when there is no certainty about the type of statement. In all other cases, either use executeQuery() or executeUpdate() method.
The following code demonstrates deleting a cookie in JSP:
Final: The final keyword is used for restricting a class, method, and variable. A final class can't be inherited, a final method is disabled from overriding, and a final variable becomes a constant i.e., its value can't be changed.
Finally: Any code inside the final block will be executed, irrespective of whether an exception is handled or not.
Finalize: The finalize method performs the clean up just before the object is garbage collected.
The value stored in a volatile variable is not read from the thread's cache memory but from the main memory. Volatile variables are primarily used during synchronization.
Serialization is the process by which Java objects are converted into the byte stream.
Deserialization is the exact opposite process of serialization where Java objects are retrieved from the byte stream.
A Java object is serialized by writing it to an ObjectOutputStream and deserialized by reading it from an ObjectInputStream.
Typically, the OutOfMemoryError exception is thrown when the JVM is not able to allocate an object due to running out of memory. In such a situation, no memory could be reclaimed by the garbage collector.
There can be several reasons that result in the OutOfMemoryError exception, of which the most notable ones are:
The execution Java program starts with public static void main(String args[ ]), also called the main() method.
Java Programming Masterclass Updated to Java 17
Wrapper classes are responsible for converting the Java primitives into the reference types (objects). A class is dedicated to every primitive data type. They are known as wrapper classes because they wrap the primitive data type into an object of that class. It is present in the Java.lang package. The table below displays the different primitive types and wrapper classes.
|
|
boolean | Boolean |
char | Character |
double | Double |
float | Float |
int | Integer |
long | Long |
A Singleton class allows only one instance of the class to be created. A class can be made singleton with the following steps:
Yes, the program would compile and run without any errors as the order of the specifiers doesn't matter.
|
|
It is a method of String class | It is an operator |
Content comparison | Address comparison |
Pointers are considered to be unsafe, and increase the complexity of the program, adding the concept of pointers can be contradicting. Also, JVM is responsible for implicit memory allocation; thus, to avoid direct access to memory by the user, pointers are discouraged in Java.
|
|
Represents the current instance of the class | Represents the current instance of the parent/base class |
It is used to call the default constructor of the same class | It is used to call the default constructor of the parent/base class. |
Accesses method of the current class | Accesses method of the base class |
Points current class instance | Points to the superclass instance. |
Must be the first line of the block | It must be the first line of the block. |
Apart from having good knowledge about concepts of Java programming, you are also tested for your skills in coding in Java programming language. The following are Java coding interview questions that are relevant for freshers and are quite popular amongst Java programming interviews.
Code snippet i. is an example of method overloading while the code snippet ii. demonstrates method overriding.
72. write a program to delete duplicates from an array., 73. write a program to reverse a number., 74. write a program that implements binary search., 75. write a program to check if a number is prime., 76. write a program to print fibonacci series., 77. write a program to check if the given string is a palindrome., 78. write a program to print the following pattern., 79. write a program to swap two numbers., 80. write a program to check if the given number is an armstrong number..
These core Java Interview Questions and Java Programming Interview Questions are a great way to prepare you for the interview. Review the answers, including the coding examples, and put your best foot forward.
Please note that we also provided a PDF for your preparation so that you can download and learn and prepare on the go:
Download Java Interview Questions PDF
Prefer on-demand videos? Check out this course for further reading and preparation for a Java-based interview: Java Interview Guides: 200+ Interview Question and Answer
Otherwise, we recommend this book to help you succeed in your future Java interviews: Elements of Programming Interviews in Java: The insider guide second edition
There are several basic Java interview questions that can appear in an interview. Look at the ones we’ve listed above to get a sense of them.
You should prepare for a Java interview by learning both the theory and practicing coding. There are several related questions above.
Advanced Java interview questions can be of many kinds, including both theory and coding-based questions. Check out the list of Java programming questions above to see what they are like.
People are also reading:
Simran works at Hackr as a technical writer. The graduate in MS Computer Science from the well known CS hub, aka Silicon Valley, is also an editor of the website. She enjoys writing about any tech topic, including programming, algorithms, cloud, data science, and AI. Traveling, sketching, and gardening are the hobbies that interest her.
Subscribe to our Newsletter for Articles, News, & Jobs.
Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.
In this article
Please login to leave comments
Get news once a week, and don't worry — no spam.
{{ errors }}
{{ message }}
Disclosure: This page may contain affliate links, meaning when you click the links and make a purchase, we receive a commission.
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....
1) what is the difference between an inner class and a sub-class.
An Inner class is a class which is nested within another class. An Inner class has access rights for the class which is nesting it and it can access all variables and methods defined in the outer class.
A sub-class is a class which inherits from another class called super class. Sub-class can access all public and protected methods and fields of its super class.
👉 Free PDF Download: Java Interview Interview Questions & Answers >>
In Java, access specifiers are the keywords used before a class name which defines the access scope. The types of access specifiers for classes are:
1) Public: Class,Method,Field is accessible from anywhere.
2) Protected: Method,Field can be accessed from the same class to which they belong or from the sub-classes, and from the class of same package, but not from outside.
3) Default: Method,Field,class can be accessed only from the same package and not from outside of it’s native package.
When there is a requirement to share a method or a variable between multiple objects of a class instead of creating separate copies for each object, we use static keyword to make a method or variable shared for all objects.
Encapsulation is a concept in Object Oriented Programming for combining properties and methods in a single unit.
Encapsulation helps programmers to follow a modular approach for software development as each object has its own set of methods and variables and serves its functions independent of other objects. Encapsulation also serves data hiding purpose.
A singleton class in java can have only one instance and hence all its methods and variables belong to just one instance. Singleton class concept is useful for the situations when there is a need to limit the number of objects for a class.
The best example of singleton usage scenario is when there is a limit of having only one connection to a database due to some driver limitations or because of any licensing issues.
Looping is used in programming to execute a statement or a block of statement repeatedly. There are three types of loops in Java :
1) For Loops
For loops are used in java to execute statements repeatedly for a given number of times. For loops are used when number of times to execute the statements is known to programmer.
2) While Loops
While loop is used when certain statements need to be executed repeatedly until a condition is fulfilled. In while loops, condition is checked first before execution of statements.
3) Do While Loops
An infinite loop runs without any condition and runs infinitely. An infinite loop can be broken by defining any breaking logic in the body of the statement blocks.
Infinite loop is declared as follows:
break and continue are two important keywords used in Loops. When a break keyword is used in a loop, loop is broken instantly while when continue keyword is used, current iteration is broken and loop continues with next iteration.
In below example, Loop is broken when counter reaches 4.
In the below example when counter reaches 4, loop jumps to next iteration and any statements after the continue keyword are skipped for current iteration.
In java, float takes 4 bytes in memory while Double takes 8 bytes in memory. Float is single precision floating point decimal number while Double is double precision decimal number.
In java, a constant is declared using the keyword Final. Value can be assigned only once and after assignment, value of a constant can’t be changed.
In below example, a constant with the name const_val is declared and assigned avalue:
Private Final int const_val=100
When a method is declared as final, it can NOT be overridden by the subclasses. This method are faster than any other method, because they are resolved at complied time.
When a class is declares as final, it cannot be subclassed. Example String, Integer and other wrapper classes.
Ternary operator , also called conditional operator is used to decide which value to assign to a variable based on a Boolean value evaluation. It’s denoted as ?
In the below example, if rank is 1, status is assigned a value of “Done” else “Pending”.
In a switch statement , default case is executed when no other switch condition matches. Default case is an optional case .It can be declared only once all other switch cases have been coded.
In the below example, when score is not 1 or 2, default case is used.
java.lang.object
In java, main() method can’t return any data and hence, it’s always declared with a void return type.
In Java, package is a collection of classes and interfaces which are bundled together as they are related to each other. Use of packages helps developers to modularize the code and group the code for proper re-use. Once code has been packaged in Packages, it can be imported in other classes and used.
Yes we can create an abstract class by using abstract keyword before class name even if it doesn’t have any abstract method. However, if a class has even one abstract method, it must be declared as abstract otherwise it will give an error.
The primary difference between an abstract class and interface is that an interface can only possess declaration of public static methods with no concrete implementation while an abstract class can have members with any access specifiers (public, private etc) with or without concrete implementation.
Another key difference in the use of abstract classes and interfaces is that a class which implements an interface must implement all the methods of the interface while a class which inherits from an abstract class doesn’t require implementation of all the methods of its super class.
Interfaces are slower in performance as compared to abstract classes as extra indirections are required for interfaces. Another key factor for developers to take into consideration is that any class can extend only one abstract class while a class can implement many interfaces.
Use of interfaces also puts an extra burden on the developers as any time an interface is implemented in a class; developer is forced to implement each and every method of interface.
In java, when a package is imported, its sub-packages aren’t imported and developer needs to import them separately if required.
For example, if a developer imports a package university.*, all classes in the package named university are loaded but no classes from the sub-package are loaded. To load the classes from its sub-package (say department), developer has to import it explicitly as follows:
Import university.department.*
In java, main method must be public static in order to run any application correctly. If main method is declared as private, developer won’t get any compilation error however, it will not get executed and will give a runtime error.
In java, we can pass argument to a function only by value and not by reference.
In java, to convert an object into byte stream by serialization, an interface with the name Serializable is implemented by the class. All objects of a class implementing serializable interface get serialized and their state is saved in byte stream.
Serialization is used when data needs to be transmitted over the network. Using serialization, object’s state is saved and converted into byte stream .The byte stream is transferred over the network and the object is re-created at destination.
Try block needs to be followed by either Catch block or Finally block or both. Any exception thrown from try block needs to be either caught in the catch block or else any specific tasks to be performed before code abortion are put in the Finally block.
26) is there any way to skip finally block of exception even if some exception occurs in the exception block.
If an exception is raised in Try block, control passes to catch block if it exists otherwise to finally block. Finally block is always executed when an exception occurs and the only way to avoid execution of any statements in Finally block is by aborting the code forcibly by writing following line of code at the end of try block:
The constructor of a class is invoked every time an object is created with new keyword.
For example, in the following class two objects are created using new keyword and hence, constructor is invoked two times.
29) can we override static methods of a class.
We cannot override static methods. Static methods belong to a class and not to individual objects and are resolved at the time of compilation (not at runtime).Even if we try to override static method, we will not get an complitaion error,nor the impact of overriding when running the code.
Ans : Output will be:
Displaying from subClass
Printing from superclass
String is not a primitive data type in java. When a string is created in java, it’s actually an object of Java.Lang.String class that gets created. After creation of this string object, all built-in methods of String class can be used on the string object.
In the above example, two objects of Java.Lang.String class are created. s1 and s3 are references to same object.
In java, string objects are called immutable as once value has been assigned to a string, it can’t be changed and if changed, a new object is created.
In below example, reference str refers to a string object having value “Value one”.
When a new value is assigned to it, a new String object gets created and the reference is moved to the new object.
An array groups data of same primitive type and is static in nature while vectors are dynamic in nature and can hold data of different data types.
Multi threading is a programming concept to run multiple tasks in a concurrent manner within a single program. Threads share same process stack and running in parallel. It helps in performance improvement of any program.
Runnable interface is used in java for implementing multi threaded applications. Java.Lang.Runnable interface is implemented by a class to support multi threading.
Multi threaded applications can be developed in Java by using any of the following two methodologies:
1) By using Java.Lang.Runnable Interface. Classes implement this interface to enable multi threading. There is a Run() method in this interface which is implemented.
2) By writing a class that extend Java.Lang.Thread class.
Since StringBuffers are dynamic in nature and we can change the values of StringBuffer objects unlike String which is immutable, it’s always a good choice to use StringBuffer when data is being changed too much. If we use String in such a case, for every data change a new String object will be created which will be an extra overhead.
Break is used after each case (except the last one) in a switch so that code breaks after the valid case and doesn’t flow in the proceeding cases too.
If break isn’t used after each case, all cases after the valid case also get executed resulting in wrong results.
In java, when an object is not referenced any more, garbage collection takes place and the object is destroyed automatically. For automatic garbage collection java calls either System.gc() method or Runtime.gc() method.
If we want to execute any statements before even creation of objects at load time of class, we can use a static block of code in the class. Any statements inside this static block of code will get executed once at the time of loading the class even before creation of objects in the main method.
If there is a hierarchy of inheritance used, a class can be a super class for another class and a sub-class for another one at the same time.
In the example below, continent class is sub-class of world class and it’s super class of country class.
Even if no explicit constructor is defined in a java class, objects get created successfully as a default constructor is implicitly used for object creation. This constructor has no parameters.
In multi-threading, access to the resources which are shared among multiple threads can be controlled by using the concept of synchronization. Using synchronized keyword , we can ensure that only one thread can use shared resource at a time and others can get control of the resource only once it has become free from the other one using it.
Constructor is called automatically when we create an object using new keyword. It’s called only once for an object at the time of object creation and hence, we can’t invoke the constructor again for an object after its creation.
Private members of a class aren’t accessible outside the scope of that class and any other class even in the same package can’t access them.
We can define two methods in a class with the same name but with different number/type of parameters. Which method is to get invoked will depend upon the parameters passed.
For example in the class below we have two print methods with same name but different parameters. Depending upon the parameters, appropriate one will be called:
We can use the concept of cloning to create copy of an object. Using clone, we create copies with the actual state of an object.
Clone() is a method of Cloneable interface and hence, Cloneable interface needs to be implemented for making object copies.
Key benefit of using inheritance is reusability of code as inheritance enables sub-classes to reuse the code of its super class. Polymorphism (Extensibility) is another great benefit which allow new functionality to be introduced without effecting existing derived classes.
Default access specifier for variables and method is package protected i.e variables and class is available to any other class but in the same package, not outside the package.
There are no pointers in Java. So we can’t use concept of pointers in Java.
If we want a class not to be extended further by any class, we can use the keyword Final with the class name.
In the following example, Stone class is Final and can’t be extend
When a method or a variable is declared with Protected access specifier, it becomes accessible in the same class, any other class of the same package as well as a sub-class.
Modifier | Class | Package | Subclass | World |
---|---|---|---|---|
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
no modifier | Y | Y | N | N |
private | Y | N | N | N |
Stack and Queue both are used as placeholder for a collection of data. The primary difference between a stack and a queue is that stack is based on Last in First out (LIFO) principle while a queue is based on FIFO (First In First Out) principle.
If we want certain variables of a class not to be serialized, we can use the keyword transient while declaring them. For example, the variable trans_var below is a transient variable and can’t be serialized:
Primitive data types like int can be handled as objects by the use of their respective wrapper classes. For example, Integer is a wrapper class for primitive data type int. We can apply different methods to a wrapper class, just like any other object.
Checked exceptions can be caught at the time of program compilation. Checked exceptions must be handled by using try catch block in the code in order to successfully compile the code.
A thread in Java can be in either of the following states:
Java provides a default no argument constructor if no explicit constructor is defined in a Java class. But if an explicit constructor has been defined, default constructor can’t be invoked and developer can use only those constructors which are defined in the class.
The basic condition of method overriding is that method name, arguments as well as return type must be exactly same as is that of the method being overridden. Hence using a different return type doesn’t override a method.
In this case postfix ++ operator is used which first returns the value and then increments. Hence it’s output will be 4.
main method is an entry point of Java class and is required for execution of the program however; a class gets compiled successfully even if it doesn’t have a main method. It can’t be run though.
Non-Static methods are owned by objects of a class and have object level scope and in order to call the non-Static methods from a static block (like from a static main method), an object of the class needs to be created first. Then using object reference, these methods can be invoked.
Java programs can be executed in a machine only once following two environment variables have been properly set:
In Java, if a variable is used in a code without prior initialization by a valid value, program doesn’t compile and gives an error as no default value is assigned to variables in Java.
In Java, a class can be derived from only one class and not from multiple classes. Multiple inheritances is not supported by Java.
Constructor in Java must have same name as the class name and if the name is different, it doesn’t act as a constructor and compiler thinks of it as a normal method.
Round(3.7) returns 4 and Ceil(3.7) returns 4.
In Java, there is not goto keyword and java doesn’t support this feature of going to a particular labeled line.
In java, a thread which is in dead state can’t be started again. There is no way to restart a dead thread.
Ans: The above class declaration is incorrect as an abstract class can’t be declared as Final.
JDK is development Kit of Java and is required for development only and to run a Java program on a machine, JDK isn’t required. Only JRE is required.
In Java, equals() method is used to compare the contents of two string objects and returns true if the two have same value while == operator compares the references of two string objects.
In the following example, equals() returns true as the two string objects have same values. However == operator returns false as both string objects are referencing to different objects:
Yes, we can do this by use of native methods. In case of native method based development, we define public static methods in our Java class without its implementation and then implementation is done in another language like C separately.
In Java, there are no destructors defined in the class as there is no need to do so. Java has its own garbage collection mechanism which does the job automatically by destroying the objects when no longer referenced.
75) can a variable be local and static at the same time.
No a variable can’t be static as well as local at the same time. Defining a local variable as static gives compilation error.
Static methods can’t be overridden in any class while any methods in an interface are by default abstract and are supposed to be implemented in the classes being implementing the interface. So it makes no sense to have static methods in an interface in Java.
No, we can’t change the value of any variable of an interface in the implementing class as all variables defined in the interface are by default public, static and Final and final variables are like constants which can’t be changed later.
Even though automatic garbage collection is provided by Java, it doesn’t ensure that a Java program will not go out of memory as there is a possibility that creation of Java objects is being done at a faster pace compared to garbage collection resulting in filling of all the available memory resources.
So, garbage collection helps in reducing the chances of a program going out of memory but it doesn’t ensure that.
No, Java class main method can have only void return type for the program to get successfully executed.
Nonetheless , if you absolutely must return a value to at the completion of main method , you can use System.exit(int status)
Once an object has been destroyed by garbage collector, it no longer exists on the heap and it can’t be accessed again. There is no way to reference it again.
Run() is a method of Runnable interface that must be implemented by all threads.
Ans: This can be implemented by use of the concept of synchronization. Database related code can be placed in a method which hs synchronized keyword so that only one thread can access it at a time.
In order to throw an exception in a block of code manually, throw keyword is used. Then this exception is caught and handled in the catch block.
If we declare the constructor of a class as private, it will not be accessible by any other class and hence, no other class will be able to instantiate it and formation of its object will be limited to itself only.
In java, each object when created gets a memory space from a heap. When an object is destroyed by a garbage collector, the space allocated to it from the heap is re-allocated to the heap and becomes available for any new objects.
In java, there is no way to find out the exact size of an object on the heap.
Class A: Three methods, four variables, no object
Class B: Five methods, three variables, no object
Memory isn’t allocated before creation of objects. Since for both classes, there are no objects created so no memory is allocated on heap for any class.
If an exception is not handled in a program using try catch blocks, program gets aborted and no statement executes after the statement which caused exception throwing.
If a class has multiple constructors, it’s possible to call one constructor from the body of another one using this() .
An anonymous class is a class defined without any name in a single line of code using new keyword.
For example, in below code we have defined an anonymous class in one line of code:
Arrays are static and once we have specified its size, we can’t change it. If we want to use such collections where we may require a change of size (no of items), we should prefer vector over array.
If there is main method in more than one classes in a java application, it won’t cause any issue as entry point for any application will be a specific class and code will start from the main method of that particular class only.
The best way to persist data for future use is to use the concept of serialization.
In Java, if we define a new class inside a particular block, it’s called a local class. Such a class has local scope and isn’t usable outside the block where its defined.
Although String and StringBuffer both represent String objects, we can’t compare them with each other and if we try to compare them, we get an error.
Java provides a Collection API which provides many useful methods which can be applied on a set of objects. Some of the important classes provided by Collection API include ArrayList, HashMap, TreeSet and TreeMap.
No, we can neither cast any other primitive type to Boolean data type nor can cast Boolean data type to any other primitive data type.
The basic requirement of method overriding in Java is that the overridden method should have same name, and parameters.But a method can be overridden with a different return type as long as the new return type extends the original.
For example , method is returning a reference type.
In Java, Java.lang.Throwable is the super class of all exception classes and all exception classes are derived from this base class.
In case of inheritance, when a new object of a derived class is created, first the constructor of the super class is invoked and then the constructor of the derived class is invoked.
Prep Up For your Job Interview!!! Go through Java Tutorial to be better prepared.
This detailed Java Mock Test Quiz will help you to clear the doubts about Java interview questions and will also help you to crack the interview.
These Java and Java 8 interview questions will also help in your viva(orals)
Company interview, technical interview, web interview, php interview, .net interview, java interview, database interview.
|
IMAGES
COMMENTS
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.
OOPs Interview Questions and Answers; Java Exercises; ... 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 ... It is a general perception that the approach using loops is treated as naive approach to solve a problem statement
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.
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
Consider that, for a given number N, if there is a prime number M between 2 to √N (square root of N) that evenly divides it, then N is not a prime number. 5. Write a Java program to print a Fibonacci sequence using recursion. A Fibonacci sequence is one in which each number is the sum of the two previous numbers.
Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.
Explore the Java coding exercises for practicing with commands below. First, read the conditions, scroll down to the Solution box, and type your solution. Then, click Verify (above the Conditions box) to check the correctness of your program. Exercise 1 Exercise 2 Exercise 3. Start task.
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. ... Multiple Choice Question: Easy: CodeChef Learn Problem Solving: 287: Multiple Choice Question: Easy: Learning SQL: 339: Multiple Choice Question: Easy: Parking Charges: 416: 6. Conditional ...
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 ...
We have gathered a variety of Java exercises (with answers) for each Java Chapter. Try to solve an exercise by editing some code, or show the answer to see what you've done wrong. Count Your Score. You will get 1 point for each correct answer. Your score and total score will always be displayed.
Highlights. Binary Tree problems are common at Google, Amazon and Facebook coding interviews.; Sharpen your lambda and streams skills with Java 8 coding practice problems.; Check our Berlin Clock solution, a commonly used code exercise.; We have videos too! Check out the FizzBuzz solution, a problem widely used on phone screenings.
Two important properties of a Java object are behavior and state. An object is created as soon as the JVM comes across the new keyword. 17. Define classes in Java. A class is a collection of objects of similar data types. Classes are user-defined data types and behave like built-in types of a programming language.
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 ...
Write a Java program to create a class called "Book" with attributes for title, author, and ISBN, and methods to add and remove books from a collection. Click me to see the solution. 6. Write a Java program to create a class called "Employee" with a name, job title, and salary attributes, and methods to calculate and update salary.
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 ...
Write a Java program to test if an array of integers contains an element 10 next to 10 or an element 20 next to 20, but not both. Click me to see the solution. 94. Write a Java program to rearrange all the elements of a given array of integers so that all the odd numbers come before all the even numbers. Click me to see the solution. 95.
Basic Core Java Interview Questions: Q1. What is the difference between an Inner Class and a Sub-Class? Ans: An Inner class is a class which is nested within another class. An Inner class has access rights for the class which is nesting it and it can access all variables and methods defined in the outer class.
There is the list of 300 core Java interview questions. If there is any core Java interview question that has been asked to you, kindly post it in the ask question section. We assure that you will get here the 90% frequently asked interview questions and answers. The answers to the Core Java interview questions are short and to the point.
Here's a list of additional java interview questions that hiring managers may ask you: 41. Write a program to sort a sequence of numbers in ascending order. 42. Using Java 8 date-time library in CLASSPATH (package private) file, write a program that shows how you can add time to any time with respect to midnight on Jan. 1, 2000.
Java Conditional Statement Exercises [32 exercises with solution] [ An editor is available at the bottom of the page to write and execute the scripts. Go to the editor] 1. Write a Java program to get a number from the user and print whether it is positive or negative. Test Data Input number: 35 Expected Output : Number is positive Click me to ...
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.
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.
The #1 tech hiring platform. SCREENINGINTERVIEWING. CodinGame is a challenge-based training platform for programmers where you can play with the hottest programming topics. Solve games, code AI bots, learn from your peers, have fun.