blog banner
 

 

1. What is Java Garbage Collection Process ? Advanatage of using JAVA automatic garbage collection ?

Garbage collection is the process of reclaiming the unused memory space and making it available for the future instances.

The Java virtual machine's heap stores all objects created by a running Java application. Objects are created by the new, newarray, anewarray, and multianewarray instructions, but never freed explicitly (using system.gc() mentod) by the code. Garbage collection is the process of automatically freeing objects that are no longer referenced by the program.

In Java destruction of object from memory is done automatically by the JVM. When there is no reference to an object, then that object is assumed to be no longer needed and the memory occupied by the object are released. This technique is called Garbage Collection. This is accomplished by the JVM.

So we can say that, Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection

  • It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
  • It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

 

2. Why Do we need JAVA garbage collection ?

The name "garbage collection" implies that objects no longer needed by the program are "garbage" and can be thrown away. A more accurate and up-to-date metaphor might be "memory recycling." When an object is no longer referenced by the program, the heap space it occupies can be recycled so that the space is made available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed.

In addition to freeing unreferenced objects, a garbage collector may also combat heap fragmentation. Heap fragmentation occurs through the course of normal program execution. New objects are allocated, and unreferenced objects are freed such that free portions of heap memory are left in between portions occupied by live objects. Requests to allocate new objects may have to be filled by extending the size of the heap even though there is enough total unused space in the existing heap. This will happen if there is not enough contiguous free heap space available into which the new object will fit. On a virtual memory system, the extra paging (or swapping) required to service an ever growing heap can degrade the performance of the executing program. On an embedded system with low memory, fragmentation could cause the virtual machine to "run out of memory" unnecessarily.

Garbage collection relieves you from the burden of freeing allocated memory. Knowing when to explicitly free allocated memory can be very tricky. Giving this job to the Java virtual machine has several advantages. First, it can make you more productive. When programming in non-garbage-collected languages you can spend many late hours (or days or weeks) chasing down an elusive memory problem. When programming in Java you can use that time more advantageously by getting ahead of schedule or simply going home to have a life.

A second advantage of garbage collection is that it helps ensure program integrity. Garbage collection is an important part of Java's security strategy. Java programmers are unable to accidentally (or purposely) crash the Java virtual machine by incorrectly freeing memory.
 

3. When does one object become eligible for the garbage collection ? How can an object be unreferenced?

There are many ways:

  • By nulling the reference
  • By assigning a reference to another
  • By annonymous object
  • By Isolating a Reference etc.

By nulling the reference

If we nullify the references to an object then there will be no reachable references the object looses its importance and it will be no longer needed thus becomes eligible for Garbage Collection.

Employee e=new Employee();
e=null;

By assigning a reference to another

To remove the reference to a particular object and making it eligible for Garbage Collection is to set the reference variable which currently refers to it to a new object. Thus, re-assigning the reference variable.

Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection

By annonymous object

An annonymous object is created in this way

new Employee();

By Isolating a Reference

This time we are not removing the references but just isolating them. Consider a case where a reference to an object is also used to refer to another reference to the same object. Now imagine that two such instances exist and that they refer to each other. If all other references to these two objects are removed, then even though each object still has a valid reference, there will be no way for any live thread to access either object. When the garbage collector runs, it will remove such objects.

Employee r2 = new Employee();

Employee r3= new Employee();
Employee r4= new Employee();
r2.r = r3;
r3.r = r4;
r4.r = r2;
r2 = null;
r3 = null;
r4 = null;
 

4. How does java garbage collection works ?

JAVA automatic garabage collection is done by JVM.

 

Eden Space:

When an instance is created, it is first stored in the eden space in young generation of heap memory area.

Survivor Space (S0 and S1):

As part of the minor garbage collection cycle, objects that are live (which is still referenced) are moved to survivor space S0 from eden space. Similarly the garbage collector scans S0 and moves the live instances to S1.
Instances that are not live (dereferenced) are marked for garbage collection. Depending on the garbage collector (there are four types of garbage collectors available and we will see about them in the next tutorial) chosen either the marked instances will be removed from memory on the go or the eviction process will be done in a separate process.

Old Generation / Tenured Generation:

Old or tenured generation is the second logical part of the heap memory. When the garbage collector does the minor GC cycle, instances that are still live in the S1 survivor space will be promoted to the old generation. Objects that are dereferenced in the S1 space is marked for eviction.

Major GC:

Old generation is the last phase in the instance life cycle with respect to the Java garbage collection process. Major GC is the garbage collection process that scans the old generation part of the heap memory. If instances are dereferenced, then they are marked for eviction and if not they just continue to stay in the old generation.

Memory Fragmentation:

Once the instances are deleted from the heap memory the location becomes empty and becomes available for future allocation of live instances. These empty spaces will be fragmented across the memory area. For quicker allocation of the instance it should be defragmented. Based on the choice of the garbage collector, the reclaimed memory area will either be compacted on the go or will be done in a separate pass of the GC.
 

5. Which objects are not cleared automatically by JVM ?

The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).

 

6. What is GC() method in JAVA ? How to do garbage collection in java explicitly ?

gc() method is used to call garbage collector explicitly. However gc() method does not guarantee that JVM will perform the garbage collection. It only request the JVM for garbage collection. This method is present in System and Runtime class of java.lang package.

public class TestGarbage1{

public static void main(String args[]){

TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc(); // Runtime.gc(); would do the same thing

}

}
 

7. What is finalize in JAVA ? Importance of finalize keyword in JAVA ?

It is defined in java.lang package under object class. The java.lang.Object.finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:

importance

The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).

Properties

  • finalize() method is defined in java.lang.Object class, therefore it is available to all the classes.
  • finalize() method is declare as proctected inside Object class.
  • finalize() method gets called only once by GC threads.

Sometime an object will need to perform some specific task before it is destroyed such as closing an open connection or releasing any resources held. To handle such situation finalize() method is used. finalize() method is called by garbage collection thread before collecting object. Its the last chance for any object to perform cleanup utility.
Signature of finalize() method

protected void finalize()
{
//finalize-code
}

8. what is the difference between final , finally and finalize in JAVA ?

final finally finalize
Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed. Finally is used to place important code, it will be executed whether exception is handled or not. Finalize is used to perform clean up processing just before object is garbage collected.
Final is a keyword. Finally is a block. Finalize is a method.

 

9. How can we achieve the feature of const variable of C programming in JAVA ?

In java a final variable does the same thing as const variable in C.
 

10. What are the difference between Class method and Instance method ?

Class method Instance method
Class methods are methods which are declared as static. The method can be called without creating an instance of the class Instance methods on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword.
Instance methods operate on specific instances of classes.
Class methods can only operate on class members and not on instance members as class methods are unaware of instance members. Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class.
Class methods are methods which are declared as static. The method can be called without creating an instance of the class. Instance methods are not declared as static.

 

11. How are this() and super() used with constructors?

  • Constructors use this to refer to another constructor in the same class with a different parameter list.
  • Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.

 

12. What is the difference between equals() and == ?

The == (double equals) returns true, if the variable reference points to the same object in memory. This is called “shallow comparison”.

The equals() method calls the user implemented equals() method, which compares the object attribute values. The equals() method provides “deep comparison” by checking if two objects are logically equal as opposed to the shallow comparison provided by the operator ==.

If equals() method does not exist in a user supplied class then the inherited Object class's equals() method will be called which evaluates if the references point to the same object in memory. In this case, the object.equals() works just like the "==" operator.
 

13. 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.
 

14. What is a singleton class? Give a practical example of its usage.

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. More on java singleton is described in part#7
 

16. How can you generate random numbers in Java?

Using Math.random() you can generate random numbers in the range 0.1 to 1.0
Using Random class in package java.util
 

17. What is data encapsulation and what’s its significance?

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.
 

18. What’s the base class in Java from which all classes are derived?

java.lang.object
 

19. Can main() method in Java can return any data?

In java, main() method can’t return any data and hence, it’s always declared with a void return type.

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.
 

20. Can we declare a class as Abstract without having any abstract method?

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.
 

21. What are the performance implications of Interfaces over abstract classes?

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.
 

22. Does Importing a package imports its sub-packages as well in Java?

Ans: 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.*
 

23. How an object is serialized in java?

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.
 

24. When we should use serialization?

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.
 

25. Is it compulsory for a Try Block to be followed by a Catch Block in Java for Exception handling?

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:

System.exit(0);

27. 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.
 

28. Is String a data type in java?

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.
 

29. Why Strings in Java are called as Immutable?

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”.

String str="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.

str="New Value";
 

30. What is an immutable object?

An immutable object is one that we cannot change once it is created. Steps involved in creation of an immutable object are :

- Make all of its data fields private.
- Methods which can perform changes in any of the data fields after the construction of object must be avoide.
 

31. What are the List interface and its main implementation?

The List helps in collections of objects. Lists may contain duplicate elements. The main implementations of the List interface are as follows :

ArrayList : Resizable-array implementation of the List interface.

Vector : Synchronized resizable-array implementation of the List.

LinkedList : Doubly-linked list implementation of the List interface. Better performance than the ArrayList implementation when elements are inserted or deleted timely.
 

32. Explain the user defined Exceptions.

User Defined Exceptions are exceptions defined by the user for specific purposed. This allows custom exceptions to be generated and caught in the same way as normal exceptions. While defining a User Defined Exception, we need to take care of the following aspects :

- It should be extend from Exception class.
- Use toString() method to display information about the exception.
 

33. When should I use abstract classes and when should I use interfaces?

Use Interface, when :

- Design changing frequently or when various implementations only share method signatures.
- We need some classes to use some methods which we do not want to be included in the class.

Use Abstract Class, when :

- Various implementations are of the same kind and use common behavior.
- Enabling with generalized form of abstraction and leave the implementation task with the inheriting subclass.
- Creating planned inheritance hierarchies.
 

34. What are the difference between throw and throws?

The difference between throw and throws are :

- Throw is used to trigger an exception where as throws is used in the declaration of exception.
- Without throws, checked exception cannot be handled where as checked exception can be propagated with throws.
- Throw is used inside the method where as throws is used with the method signature.
- Throw is followed by an instance but throws is followed by class.
 

35. 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.

Admin Team


0 Respond



Written
Exam Questions
BLOG Posts
For study materials
Job Walk-In
Updates across India
Interview round
Questions
Interview or procedure
Experiences
Files
For study materials
Please LIKE our page to Get regular JOB WALK-IN UPDATES across India and STUDY MATERIALS on facebook news feed.