Java Interview Questions Part 3

How to make a read-only class in Java?

A class can be made read-only by making all of the fields private. The read-only class will have only getter methods which return the private property of the class to the main method. We cannot modify this property because there is no setter method available in the class. Consider the following example.

  1.   //A Java class which has only getter methods.    
  2. public class Student{    
  3. //private data member    
  4. private String college="AKG";    
  5. //getter method for college    
  6. public String getCollege(){    
  7. return college;    
  8. }    
  9. }    

122) How to make a write-only class in Java?

A class can be made write-only by making all of the fields private. The write-only class will have only setter methods which set the value passed from the main method to the private fields. We cannot read the properties of the class because there is no getter method in this class. Consider the following example.

  1.   //A Java class which has only setter methods.    
  2. public class Student{    
  3. //private data member    
  4. private String college;    
  5. //getter method for college    
  6. public void setCollege(String college){    
  7. this.college=college;    
  8. }    
  9. }    

 

Can you declare an interface method static?

No, because methods of an interface are abstract by default, and we can not use static and abstract together.

Do I need to import java.lang package any time? Why?

No. It is by default loaded internally by the JVM.

 

Is the following program written correctly? If yes then what will be the output of the program?

  1. abstract class Calculate  
  2. {  
  3.     abstract int multiply(int a, int b);  
  4. }  
  5.    
  6. public class Main  
  7. {  
  8.     public static void main(String[] args)  
  9.     {  
  10. 10.         int result = new Calculate()  
  11. 11.         {      
  12. 12.             @Override  
  13. 13.             int multiply(int a, int b)  
  14. 14.             {  
  15. 15.                 return a*b;  
  16. 16.             }  
  17. 17.         }.multiply(12,32);  
  18. 18.         System.out.println("result = "+result);  
  19. 19.     }  

20. }  

Yes, the program is written correctly. The Main class provides the definition of abstract method multiply declared in abstract class Calculation. The output of the program will be:

Output

384

More details.

 

What is the meaning of immutable regarding String?

The simple meaning of immutable is unmodifiable or unchangeable. In Java, String is immutable, i.e., once string object has been created, its value can't be changed. Consider the following example for better understanding.

  1. class Testimmutablestring{  
  2.  public static void main(String args[]){  
  3.    String s="Sachin";  
  4.    s.concat(" Tendulkar");//concat() method appends the string at the end  
  5.    System.out.println(s);//will print Sachin because strings are immutable objects  
  6.  }  
  7. }  

Test it Now

Output:

Sachin

More details.


How many objects will be created in the following code?

  1. String s1="Welcome";  
  2. String s2="Welcome";  
  3. String s3="Welcome";  

Only one object will be created using the above code because strings in Java are immutable.

More details.


How many objects will be created in the following code?

  1. String s = new String("Welcome");  

Two objects, one in string constant pool and other in non-pool(heap).

More details.

What is the output of the following Java program?

  1. public class Test   
  2.   
  3.   public static void main (String args[])  
  4.   {  
  5.       String a = new String("Sharma is a good player");  
  6.       String b = "Sharma is a good player";  
  7.       if(a == b)  
  8.       {  
  9.           System.out.println("a == b");  
  10. 10.       }  
  11. 11.       if(a.equals(b))  
  12. 12.       {  
  13. 13.           System.out.println("a equals b");  
  14. 14.       }  
  15. 15.   }  

Output

  a equals b

Explanation

The operator == also check whether the references of the two string objects are equal or not. Although both of the strings contain the same content, their references are not equal because both are created by different ways(Constructor and String literal) therefore, a == b is unequal. On the other hand, the equal() method always check for the content. Since their content is equal hence, a equals b is printed.

What is String Pool?

String pool is the space reserved in the heap memory that can be used to store the strings. The main advantage of using the String pool is whenever we create a string literal; the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. Therefore, it saves the memory by avoiding the duplicacy.

How many ways can we create the string object?

1) String Literal

Java String literal is created by using double quotes. For Example:

  1. String s="welcome";  

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. String objects are stored in a special memory area known as the string constant pool For example:

  1. String s1="Welcome";  
  2. String s2="Welcome";//It doesn't create a new instance  

2) By new keyword

  1. String s=new String("Welcome");//creates two objects and one reference variable  

In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the constant string pool. The variable s will refer to the object in a heap (non-pool).

 

How can we create an immutable class in Java?

We can create an immutable class by defining a final class having all of its members as final. Consider the following example.

  1. public final class Employee{  
  2. final String pancardNumber;  
  3.   
  4. public Employee(String pancardNumber){  
  5. this.pancardNumber=pancardNumber;  
  6. }  
  7.   
  8. public String getPancardNumber(){  
  9. return pancardNumber;  

10. }  

  1. 11.   

12. }  

More details.

 

What are the differences between StringBuffer and StringBuilder?

The differences between the StringBuffer and StringBuilder is given below.

No.

StringBuffer

StringBuilder

1)

StringBuffer is synchronized, i.e., thread safe. It means two threads can't call the methods of StringBuffer simultaneously.

StringBuilder is non-synchronized,i.e., not thread safe. It means two threads can call the methods of StringBuilder simultaneously.

2)

StringBuffer is less efficient than StringBuilder.

StringBuilder is more efficient than StringBuffer.

 

Write a Java program to count the number of words present in a string?

Program:

  1.   public class Test   
  2. {  
  3.     public static void main (String args[])  
  4.     {  
  5.         String s = "Sharma is a good player and he is so punctual";  
  6.         String words[] = s.split(" ");  
  7.         System.out.println("The Number of words present in the string are : "+words.length);  
  8.     }  
  9. }  

Output

The Number of words present in the string are : 10

 

What is the output of the following Java program?

  1. public class Test   
  2. {  
  3.     public static void main (String args[])  
  4.     {  
  5.         String s1 = "Sharma is a good player";  
  6.         String s2 = new String("Sharma is a good player");  
  7.         s2 = s2.intern();  
  8.         System.out.println(s1 ==s2);  
  9.     }  

10. }  

Output

true

Explanation

The intern method returns the String object reference from the string pool. In this case, s1 is created by using string literal whereas, s2 is created by using the String pool. However, s2 is changed to the reference of s1, and the operator == returns true.

What is the purpose of toString() method in Java?

The toString() method returns the string representation of an object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object, etc. depending upon your implementation. By overriding the toString() method of the Object class, we can return the values of the object, so we don't need to write much code. Consider the following example.

  1. class Student{  
  2.  int rollno;  
  3.  String name;  
  4.  String city;  
  5.   
  6.  Student(int rollno, String name, String city){  
  7.  this.rollno=rollno;  
  8.  this.name=name;  
  9.  this.city=city;  
  10. 10.  }  
  11. 11.    
  12. 12.  public String toString(){//overriding the toString() method  
  13. 13.   return rollno+" "+name+" "+city;  
  14. 14.  }  
  15. 15.  public static void main(String args[]){  
  16. 16.    Student s1=new Student(101,"Raj","lucknow");  
  17. 17.    Student s2=new Student(102,"Vijay","ghaziabad");  
  18. 18.      
  19. 19.    System.out.println(s1);//compiler writes here s1.toString()  
  20. 20.    System.out.println(s2);//compiler writes here s2.toString()  
  21. 21.  }  

22. }  

Output:

101 Raj lucknow

102 Vijay ghaziabad

More details.

 

Why CharArray() is preferred over String to store the password?

String stays in the string pool until the garbage is collected. If we store the password into a string, it stays in the memory for a longer period, and anyone having the memory-dump can extract the password as clear text. On the other hand, Using CharArray allows us to set it to blank whenever we are done with the password. It avoids the security threat with the string by enabling us to control the memory.

Why are the objects immutable in java?

Because Java uses the concept of the string literal. Suppose there are five reference variables, all refer to one object "sachin". If one reference variable changes the value of the object, it will be affected by all the reference variables. That is why string objects are immutable in java.

Why java uses the concept of the string literal?

To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).

When can an object reference be cast to an interface reference?

An object reference can be cast to an interface reference when the object implements the referenced interface.

What is Java instanceOf operator?

The instanceof in Java is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has a null value, it returns false. Consider the following example.

  1. class Simple1{  
  2.  public static void main(String args[]){  
  3.  Simple1 s=new Simple1();  
  4.  System.out.println(s instanceof Simple1);//true  
  5.  }  
  6. }  

Test it Now

Output

true


An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object of Dog can be referred by either Dog or Animal class.

What is aggregation?

Aggregation can be defined as the relationship between two classes where the aggregate class contains a reference to the class it owns. Aggregation is best described as a has-a relationship. For example, The aggregate class Employee having various fields such as age, name, and salary also contains an object of Address class having various fields such as Address-Line 1, City, State, and pin-code. In other words, we can say that Employee (class) has an object of Address class. Consider the following example.

Address.java

  1. public class Address {  
  2. String city,state,country;  
  3.   
  4. public Address(String city, String state, String country) {  
  5.     this.city = city;  
  6.     this.state = state;  
  7.     this.country = country;  
  8. }  
  9.   

10. }  

Employee.java

  1. public class Emp {  
  2. int id;  
  3. String name;  
  4. Address address;  
  5.   
  6. public Emp(int id, String name,Address address) {  
  7.     this.id = id;  
  8.     this.name = name;  
  9.     this.address=address;  

10. }  

  1. 11.   

12. void display(){  

13. System.out.println(id+" "+name);  

14. System.out.println(address.city+" "+address.state+" "+address.country);  

15. }  

  1. 16.   

17. public static void main(String[] args) {  

18. Address address1=new Address("gzb","UP","india");  

19. Address address2=new Address("gno","UP","india");  

  1. 20.   

21. Emp e=new Emp(111,"varun",address1);  

22. Emp e2=new Emp(112,"arun",address2);  

  1. 23.       

24. e.display();  

25. e2.display();  

  1. 26.       

27. }  

28. }  

Output

111 varun

gzb UP india

112 arun

gno UP india

How is garbage collection controlled?

Garbage collection is managed by JVM. It is performed when there is not enough space in the memory and memory is running low. We can externally call the System.gc() for the garbage collection. However, it depends upon the JVM whether to perform it or not.

What is the difference between static (class) method and instance method?

static or class method

instance method

1)A method that is declared as static is known as the static method.

A method that is not declared as static is known as the instance method.

2)We don't need to create the objects to call the static methods.

The object is required to call the instance methods.

3)Non-static (instance) members cannot be accessed in the static context (static method, static block, and static nested class) directly.

Static and non-static variables both can be accessed in instance methods.

4)For example: public static int cube(int n){ return n*n*n;}

For example: public void msg(){...}.

 

What is object-oriented paradigm?

It is a programming paradigm based on objects having data and methods defined in the class to which it belongs. Object-oriented paradigm aims to incorporate the advantages of modularity and reusability. Objects are the instances of classes which interacts with one another to design applications and programs. There are the following features of the object-oriented paradigm.

  • Follows the bottom-up approach in program design.
  • Focus on data with methods to operate upon the object's data
  • Includes the concept like Encapsulation and abstraction which hides the complexities from the user and show only functionality.
  • Implements the real-time approach like inheritance, abstraction, etc.
  • The examples of the object-oriented paradigm are C++, Simula, Smalltalk, Python, C#, etc.

What is the difference between an object-oriented programming language and object-based programming language?

There are the following basic differences between the object-oriented language and object-based language.

  • Object-oriented languages follow all the concepts of OOPs whereas, the object-based language doesn't follow all the concepts of OOPs like inheritance and polymorphism.
  • Object-oriented languages do not have the inbuilt objects whereas Object-based languages have the inbuilt objects, for example, JavaScript has window object.
  • Examples of object-oriented programming are Java, C#, Smalltalk, etc. whereas the examples of object-based languages are JavaScript, VBScript, etc

What is composition?

Holding the reference of a class within some other class is known as composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. In other words, we can say that composition is the particular case of aggregation which represents a stronger relationship between two objects. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

What is the difference between aggregation and composition?

Aggregation represents the weak relationship whereas composition represents the strong relationship. For example, the bike has an indicator (aggregation), but the bike has an engine (composition).

What is the difference between final, finally and finalize?

No.

final

finally

finalize

1)

Final is used to apply restrictions on class, method, and variable. The 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 an exception is handled or not.

Finalize is used to perform clean up processing just before an object is garbage collected.

2)

Final is a keyword.

Finally is a block.

Finalize is a method.


 

How can an object be unreferenced?

There are many ways:

  • By nulling the reference
  • By assigning a reference to another
  • By anonymous object etc.

 

By nulling a reference:

  1. Employee e=new Employee();  
  2. e=null;  

 By assigning a reference to another:

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

 By anonymous object:

  1. new Employee();  

 

Can an unreferenced object be referenced again?

Yes,

Can we overload the methods by making them static?

No, We cannot overload the methods by just applying the static keyword to them(number of parameters and types are the same). Consider the following example.

  1. public class Animal  
  2. {  
  3.     void consume(int a)  
  4.     {  
  5.         System.out.println(a+" consumed!!");  
  6.     }  
  7.     static void consume(int a)  
  8.     {  
  9.         System.out.println("consumed static "+a);  
  10. 10.     }  
  11. 11.     public static void main (String args[])  
  12. 12.     {  
  13. 13.         Animal a = new Animal();  
  14. 14.         a.consume(10);  
  15. 15.         Animal.consume(20);  
  16. 16.     }  

17. }    

Output

Animal.java:7: error: method consume(int) is already defined in class Animal

    static void consume(int a)

                ^

Animal.java:15: error: non-static method consume(int) cannot be referenced from a static context

        Animal.consume(20);

              ^

2 errors

 

posted @ 2020-04-11 21:21  CodingYM  阅读(258)  评论(0编辑  收藏  举报