Technical Java Interview Questions And Answers PdfBy Grandiphytua1950 In and pdf 01.05.2021 at 08:08 5 min read
File Name: technical java interview questions and answers .zip
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.
- Top 130+ Java Interview Questions & Answers 2021
- Java interview questions for 2 years experience
- Top 1000+ Java Interview Questions and Answers Pdf - 1
Top 130+ Java Interview Questions & Answers 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.
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. 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.
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. This is made far easier with Map. When we remove keys from the key set, they are also removed from the backing map:.
Note, it is important to consult the documentation of the backing collection to see which modifications will successfully write through. In the example above, map. What is reflection? Give an example of functionality that can only be implemented using reflection.
Java interview questions for 2 years experience
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. Java is the high-level, object-oriented , robust, secure programming language, platform-independent, high performance, Multithreaded, and portable programming language. It was developed by James Gosling in June Java Virtual Machine is a virtual machine that enables the computer to run the Java program.
Top 1000+ Java Interview Questions and Answers Pdf - 1
Download PDF We have compiled the most frequently asked Java Interview Questions and Answers that will help you prepare for the Basic Java interview questions that an interviewer might ask you during your interview. In this list of Basic Java interview questions, we have covered all commonly asked basic and advanced Core Java interview questions with detailed answers to help you clear the job interview. The following list contains important Core Java interview questions for freshers as well as Java interview questions and answers for experienced programmers to help them prepare for the interview. This detailed guide of interview questions for Java Programming will help you to crack your Job interview easily.
Answer- The two paradigms for Object Oriented programming are as follows Process oriented It can be thought of as code acting on data. Example is C language 2. Object oriented It can be thought of as data controlling access to code. Example is Java.
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.
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. What is a class in Java?
Core Java - OOPs Concepts: Initial OOPs Interview Questions
I was getting a lot of emails and comments to create java interview questions and answers PDF eBook. Below image shows the cover page of this eBook. Just subscribe to my newsletter and you will get this eBook first thing in the email. So go ahead, subscribe from any of the forms on the website and get this eBook too. Can you please send me the pdf at garun1mishra gmail. I need a core java and adavanced java interview Questions and answers.
Hola. Тишина. Наверное, Меган, подумал. У нее оставалось целых пять часов до рейса, и она сказала, что попытается отмыть руку. - Меган? - позвал он и постучал .
- Человек умирал, и у него было одно желание.
Я же сказала вам, что ревела навзрыд, опоздав на самолет. Он перевел взгляд на слова, нацарапанные на ее руке. Она смутилась. - Боже, вы, кажется, сумели прочесть.
Вот он - истинный Стратмор. Он задумал способствовать распространению алгоритма, который АНБ с легкостью взломает. - Полный и всеобщий доступ, - объяснял Стратмор. - Цифровая крепость сразу же станет всеобщим стандартом шифрования. - Сразу же? - усомнилась Сьюзан.
Рассказывай. Немедленно. Но Дэвид знал, что никогда ей этого не откроет. Секрет выражения без воска был ему слишком дорог.
Хорошо. Давайте попробуем. - Он потянулся к клавиатуре. - Мистер Беккер, пожалуйста, продиктуйте надпись.
Я не сказал ему про спутницу. - Взмахом руки Клушар величественно отверг вопрос Беккера. - Они не преступницы - глупо было бы искать их, как обычных жуликов. Беккер все еще не мог прийти в себя от всего, что услышал. - Может, там был кто-нибудь .
С тех пор их отношения развивались с быстротой скольжения по склону горы. ГЛАВА 4 Потайная дверь издала сигнал, выведя Сьюзан из состояния печальной задумчивости. Дверь повернулась до положения полного открытия. Через пять секунд она вновь закроется, совершив вокруг своей оси поворот на триста шестьдесят градусов. Сьюзан собралась с мыслями и шагнула в дверной проем.
Лицо мужчины из мертвенно-бледного стало красным.
И уже утром мы сможем поехать. В нашем распоряжении будет целых два дня. - Но я уже забронировала номер, обиженно сказала Сьюзан. - Нашу старую комнату в Стоун-Мэнор.
Их отношения развивались медленно и романтично: встречи украдкой, если позволяли дела, долгие прогулки по университетскому городку, чашечка капуччино у Мерлутти поздно вечером, иногда лекции и концерты. Сьюзан вдруг поняла, что стала смеяться гораздо чаще, чем раньше. Казалось, не было на свете ничего, что Дэвид не мог бы обратить в шутку.
Кто он. - Понятия не имею. - Похож на китайца. Японец, подумал Беккер.