Basics Of Java Interview Questions And Answers Pdf
File Name: basics of java interview questions and answers .zip
What is the right data type to represent a price in Java? Answer: BigDecimal, if memory is not a concern and Performance, is not critical, otherwise double with predefined precision.
- Top 100 Java Interview Questions and Answers (Download PDF)
- Top 100 Java Interview Questions and Answers
- 100+ Java Interview Questions You Must Prepare In 2021
The main distinction between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated. Fail-safe iterators allow this; fail-fast iterators do not. Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified i.
Top 100 Java Interview Questions and Answers (Download PDF)
The main distinction between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated. Fail-safe iterators allow this; fail-fast iterators do not. Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified i. Fail-safe iterates operate on a cloned copy of the collection and therefore do not throw an exception if the collection is modified during iteration.
Which of them is most efficient for adding and removing elements from the list? Explain your answer, including any other alternatives you may be aware of. Of the three, LinkedList is generally going to give you the best performance. ArrayList and Vector each use an array to store the elements of the list.
As a result, when an element is inserted into or removed from the middle of the list, the elements that follow must all be shifted accordingly. Vector is synchronized, so if a thread-safe implementation is not needed, it is recommended to use ArrayList rather than Vector. LinkedList , on the other hand, is implemented using a doubly linked list. As a result, an inserting or removing an element only requires updating the links that immediately precede and follow the element being inserted or removed.
Why would it be more secure to store sensitive data such as a password, social security number, etc. In Java, Strings are immutable and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and exploit it.
In contrast, if you use a mutable object like a character array, for example, to store the value, you can set it to blank once you are done with it with confidence that it will no longer be retained in memory.
A single ThreadLocal instance can store different values for each thread independently. Each thread that accesses the get or set method of a ThreadLocal instance is accessing its own, independently initialized copy of the variable.
ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread e. The example below, from the ThreadLocal Javadoc , generates unique identifiers local to each thread.
Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection unless other references to these copies exist.
In Java, each thread has its own stack, including its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables into its own stack.
In all versions of Java, the volatile keyword guarantees global ordering on reads and writes to a variable. In Java 5 or later, volatile reads and writes establish a happens-before relationship, much like acquiring and releasing a mutex. Using volatile may be faster than a lock, but it will not work in some situations. The range of situations in which volatile is effective was expanded in Java 5; in particular, double-checked locking now works correctly.
The volatile keyword is also useful for bit types like long and double since they are written in two operations. Without the volatile keyword you risk stale or invalid values. One common example for using volatile is for a flag to terminate a thread.
By making the flag volatile, you can ensure that the thread that is checking its value will see that it has been set to true without even having to use a synchronized block.
For example:. Tail recursion is functionally equivalent to iteration. Since Java does not yet support tail call optimization, describe how to transform a simple tail recursive function into a loop and why one is typically preferred over the other. Here is an example of a typical recursive function, computing the arithmetic series 1, 2, 3…N.
Notice how the addition is performed after the function call. For each recursive step, we add another frame to the stack. Tail recursion occurs when the recursive call is in the tail position within its enclosing context - after the function calls itself, it performs no additional work. That is, once the base case is complete, the solution is apparent. Here you can see that a plays the role of the accumulator - instead of computing the sum on the way down the stack, we compute it on the way up, effectively making the return trip unnecessary, since it stores no additional state and performs no further computation.
Many functional languages natively support tail call optimization, however the JVM does not. In order to implement recursive functions in Java, we need to be aware of this limitation to avoid StackOverflowError s. In Java, iteration is almost universally preferred to recursion. How can you swap the values of two numeric variables without using any other variables?
You can swap two values a and b without using any other variables as follows:. This can be done using Thread. Classes may be loaded from the local file system, a remote file system, or even the web. When the JVM is started, three class loaders are used: 1. Extension Classloader: Loads jar files from folder. Is a finally block executed when an exception is thrown from a try block that does not have a catch block, and if so, when?
A finally block is executed even if an exception is thrown or propagated to the calling code block. When designing an abstract class, why should you avoid calling abstract methods inside its constructor? This is a problem of initialization order. The subclass constructor will not have had a chance to run yet and there is no way to force it to run it before the parent class.
Consider the following example class:. This seems like a good start for an abstract Widget: it allows subclasses to fill in width and height , and caches their initial values. However, look when you spec out a typical subclass implementation like so:.
This is because the this. What variance is imposed on generic type parameters? How much control does Java give you over this? So even though String extends i. Java does give you some control over this in the form of use-site variance. On individual methods, we can use? Consider a function with a callback parameter:. Note, however, that attempting to provide a callback that handles only Long a subtype of Number will rightly fail:.
Liberal application of use-site variance can prevent many of the unsafe casts that often appear in Java code and is crucial when designing interfaces used by multiple developers. A static initializer gives you the opportunity to run code during the initial loading of a class and it guarantees that this code will only run once and will finish running before your class can be accessed in any way.
They are useful for performing initialization of complex static objects or to register a type with a static registry, as JDBC drivers do. Suppose you want to create a static, immutable Map containing some feature flags. Within the same class, you can repeat this pattern of declaring a static field and immediately initializing it, since multiple static initializers are allowed. If one needs a Set , how do you choose between HashSet vs.
At first glance, HashSet is superior in almost every way: O 1 add , remove and contains , vs. O log N for TreeSet. However, TreeSet is indispensable when you wish to maintain order over the inserted elements or query for a range of elements within the set. Consider a Set of timestamped Event objects. They could be stored in a HashSet , with equals and hashCode based on that timestamp. This is efficient storage and permits looking up events by a specific timestamp, but how would you get all events that happened on any given day?
Generally speaking, TreeSet is a good choice when order matters and when reads are balanced against the increased cost of writes. Method references were introduced in Java 8 and allow constructors and methods static or otherwise to be used as lambdas. They allow one to discard the boilerplate of a lambda when the method reference matches an expected signature. For example, suppose we have a service that must be stopped by a shutdown hook. Before Java 8, we would have code like this:.
However, stop matches the signature of Runnable. For example, suppose we have a Person class and want just the lowercase names of a collection of people:. A complex lambda can also be pushed into a static or instance method and then used via a method reference instead. So we can see that method references are mainly used to improve code organization, clarity and terseness. Enums are essentially final classes with a fixed number of instances. They can implement interfaces but cannot extend another class.
This flexibility is useful in implementing the strategy pattern, for example, when the number of strategies is fixed. Consider an address book that records multiple methods of contact. We can represent these methods as an enum and attach fields, like the filename of the icon to display in the UI, and any corresponding behaviour, like how to initiate contact via that method:.
We can dispense with switch statements entirely by simply using instances of ContactMethod :. This is just the beginning of what can be done with enums.
Generally, the safety and flexibility of enums means they should be used in place of integer constants, and switch statements can be eliminated with liberal use of abstract methods. Give an example of when this property is useful. If a collection backs another, it means that changes in one are reflected in the other and vice-versa. For example, suppose we wanted to create a whitelist function that removes invalid keys from a Map.
Top 100 Java Interview Questions and Answers
In this post, we will see Java interview questions for 5 to 6 years experience. When you have 5 years of experience as java developer, you need to have a good understanding of collections , multithreading concepts. Here are some questions which are most asked for 5 years of experience java programmers. You might find some of the questions very easy but believe me most developers failed to answer these questions. What will be the output? Compile time error C. Runtime error.
Home page Contact Us. Net DWH New. Basic Java Interview Question and Answers. What is Java? Java is an object programming language that was designed to be portable across multiple platforms and operating systems.
100+ Java Interview Questions You Must Prepare In 2021
There is the list of 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. The answers to the Core Java interview questions are short and to the point. The core Java interview questions are categorized in Basics of Java interview questions, OOPs interview questions, String Handling interview questions, Multithreading interview questions, collection interview questions, JDBC interview questions, etc.
In this article, we have compiled the most frequently asked Java Interview Questions. These questions will give you an acquaintance with the type of questions that an interviewer might ask you during you interview for Java Programming. As a Fresher, you have either just attended an interview or planning to attend one soon. An Entry Level jobseeker looking to grow your career in software programming , you may be nervous about your upcoming interviews. All of us have those moments of panic where we blank out and might even forget what a thread is.
Java Interview Questions & Answers for Freshers
Беккер молча ждал выстрела, который должен оборвать его жизнь. ГЛАВА 89 Лучи утреннего солнца едва успели коснуться крыш Севильи и лабиринта узких улочек под. Колокола на башне Гиральда созывали людей на утреннюю мессу. Этой минуты ждали все жители города. Повсюду в старинных домах отворялись ворота, и люди целыми семьями выходили на улицы.
Она не клюнет на твою тактику разделяй и властвуй, - сказал Стратмор, подходя еще ближе. - Отпусти. - Чатрукьян был совсем мальчишка. Ради всего святого, зачем вы это сделали. Чтобы скрыть свою маленькую тайну.
Я хочу открыть этот проклятый файл и ознакомиться с созданной Танкадо программой. Сьюзан была столь же любопытна, как и ее шеф, но чутье подсказывало ей, что расшифровка алгоритма Цифровой крепости неразумна, какой бы интерес это ни представляло.