JavaRush /Java Blog /Random EN /java core. Questions for the interview, part 3
Vadim625
Level 27

java core. Questions for the interview, part 3

Published in the Random EN group
In the previous two articles, we discussed some of the important questions you are most often asked in job interviews. It is time to move on and consider the rest of the questions.
java core.  Questions for the interview, part 3 - 1

Deep copy and shallow copy

An exact copy of the original is its clone. In Java, this means the ability to create an object with the same structure as the original object. The method clone()provides this functionality. Shallow copying copies as little information as possible. By default, cloning in Java is shallow, i.e. Object classdoes not know about the structure of the class it is copying. When cloned, the JVM does things like this:
  1. If the class has only members of primitive types, then a completely new copy of the object will be created and a reference to that object will be returned.
  2. If the class contains not only members of primitive types, but also any other class type, then references to objects of these classes are copied. Therefore, both objects will have the same references.
Deep copying duplicates everything. Deep copying is two collections, one of which duplicates all the elements of the original collection. We want to make a copy in which making changes to any element of the copy will not affect the original collection. Deep cloning requires the following rules:
  1. There is no need to copy the primitive data separately;
  2. All member classes in the original class must support cloning. For each class member, must be called super.clone()when overriding a method clone();
  3. If any member of the class does not support cloning, then in the clone method you need to create a new instance of this class and copy each of its members with all the attributes into the new class object, one at a time.
Learn more about cloning here

What is sync? Object-level lock vs. class-level lock?

Synchronization refers to multithreading. A synchronized block of code can only be executed by one thread at a time. Java allows you to process multiple threads at the same time. This can result in two or more threads wanting to access the same field. Synchronization avoids memory errors that occur when memory resources are misused. When a method is declared synchronized, a thread holds its monitor. If another thread tries to access the synchronized method at this time, then the thread blocks and waits for the monitor to become free. Synchronization in Java is done with the special synchronized keyword.. You can mark individual blocks or methods in your class this way. The synchronized keyword cannot be used with class variables or attributes. Object-level locking is a mechanism when you want to synchronize a non-static method or a non-static block of code in such a way that only one thread can execute the block of code in a given class instance. This should always be done to make an instance of the class thread-safe. Class Level Lockingprevents multiple threads from entering a synchronized block for all available class instances. For example, if there are 100 DemoClass instances, then only 1 thread will be able to execute demoMethod() using one of the variables at a given time. This should always be done to ensure static thread safety. Learn more about sync here.

What's the difference between sleep() and wait()?

Sleep()is a method that is used to delay the process for a few seconds. In the case of wait(), the thread is waiting until we call the notify()or method notifyAll(). The main difference is that wait()it releases the monitor lock while it sleep()does not release the lock. Wait()used for multi-threaded applications, sleep()used simply to pause the execution of a thread. Thread.sleep()puts the current thread in the "Not Runnable" state for a specified amount of time. The thread saves the state of the monitor as it was before this method was called. If another thread calls t.interrupt(), the thread that "fell asleep" will wake up. note thatsleep()is a static method, which means that it always affects the current thread (the one executing the method sleep()). A common mistake is to call t.sleep()where tis another thread; even when the current thread that called the method sleep()is not ta thread. Object.wait()sends the current thread into the "Not Runnable" state for a while, just like sleep(), but with some nuance. Wait()called on the object, not on the thread; we call this object “lock object”. Before calling lock.wait(), the current thread must be synchronized with "lock object";wait()then releases that lock, and adds the thread to the ”wait list” associated with that lock. Later, another thread can synchronize to the same lock object and call the lock.notify(). This method will "wake up" the original thread, which is still waiting. In principle, wait()/ notify()can be compared to sleep()/ interrupt(), only the active thread does not need a direct pointer to the sleeping thread, it only needs to know the shared lock object. Read the detailed difference here.

Is it possible to assign null to this of a reference variable?

No you can not. In Java, the left side of an assignment statement must be a variable. "This" is a special keyword that always gives the current instance of the class. It's not just any variable. Likewise, null cannot be assigned to a variable using the "super" keyword or any other similar keyword.

What's the difference between && and &?

&- bitwise and &&- logically.
  1. &evaluates both sides of the operation;
  2. &&evaluates the left side of the operation. If it is true, it continues to evaluate the right side.
Look here for a deeper understanding.

How to override equals() and hachCode() methods?

hashCode()and equals()methods are defined in the class Object, which is the parent class for Java objects. For this reason, all Java objects inherit the default implementation for methods. The method hashCode()is used to get a unique integer for a given object. This integer is used to determine the location of the object when that object needs to be saved, for example to HashTable. By default, hashCode()returns integera representation of the address of the memory location where the object is stored. The method equls(), as its name implies, is used to simply check if two objects are equal. The default implementation checks object references for equality. The following are important guidelines for reloading these methods:
  1. Always use the same object attributes when generating hashCode()and equals();
  2. Symmetry. Those. if for any objects xand y x.equals(y)returns true, then it y.equals(x)should return true;
  3. Reflexivity. For any object, x x.equals(x)must return true;
  4. Constancy. For any objects, xand y x.equals(y)returns the same if the information used in the comparisons does not change;
  5. Transitivity. For any objects x, yand z, if x.equals(y)it returns true and y.equals(z)returns true, then it x.equals(z)must return true;
  6. Whenever a method is called on the same object during application execution, it must return the same number, as long as the information used does not change. hashCodemay return different values ​​for identical objects in different application instances;
  7. If two objects are equal, according to equals, then they hashCodemust return the same value;
  8. The return requirement is optional. Two unequal objects can return the same hashCode. However, to improve performance, it's better to have different objects return different codes.
Read interesting facts about these methods here.

Tell me about access modifiers

Java classes, fields, constructors, and methods can have one of four different access modifiers: private If a method or variable is marked private , then only code within that class can access the variable, or call the method. Code inside subclasses cannot access a variable or method, just as it cannot access it from any other class. The private access modifier is most often used for constructors, methods, and variables. default access modifier defaultdeclared if the modifier is not specified at all. This modifier means that access to the fields, constructors and methods of this class can be obtained by code within the class itself, code within classes in the same package. Subclasses cannot access superclass member methods and variables if they are declared as default unless the subclass is in the same package as the superclass. The protected modifier works in the same way as default , except that subclasses can also access the protected methods and variables of the superclass. This statement is true even if the subclass is not in the same package as the superclass. public Access Modifierpublic means that all code can access the class, its variables, constructors, or methods, no matter where the code is located. java core.  Questions for the interview, part 3 - 2

What is a garbage collector? Can we call it?

Garbage collection is an automatic memory management feature in many modern programming languages ​​such as Java and the languages ​​in NET.Framework. Languages ​​that use garbage collection often interpret garbage collection in a virtual machine such as the JVM. Garbage collection has two purposes: any unused memory must be freed, and memory must not be freed if the program is still using it. Can you run garbage collection manually? No, System.gc()it gives you as much access as possible. The best option is to call the method System.gc(), which will hint to the garbage collector about the need to run. There is no way to run it immediately since the garbage collector is non-deterministic. Also, according to the documentation,OutOfMemoryErrorwill not be thrown if the virtual machine was unable to free memory after a full garbage collection. Learn more about the garbage collector here.

What does the native keyword mean? Explain in detail

The native keyword is used to indicate that the method is not implemented in a Java file, but in another programming language. Native methods have been used in the past. In current versions of Java, this is needed less frequently. Currently, native methods are required when:
  1. You must call a library from Java that is written in another language.
  2. You need access to system or hardware resources that can only be accessed using another language (usually C). In fact, many system functions that interact with the real computer (such as disks or network data) can only be called by the native method.
The disadvantages of using libraries of native methods are also significant:
  1. JNI/JNA can destabilize the JVM, especially if you try to do something complex. If your native method does something wrong, there is a chance that the JVM will crash. Also, bad things can happen if your native method is called from multiple threads. And so on.
  2. A program with native code is harder to debug.
  3. Native code requires separate building of frameworks, which can create problems with porting to other platforms.

What is serialization?

In computer science, in the context of data storage and transmission, serialization is the process of translating a data structure or state of an object into a format that can be stored and restored later in another computing environment. After receiving a series of bits, they are recalculated according to the serialization format, and can be used to create a semantically identical clone of the original object. Java provides automatic serialization which requires an object to implement an interfacejava.io.Serializable. The interface implementation marks the class as "serializable". There are no serialization methods in the java.io.Serializable interface, but a serializable class can optionally define methods to be called as part of the serialization/deserialization process. When making changes to classes, you need to consider which ones will be compatible and not compatible with serialization. You can read the full instructions here. I will give the most important points: Incompatible changes:
  1. Removing a field;
  2. Move a class up or down the hierarchy;
  3. Changing a non-static field to static or non-transient to transient;
  4. Changing the declared primitive data type;
  5. Changing the method WriteObjector ReadObjectso that they no longer write or read fields by default;
  6. Change class Serializableto Externalizableor vice versa;
  7. Changing enum class to non-enum or vice versa;
  8. Delete Serializableor Externalizable;
  9. Adding writeReplaceor readResolvemethod to a class.
Compatible changes:
  1. Adding fields;
  2. Adding/removing classes;
  3. Adding methods WriteObject/ReadObject[methods defaultReadObjector defaultWriteObjectmust be called at the beginning];
  4. Removing methods WriteObject/ReadObject;
  5. Adding java.io.Serializable;
  6. Changing field access;
  7. Changing a static field to non-static or transient to non-transient .
Links to previous parts: Java Core. Interview Questions Part 1 Java Core. Interview Questions Part 2 Original Article Happy Learning!
Comments (1)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
21 August 2023
Well, thanks a lot for sharing content with detailed answers. Well, I have seen all 3 parts i.e. 1. https://javarush.com/en/groups/posts/en.765.java-core-questions-for-the-interview-part-1 2. https://javarush.com/en/groups/posts/en.764.java-core-questions-for-the-interview-part-2 3. https://javarush.com/en/groups/posts/en.780.java-core-questions-for-the-interview-part-3 Well, nowadays I am also preparing for Java Interview and I have also seen this post where author list almost 100 question with answer which help me a lot on exploring my learning. Thanks again for sharing it with us.