[19 Feb 2020] Java Collection
[1] Vector vs ArrayList in Java
ArrayList and Vectors both implement the List interface and both use (dynamically resizable) arrays for its internal data structure, much like using an ordinary array.
Syntax:
ArrayList<T> al = new ArrayList<T>();
Vector<T> v = new Vector<T>();
Major Differences between ArrayList and Vector:
Synchronization : Vector is synchronized, which means only one thread at a time can access the code, while arrayList is not synchronized, which means multiple threads can work on arrayList at the same time. For example, if one thread is performing an add operation, then there can be another thread performing a remove operation in a multithreading environment.
If multiple threads access arrayList concurrently, then we must synchronize the block of the code which modifies the list structurally, or alternatively allow simple element modifications. Structural modification means addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification.
Performance: ArrayList is faster, since it is non-synchronized, while vector operations give slower performance since they are synchronized (thread-safe). If one thread works on a vector, it has acquired a lock on it, which forces any other thread wanting to work on it to have to wait until the lock is released.
Data Growth: ArrayList and Vector both grow and shrink dynamically to maintain optimal use of storage – but the way they resize is different. ArrayList increments 50% of the current array size if the number of elements exceeds its capacity, while vector increments 100% – essentially doubling the current array size.
Traversal: Vector can use both Enumeration and Iterator for traversing over elements of vector while ArrayList can only use Iterator for traversing.
Note: ArrayList is preferable when there is no specific requirement to use vector.
// Java Program to illustrate use of ArrayList
// and Vector in Java
import java.io.*;
import java.util.*;
class GFG
{
public static void main (String[] args)
{
// creating an ArrayList
ArrayList<String> al = new ArrayList<String>();
// adding object to arraylist
al.add("Practice.GeeksforGeeks.org");
al.add("quiz.GeeksforGeeks.org");
al.add("code.GeeksforGeeks.org");
al.add("contribute.GeeksforGeeks.org");
// traversing elements using Iterator'
System.out.println("ArrayList elements are:");
Iterator it = al.iterator();
while (it.hasNext())
System.out.println(it.next());
// creating Vector
Vector<String> v = new Vector<String>();
v.addElement("Practice");
v.addElement("quiz");
v.addElement("code");
// traversing elements using Enumeration
System.out.println("\nVector elements are:");
Enumeration e = v.elements();
while (e.hasMoreElements())
System.out.println(e.nextElement());
}
}
Output:
ArrayList elements are:
Practice.GeeksforGeeks.org
quiz.GeeksforGeeks.org
code.GeeksforGeeks.org
contribute.GeeksforGeeks.org
Vector elements are:
Practice
quiz
code
How to choose between ArrayList and Vector?
ArrayList is unsynchronized and not thread-safe, whereas Vectors are. Only one thread can call methods on a Vector at a time, which is a slight overhead, but helpful when safety is a concern. Therefore, in a single-threaded case, arrayList is the obvious choice, but where multithreading is concerned, vectors are often preferable.
If we don’t know how much data we are going to have, but know the rate at which it grows, Vector has an advantage, since we can set the increment value in vectors.
ArrayList is newer and faster. If we don’t have any explicit requirements for using either of them, we use ArrayList over vector.
Why Java doesn’t support multiple inheritance?
Java doesn’t support multiple inheritance in classes because of “Diamond Problem”. To know more about diamond problem with example, read Multiple Inheritance in Java.
However multiple inheritances are supported in interfaces. An interface can extend multiple interfaces because they just declare the methods and implementation will be present in the implementing class. So there is no issue of the diamond problem with interfaces.
What is the importance of main method in Java?
main() method is the entry point of any standalone java application. The syntax of main method is public static void main(String args[]).
Java main method is public and static so that Java runtime can access it without initializing the class. The input parameter is an array of String through which we can pass runtime arguments to the java program. Check this post to learn how to compile and run java program.
Can we overload main method?
Yes, we can have multiple methods with name “main” in a single class. However if we run the class, java runtime environment will look for main method with syntax as public static void main(String args[]).
What is Java Package and which package is imported by default?
Java package is the mechanism to organize the java classes by grouping them. The grouping logic can be based on functionality or modules based. A java class fully classified name contains package and class name. For example, java.lang.Object is the fully classified name of Object class that is part of java.lang package.
java.lang package is imported by default and we don’t need to import any class from this package explicitly.
What is finally and finalize in java?
finally block is used with try-catch to put the code that you want to get executed always, even if any exception is thrown by the try-catch block. finally block is mostly used to release resources created in the try block.
finalize() is a special method in Object class that we can override in our classes. This method gets called by the garbage collector when the object is getting garbage collected. This method is usually overridden to release system resources when the object is garbage collected.
What is the difference between abstract class and interface?
abstract keyword is used to create abstract class whereas interface is the keyword for interfaces.
Abstract classes can have method implementations whereas interfaces can’t.
A class can extend only one abstract class but it can implement multiple interfaces.
We can run an abstract class if it has main() method whereas we can’t run an interface.
Difference between Abstract Class and Interface
abstract keyword is used to create an abstract class and it can be used with methods also whereas interface keyword is used to create interface and it can’t be used with methods.
Subclasses use extends keyword to extend an abstract class and they need to provide implementation of all the declared methods in the abstract class unless the subclass is also an abstract class whereas subclasses use implements keyword to implement interfaces and should provide implementation for all the methods declared in the interface.
Abstract classes can have methods with implementation whereas interface provides absolute abstraction and can’t have any method implementations.
Abstract classes can have constructors but interfaces can’t have constructors.
Abstract class have all the features of a normal java class except that we can’t instantiate it. We can use abstract keyword to make a class abstract but interfaces are a completely different type and can have only public static final constants and method declarations.
Abstract classes methods can have access modifiers as public, private, protected, static but interface methods are implicitly public and abstract, we can’t use any other access modifiers with interface methods.
A subclass can extend only one abstract class but it can implement multiple interfaces.
Abstract classes can extend other class and implement interfaces but interface can only extend other interfaces.
We can run an abstract class if it has main() method but we can’t run an interface because they can’t have main method implementation.
Interfaces are used to define contract for the subclasses whereas abstract class also define contract but it can provide other methods implementations for subclasses to use.
Thats all for the difference between interface and abstract classes, now we can move on to know when should we use Interface over Abstract class and vice versa.
Interface or Abstract Class
Whether to chose between Interface or abstract class for providing contract for subclasses is a design decision and depends on many factors, lets see when Interfaces are best choice and when can we use abstract classes.
Java doesn’t support multiple class level inheritance, so every class can extend only one superclass. But a class can implement multiple interfaces. So most of the times Interfaces are a good choice for providing base for class hierarchy and contract. Also coding in terms of interfaces is one of the best practices for coding in java.
If there are a lot of methods in the contract, then abstract class is more useful because we can provide default implementation for some of the methods that are common for all the subclasses. Also if subclasses don’t need to implement particular method, they can avoid providing the implementation but in case of interface, the subclass will have to provide implementation for all the methods even though it’s of no use and implementation is just empty block.
If our base contract keeps on changing then interfaces can cause issues because we can’t declare additional methods to the interface without changing all the implementation classes, with abstract class we can provide the default implementation and only change the implementation classes that are actually going to use the new methods.
Use Abstract classes and Interface both
Actually most of the times, using Interfaces and abstract classes together is the best approach for designing a system, for example in JDK java.util.List is an interface that contains a lot of methods, so there is an abstract class java.util.AbstractList that provides skeletal implementation for all the methods of List interface so that any subclass can extend this class and implement only required methods.
We should always start with an interface as base and define methods that every subclasses should implement and then if there are some methods that only certain subclass should implement, we can extend the base interface and create a new interface with those methods. The subclasses will have option to chose between the base interface or the child interface to implement according to its requirements. If the number of methods grows a lot, its not a bad idea to provide a skeletal abstract class implementing the child interface and providing flexibility to the subclasses to chose between interface and abstract class.
Java Enum Example
Java enum keyword is used to create an enum type. Let’s have a look at the java enum example program.
package com.journaldev.enums;
public enum ThreadStates {
START,
RUNNING,
WAITING,
DEAD;
}
In above example, ThreadStates is the enum with fixed constants fields START, RUNNING, WAITING and DEAD.
What is the benefit of Composition over Inheritance?
One of the best practices of Java programming is to “favor composition over inheritance”. Some of the possible reasons are:
Any change in the superclass might affect subclass even though we might not be using the superclass methods. For example, if we have a method test() in the subclass and suddenly somebody introduces a method test() in the superclass, we will get compilation errors in the subclass. The composition will never face this issue because we are using only what methods we need.
Inheritance exposes all the superclass methods and variables to the client and if we have no control in designing superclass, it can lead to security holes. Composition allows us to provide restricted access to the methods and hence more secure.
We can get runtime binding in composition where inheritance binds the classes at compile time. So composition provides flexibility in the invocation of methods.
What is Classloader in Java?
Java Classloader is the program that loads byte code program into memory when we want to access any class. We can create our own classloader by extending ClassLoader class and overriding loadClass(String name) method. Learn more at java classloader.
What are different types of classloaders?
There are three types of built-in Class Loaders in Java:
Bootstrap Class Loader – It loads JDK internal classes, typically loads rt.jar and other core classes.
Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
System Class Loader – It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options.
What does super keyword do?
super keyword can be used to access super class method when you have overridden the method in the child class.
We can use super keyword to invoke superclass constructor in child class constructor but in this case, it should be the first statement in the constructor method.
public class SuperClass {
public SuperClass(){
}
public SuperClass(int i){}
public void test(){
System.out.println("super class test method");
}
}
Use of super keyword can be seen in below child class implementation.
package com.journaldev.access;
public class ChildClass extends SuperClass {
public ChildClass(String str){
//access super class constructor with super keyword
super();
//access child class method
test();
//use super to access super class method
super.test();
}
@Override
public void test(){
System.out.println("child class test method");
}
}
What is default constructor?
No argument constructor of a class is known as default constructor. When we don’t define any constructor for the class, java compiler automatically creates the default no-args constructor for the class. If there are other constructors defined, then compiler won’t create default constructor for us.
What is Garbage Collection?
Garbage Collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. In Java, process of deallocating memory is handled automatically by the garbage collector.
We can run the garbage collector with code Runtime.getRuntime().gc() or use utility method System.gc(). For a detailed analysis of Heap Memory and Garbage Collection, please read Java Garbage Collection.
What is Serialization and Deserialization?
We can convert a Java object to an Stream that is called Serialization. Once an object is converted to Stream, it can be saved to file or send over the network or used in socket connections.
The object should implement Serializable interface and we can use java.io.ObjectOutputStream to write object to file or to any OutputStream object. Read more at Java Serialization.
The process of converting stream data created through serialization to Object is called deserialization. Read more at Java Deserialization.
How to run a JAR file through command prompt?
We can run a jar file using java command but it requires Main-Class entry in jar manifest file. Main-Class is the entry point of the jar and used by java command to execute the class. Learn more at java jar file.
What is instanceof keyword?
We can use instanceof keyword to check if an object belongs to a class or not. We should avoid it’s usage as much as possible. Sample usage is:
public static void main(String args[]){
Object str = new String("abc");
if(str instanceof String){
System.out.println("String value:"+str);
}
if(str instanceof Integer){
System.out.println("Integer value:"+str);
}
}
Can we use String with switch case?
One of the Java 7 feature was improvement of switch case of allow Strings. So if you are using Java 7 or higher version, you can use String in switch-case statements. Read more at Java switch-case String example.
Java is Pass by Value or Pass by Reference?
This is a very confusing question, we know that object variables contain the reference to the Objects in heap space. When we invoke any method, a copy of these variables is passed and gets stored in the stack memory of the method. We can test any language whether it’s pass by reference or pass by value through a simple generic swap method, to learn more read Java is Pass by Value and Not Pass by Reference.
What is difference between Heap and Stack Memory?
Major difference between Heap and Stack memory are as follows:
Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
Memory management in the stack is done in a LIFO manner whereas it’s more complex in Heap memory because it’s used globally.
For a detailed explanation with a sample program, read Java Heap vs Stack Memory.
Java Compiler is stored in JDK, JRE or JVM?
The task of java compiler is to convert java program into bytecode, we have javac executable for that. So it must be stored in JDK, we don’t need it in JRE and JVM is just the specs.
What will be the output of following programs?
static method in class
package com.journaldev.util;
public class Test {
public static String toString(){
System.out.println("Test toString called");
return "";
}
public static void main(String args[]){
System.out.println(toString());
}
}
Answer: The code won’t compile because we can’t have an Object class method with static keyword. Note that Object class has toString() method. You will get a compile-time error as “This static method cannot hide the instance method from Object”. The reason is that static method belongs to the class and since every class base is Object, we can’t have the same method in the instance as well as in class. You won’t get this error if you change the method name from toString() to something else that is not present in superclass Object.
static method invocation
package com.journaldev.util;
public class Test {
public static String foo(){
System.out.println("Test foo called");
return "";
}
public static void main(String args[]){
Test obj = null;
System.out.println(obj.foo());
}
}
Answer: Well this is a strange situation. We all have seen NullPointerException when we invoke a method on the object that is NULL. But here this program will work and prints “Test foo called”.
The reason for this is the java compiler code optimization. When the java code is compiled to produced byte code, it figures out that foo() is a static method and should be called using class. So it changes the method call obj.foo() to Test.foo() and hence no NullPointerException.
ArrayList and Vectors both implement the List interface and both use (dynamically resizable) arrays for its internal data structure, much like using an ordinary array.
Syntax:
ArrayList<T> al = new ArrayList<T>();
Vector<T> v = new Vector<T>();
Major Differences between ArrayList and Vector:
Synchronization : Vector is synchronized, which means only one thread at a time can access the code, while arrayList is not synchronized, which means multiple threads can work on arrayList at the same time. For example, if one thread is performing an add operation, then there can be another thread performing a remove operation in a multithreading environment.
If multiple threads access arrayList concurrently, then we must synchronize the block of the code which modifies the list structurally, or alternatively allow simple element modifications. Structural modification means addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification.
Performance: ArrayList is faster, since it is non-synchronized, while vector operations give slower performance since they are synchronized (thread-safe). If one thread works on a vector, it has acquired a lock on it, which forces any other thread wanting to work on it to have to wait until the lock is released.
Data Growth: ArrayList and Vector both grow and shrink dynamically to maintain optimal use of storage – but the way they resize is different. ArrayList increments 50% of the current array size if the number of elements exceeds its capacity, while vector increments 100% – essentially doubling the current array size.
Traversal: Vector can use both Enumeration and Iterator for traversing over elements of vector while ArrayList can only use Iterator for traversing.
Note: ArrayList is preferable when there is no specific requirement to use vector.
// Java Program to illustrate use of ArrayList
// and Vector in Java
import java.io.*;
import java.util.*;
class GFG
{
public static void main (String[] args)
{
// creating an ArrayList
ArrayList<String> al = new ArrayList<String>();
// adding object to arraylist
al.add("Practice.GeeksforGeeks.org");
al.add("quiz.GeeksforGeeks.org");
al.add("code.GeeksforGeeks.org");
al.add("contribute.GeeksforGeeks.org");
// traversing elements using Iterator'
System.out.println("ArrayList elements are:");
Iterator it = al.iterator();
while (it.hasNext())
System.out.println(it.next());
// creating Vector
Vector<String> v = new Vector<String>();
v.addElement("Practice");
v.addElement("quiz");
v.addElement("code");
// traversing elements using Enumeration
System.out.println("\nVector elements are:");
Enumeration e = v.elements();
while (e.hasMoreElements())
System.out.println(e.nextElement());
}
}
Output:
ArrayList elements are:
Practice.GeeksforGeeks.org
quiz.GeeksforGeeks.org
code.GeeksforGeeks.org
contribute.GeeksforGeeks.org
Vector elements are:
Practice
quiz
code
How to choose between ArrayList and Vector?
ArrayList is unsynchronized and not thread-safe, whereas Vectors are. Only one thread can call methods on a Vector at a time, which is a slight overhead, but helpful when safety is a concern. Therefore, in a single-threaded case, arrayList is the obvious choice, but where multithreading is concerned, vectors are often preferable.
If we don’t know how much data we are going to have, but know the rate at which it grows, Vector has an advantage, since we can set the increment value in vectors.
ArrayList is newer and faster. If we don’t have any explicit requirements for using either of them, we use ArrayList over vector.
Why Java doesn’t support multiple inheritance?
Java doesn’t support multiple inheritance in classes because of “Diamond Problem”. To know more about diamond problem with example, read Multiple Inheritance in Java.
However multiple inheritances are supported in interfaces. An interface can extend multiple interfaces because they just declare the methods and implementation will be present in the implementing class. So there is no issue of the diamond problem with interfaces.
What is the importance of main method in Java?
main() method is the entry point of any standalone java application. The syntax of main method is public static void main(String args[]).
Java main method is public and static so that Java runtime can access it without initializing the class. The input parameter is an array of String through which we can pass runtime arguments to the java program. Check this post to learn how to compile and run java program.
Can we overload main method?
Yes, we can have multiple methods with name “main” in a single class. However if we run the class, java runtime environment will look for main method with syntax as public static void main(String args[]).
What is Java Package and which package is imported by default?
Java package is the mechanism to organize the java classes by grouping them. The grouping logic can be based on functionality or modules based. A java class fully classified name contains package and class name. For example, java.lang.Object is the fully classified name of Object class that is part of java.lang package.
java.lang package is imported by default and we don’t need to import any class from this package explicitly.
What is finally and finalize in java?
finally block is used with try-catch to put the code that you want to get executed always, even if any exception is thrown by the try-catch block. finally block is mostly used to release resources created in the try block.
finalize() is a special method in Object class that we can override in our classes. This method gets called by the garbage collector when the object is getting garbage collected. This method is usually overridden to release system resources when the object is garbage collected.
What is the difference between abstract class and interface?
abstract keyword is used to create abstract class whereas interface is the keyword for interfaces.
Abstract classes can have method implementations whereas interfaces can’t.
A class can extend only one abstract class but it can implement multiple interfaces.
We can run an abstract class if it has main() method whereas we can’t run an interface.
Difference between Abstract Class and Interface
abstract keyword is used to create an abstract class and it can be used with methods also whereas interface keyword is used to create interface and it can’t be used with methods.
Subclasses use extends keyword to extend an abstract class and they need to provide implementation of all the declared methods in the abstract class unless the subclass is also an abstract class whereas subclasses use implements keyword to implement interfaces and should provide implementation for all the methods declared in the interface.
Abstract classes can have methods with implementation whereas interface provides absolute abstraction and can’t have any method implementations.
Abstract classes can have constructors but interfaces can’t have constructors.
Abstract class have all the features of a normal java class except that we can’t instantiate it. We can use abstract keyword to make a class abstract but interfaces are a completely different type and can have only public static final constants and method declarations.
Abstract classes methods can have access modifiers as public, private, protected, static but interface methods are implicitly public and abstract, we can’t use any other access modifiers with interface methods.
A subclass can extend only one abstract class but it can implement multiple interfaces.
Abstract classes can extend other class and implement interfaces but interface can only extend other interfaces.
We can run an abstract class if it has main() method but we can’t run an interface because they can’t have main method implementation.
Interfaces are used to define contract for the subclasses whereas abstract class also define contract but it can provide other methods implementations for subclasses to use.
Thats all for the difference between interface and abstract classes, now we can move on to know when should we use Interface over Abstract class and vice versa.
Interface or Abstract Class
Whether to chose between Interface or abstract class for providing contract for subclasses is a design decision and depends on many factors, lets see when Interfaces are best choice and when can we use abstract classes.
Java doesn’t support multiple class level inheritance, so every class can extend only one superclass. But a class can implement multiple interfaces. So most of the times Interfaces are a good choice for providing base for class hierarchy and contract. Also coding in terms of interfaces is one of the best practices for coding in java.
If there are a lot of methods in the contract, then abstract class is more useful because we can provide default implementation for some of the methods that are common for all the subclasses. Also if subclasses don’t need to implement particular method, they can avoid providing the implementation but in case of interface, the subclass will have to provide implementation for all the methods even though it’s of no use and implementation is just empty block.
If our base contract keeps on changing then interfaces can cause issues because we can’t declare additional methods to the interface without changing all the implementation classes, with abstract class we can provide the default implementation and only change the implementation classes that are actually going to use the new methods.
Use Abstract classes and Interface both
Actually most of the times, using Interfaces and abstract classes together is the best approach for designing a system, for example in JDK java.util.List is an interface that contains a lot of methods, so there is an abstract class java.util.AbstractList that provides skeletal implementation for all the methods of List interface so that any subclass can extend this class and implement only required methods.
We should always start with an interface as base and define methods that every subclasses should implement and then if there are some methods that only certain subclass should implement, we can extend the base interface and create a new interface with those methods. The subclasses will have option to chose between the base interface or the child interface to implement according to its requirements. If the number of methods grows a lot, its not a bad idea to provide a skeletal abstract class implementing the child interface and providing flexibility to the subclasses to chose between interface and abstract class.
Java Enum Example
Java enum keyword is used to create an enum type. Let’s have a look at the java enum example program.
package com.journaldev.enums;
public enum ThreadStates {
START,
RUNNING,
WAITING,
DEAD;
}
In above example, ThreadStates is the enum with fixed constants fields START, RUNNING, WAITING and DEAD.
What is the benefit of Composition over Inheritance?
One of the best practices of Java programming is to “favor composition over inheritance”. Some of the possible reasons are:
Any change in the superclass might affect subclass even though we might not be using the superclass methods. For example, if we have a method test() in the subclass and suddenly somebody introduces a method test() in the superclass, we will get compilation errors in the subclass. The composition will never face this issue because we are using only what methods we need.
Inheritance exposes all the superclass methods and variables to the client and if we have no control in designing superclass, it can lead to security holes. Composition allows us to provide restricted access to the methods and hence more secure.
We can get runtime binding in composition where inheritance binds the classes at compile time. So composition provides flexibility in the invocation of methods.
What is Classloader in Java?
Java Classloader is the program that loads byte code program into memory when we want to access any class. We can create our own classloader by extending ClassLoader class and overriding loadClass(String name) method. Learn more at java classloader.
What are different types of classloaders?
There are three types of built-in Class Loaders in Java:
Bootstrap Class Loader – It loads JDK internal classes, typically loads rt.jar and other core classes.
Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
System Class Loader – It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options.
What does super keyword do?
super keyword can be used to access super class method when you have overridden the method in the child class.
We can use super keyword to invoke superclass constructor in child class constructor but in this case, it should be the first statement in the constructor method.
public class SuperClass {
public SuperClass(){
}
public SuperClass(int i){}
public void test(){
System.out.println("super class test method");
}
}
Use of super keyword can be seen in below child class implementation.
package com.journaldev.access;
public class ChildClass extends SuperClass {
public ChildClass(String str){
//access super class constructor with super keyword
super();
//access child class method
test();
//use super to access super class method
super.test();
}
@Override
public void test(){
System.out.println("child class test method");
}
}
What is default constructor?
No argument constructor of a class is known as default constructor. When we don’t define any constructor for the class, java compiler automatically creates the default no-args constructor for the class. If there are other constructors defined, then compiler won’t create default constructor for us.
What is Garbage Collection?
Garbage Collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. In Java, process of deallocating memory is handled automatically by the garbage collector.
We can run the garbage collector with code Runtime.getRuntime().gc() or use utility method System.gc(). For a detailed analysis of Heap Memory and Garbage Collection, please read Java Garbage Collection.
What is Serialization and Deserialization?
We can convert a Java object to an Stream that is called Serialization. Once an object is converted to Stream, it can be saved to file or send over the network or used in socket connections.
The object should implement Serializable interface and we can use java.io.ObjectOutputStream to write object to file or to any OutputStream object. Read more at Java Serialization.
The process of converting stream data created through serialization to Object is called deserialization. Read more at Java Deserialization.
How to run a JAR file through command prompt?
We can run a jar file using java command but it requires Main-Class entry in jar manifest file. Main-Class is the entry point of the jar and used by java command to execute the class. Learn more at java jar file.
What is instanceof keyword?
We can use instanceof keyword to check if an object belongs to a class or not. We should avoid it’s usage as much as possible. Sample usage is:
public static void main(String args[]){
Object str = new String("abc");
if(str instanceof String){
System.out.println("String value:"+str);
}
if(str instanceof Integer){
System.out.println("Integer value:"+str);
}
}
Can we use String with switch case?
One of the Java 7 feature was improvement of switch case of allow Strings. So if you are using Java 7 or higher version, you can use String in switch-case statements. Read more at Java switch-case String example.
Java is Pass by Value or Pass by Reference?
This is a very confusing question, we know that object variables contain the reference to the Objects in heap space. When we invoke any method, a copy of these variables is passed and gets stored in the stack memory of the method. We can test any language whether it’s pass by reference or pass by value through a simple generic swap method, to learn more read Java is Pass by Value and Not Pass by Reference.
What is difference between Heap and Stack Memory?
Major difference between Heap and Stack memory are as follows:
Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
Memory management in the stack is done in a LIFO manner whereas it’s more complex in Heap memory because it’s used globally.
For a detailed explanation with a sample program, read Java Heap vs Stack Memory.
Java Compiler is stored in JDK, JRE or JVM?
The task of java compiler is to convert java program into bytecode, we have javac executable for that. So it must be stored in JDK, we don’t need it in JRE and JVM is just the specs.
What will be the output of following programs?
static method in class
package com.journaldev.util;
public class Test {
public static String toString(){
System.out.println("Test toString called");
return "";
}
public static void main(String args[]){
System.out.println(toString());
}
}
Answer: The code won’t compile because we can’t have an Object class method with static keyword. Note that Object class has toString() method. You will get a compile-time error as “This static method cannot hide the instance method from Object”. The reason is that static method belongs to the class and since every class base is Object, we can’t have the same method in the instance as well as in class. You won’t get this error if you change the method name from toString() to something else that is not present in superclass Object.
static method invocation
package com.journaldev.util;
public class Test {
public static String foo(){
System.out.println("Test foo called");
return "";
}
public static void main(String args[]){
Test obj = null;
System.out.println(obj.foo());
}
}
Answer: Well this is a strange situation. We all have seen NullPointerException when we invoke a method on the object that is NULL. But here this program will work and prints “Test foo called”.
The reason for this is the java compiler code optimization. When the java code is compiled to produced byte code, it figures out that foo() is a static method and should be called using class. So it changes the method call obj.foo() to Test.foo() and hence no NullPointerException.
Comments
Post a Comment