Java Interview Questions Part 5

What is Socket?

A socket is simply an endpoint for communications between the machines. It provides the connection mechanism to connect the two computers using TCP. The Socket class can be used to create a socket.

Give a brief description of Java socket programming?

Java Socket programming is used for communication between the applications running on different JRE. Java Socket programming can be connection-oriented or connectionless. Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket, and DatagramPacket classes are used for connectionless socket programming. The client in socket programming must know two information:

  • IP address of the server
  • port number

What is a nested class?

The nested class can be defined as the class which is defined inside another class or interface. We use the nested class to logically group classes and interfaces in one place so that it can be more readable and maintainable. A nested class can access all the data members of the outer class including private data members and methods. The syntax of the nested class is defined below.

  1. class Java_Outer_class{    
  2.  //code    
  3.  class Java_Nested_class{    
  4.   //code    
  5.  }    
  6. }    
  7.       

There are two types of nested classes, static nested class, and non-static nested class. The non-static nested class can also be called as inner-class

More details.

 

What are the advantages of Java inner classes?

There are two types of advantages of Java inner classes.

  • Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of the outer class including private.
  • Nested classes are used to develop a more readable and maintainable code because it logically groups classes and interfaces in one place only.
  • Code Optimization: It requires less code to write.

What are the types of inner classes (non-static nested class) used in Java?

There are mainly three types of inner classes used in Java.

Type

Description

Member Inner Class

A class created within class and outside method.

Anonymous Inner Class

A class created for implementing an interface

or extending class. Its name is decided by the java compiler.

Local Inner Class

A class created within the method.

 

Is there any difference between nested classes and inner classes?

Yes, inner classes are non-static nested classes. In other words, we can say that inner classes are the part of nested classes.

More details.

What are the steps that are followed when two computers connect through TCP?

There are the following steps that are performed when two computers connect through TCP.

  • The ServerSocket object is instantiated by the server which denotes the port number to which, the connection will be made.
  • After instantiating the ServerSocket object, the server invokes accept() method of ServerSocket class which makes server wait until the client attempts to connect to the server on the given port.
  • Meanwhile, the server is waiting, a socket is created by the client by instantiating Socket class. The socket class constructor accepts the server port number and server name.
  • The Socket class constructor attempts to connect with the server on the specified name. If the connection is established, the client will have a socket object that can communicate with the server.
  • The accept() method invoked by the server returns a reference to the new socket on the server that is connected with the server.

 

What is the nested interface?

An Interface that is declared inside the interface or class is known as the nested interface. It is static by default. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The external interface or class must refer to the nested interface. It can't be accessed directly. The nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class. The syntax of the nested interface is given as follows.

  1. interface interface_name{    
  2.  ...    
  3.  interface nested_interface_name{    
  4.   ...    
  5.  }    
  6. }     
  7.       

More details.

Can a class have an interface?

Yes, an interface can be defined within the class. It is called a nested interface.

More details.

 

Can a Serialized object be transferred via network?

Yes, we can transfer a serialized object via network because the serialized object is stored in the memory in the form of bytes and can be transmitted over the network. We can also write the serialized object to the disk or the database.

What is a singleton class?

Singleton class is the class which can not be instantiated more than once. To make a class singleton, we either make its constructor private or use the static getInstance method. Consider the following example.

  1. class Singleton{  
  2.     private static Singleton single_instance = null;  
  3.     int i;  
  4.      private Singleton ()  
  5.      {  
  6.          i=90;  
  7.      }  
  8.      public static Singleton getInstance()  
  9.      {  
  10. 10.          if(single_instance == null)  
  11. 11.          {  
  12. 12.              single_instance = new Singleton();  
  13. 13.          }  
  14. 14.          return single_instance;  
  15. 15.      }  

16. }  

17. public class Main   

18. {  

  1. 19.     public static void main (String args[])  
  2. 20.     {  
  3. 21.         Singleton first = Singleton.getInstance();  
  4. 22.         System.out.println("First instance integer value:"+first.i);  
  5. 23.         first.i=first.i+90;  
  6. 24.         Singleton second = Singleton.getInstance();  
  7. 25.         System.out.println("Second instance integer value:"+second.i);  
  8. 26.     }  

27. }  

  1. 28.       

 

What is Locale?

A Locale object represents a specific geographical, political, or cultural region. This object can be used to get the locale-specific information such as country name, language, variant, etc.

  1. import java.util.*;  
  2. public class LocaleExample {  
  3. public static void main(String[] args) {  
  4. Locale locale=Locale.getDefault();  
  5. //Locale locale=new Locale("fr","fr");//for the specific locale  
  6.   
  7. System.out.println(locale.getDisplayCountry());  
  8. System.out.println(locale.getDisplayLanguage());  
  9. System.out.println(locale.getDisplayName());  

10. System.out.println(locale.getISO3Country());  

11. System.out.println(locale.getISO3Language());  

12. System.out.println(locale.getLanguage());  

13. System.out.println(locale.getCountry());  

  1. 14.       

15. }  

16. }  

Output:

United States

English

English (United States)

USA

eng

en

US


What is the output of the below Java program?

  1. public class Test1  
  2. {  
  3.   public static void main(String[] args) {  
  4.   Integer i = new Integer(201);  
  5.   Integer j = new Integer(201);  
  6.   if(i == j)  
  7.   {  
  8.     System.out.println("hello");  
  9.   }  
  10. 10.   else   
  11. 11.   {  
  12. 12.     System.out.println("bye");  
  13. 13.   }  
  14. 14.   }  

15. }  

Output

bye

Explanation

The Integer class caches integer values from -127 to 127. Therefore, the Integer objects can only be created in the range -128 to 127. The operator == will not work for the value greater than 127; thus bye is printed.

What is the purpose of the System class?

The purpose of the System class is to provide access to system resources such as standard input and output. It cannot be instantiated. Facilities provided by System class are given below.

  • Standard input
  • Error output streams
  • Standard output
  • utility method to copy the portion of an array
  • utilities to load files and libraries

There are the three fields of Java System class, i.e., static printstream err, static inputstream in, and standard output stream.

What comes to mind when someone mentions a shallow copy in Java?

Object cloning.

What are wrapper classes?

Wrapper classes are classes that allow primitive types to be accessed as objects. In other words, we can say that wrapper classes are built-in java classes which allow the conversion of objects to primitives and primitives to objects. The process of converting primitives to objects is called autoboxing, and the process of converting objects to primitives is called unboxing. There are eight wrapper classes present in java.lang package is given below.

Primitive Type

Wrapper class

boolean

Boolean

char

Character

byte

Byte

short

Short

int

Integer

long

Long

float

Float

double

Double

What do you understand by the bean persistent property?

The persistence property of Java bean comes into the act when the properties, fields, and state information are saved to or retrieve from the storage.

What are autoboxing and unboxing? When does it occur?

The autoboxing is the process of converting primitive data type to the corresponding wrapper class object, eg., int to Integer. The unboxing is the process of converting wrapper class object to primitive data type. For eg., integer to int. Unboxing and autoboxing occur automatically in Java. However, we can externally convert one into another by using the methods like valueOf() or xxxValue().

It can occur whenever a wrapper class object is expected, and primitive data type is provided or vice versa.

  • Adding primitive types into Collection like ArrayList in Java.
  • Creating an instance of parameterized classes ,e.g., ThreadLocal which expect Type.
  • Java automatically converts primitive to object whenever one is required and another is provided in the method calling.

When a primitive type is assigned to an object type.

 

What is a marker interface?

A Marker interface can be defined as the interface which has no data member and member functions. For example, Serializable, Cloneable are marker interfaces. The marker interface can be declared as follows.

  1. public interface Serializable{    

}  

 

What are the differences between C++ and Java?

The differences between C++ and Java are given in the following table.

Comparison Index

C++

Java

Platform-independent

C++ is platform-dependent.

Java is platform-independent.

Mainly used for

C++ is mainly used for system programming.

Java is mainly used for application

 programming.

It is widely used in window,

web-based, enterprise and

mobile applications.

Design Goal

C++ was designed for systems and applications programming. It was an extension of C programming language.

Java was designed

 and created as an

 interpreter for printing systems

but later extended as a support

 network computing.

It was designed with a goal of

being easy to use and accessible

to a broader audience.

Goto

C++ supports the goto statement.

Java doesn't support the goto statement.

Multiple inheritance

C++ supports multiple inheritance.

Java doesn't support multiple inheritance through class. It can be achieved by interfaces in java.

Operator Overloading

C++ supports operator overloading.

Java doesn't support

operator overloading.

Pointers

C++ supports pointers. You can write pointer program in C++.

Java supports pointer internally. However, you can't write the pointer program in java. It means java has restricted pointer support in Java.

Compiler and Interpreter

C++ uses compiler only. C++ is compiled and run using the compiler which converts source code into machine code so, C++ is platform dependent.

Java uses compiler and interpreter

both. Java source code is converted

into bytecode at compilation time.

The interpreter executes

 this bytecode at runtime

and produces output.

Java is interpreted that is why

 it is platform independent.

Call by Value and Call by reference

C++ supports both call by value and call by reference.

Java supports call by value only.

There is no call by reference in java.

Structure and Union

C++ supports structures and unions.

Java doesn't

support structures and unions.

Thread Support

C++ doesn't have built-in support for threads. It relies on third-party libraries for thread support.

Java has built-in thread support.

Documentation comment

C++ doesn't support documentation comment.

Java supports

documentation

comment (/** ... */)

to create documentation

 for java source code.

Virtual Keyword

C++ supports virtual keyword so that we can decide whether or not override a function.

Java has no virtual keyword.

We can override all non-static

methods by default.

In other words, non-static methods

are virtual by default.

unsigned right shift >>>

C++ doesn't support >>> operator.

Java supports unsigned right shift >>> operator that fills zero at the top for the negative numbers. For positive numbers, it works same like >> operator.

Inheritance Tree

C++ creates a new inheritance tree always.

Java uses a single

inheritance tree always

 because all classes are the

child of Object class in java.

 The object class is the root of the

 inheritance tree in java.

Hardware

C++ is nearer to hardware.

Java is not so interactive with

 hardware.

Object-oriented

C++ is an object-oriented language. However, in C language, single root hierarchy is not possible.

Java is also an object-oriented

 language. However,

everything

 (except fundamental types)

 is an object in Java.

 It is a single root hierarchy

as everything gets derived from

java.lang.Object.

 

What do you understand by Java virtual machine?

Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts like a run-time engine which calls the main method present in the Java code. JVM is the specification which must be implemented in the computer system. The Java code is compiled by JVM to be a Bytecode which is machine independent and close to the native code.

How many types of memory areas are allocated by JVM?

Many types:

  1. Class(Method) Area: Class Area stores per-class structures such as the runtime constant pool, field, method data, and the code for methods.
  2. Heap: It is the runtime data area in which the memory is allocated to the objects
  3. Stack: Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as the thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
  4. Program Counter Register: PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.
  5. Native Method Stack: It contains all the native methods used in the application.

More Details.

Is Empty .java file name a valid source file name?

Yes, Java allows to save our java file by .java only, we need to compile it by javac .java and run by java classname Let's take a simple example:

  1. //save by .java only  
  2. class A{  
  3. public static void main(String args[]){  
  4. System.out.println("Hello java");  
  5. }  
  6. }  
  7. //compile by javac .java  
  8. //run by     java A  

compile it by javac .java

run it by java A

What are the advantages of passing this into a method instead of the current class object itself?

As we know, that this refers to the current class object, therefore, it must be similar to the current class object. However, there can be two main advantages of passing this into a method instead of the current class object.

  • this is a final variable. Therefore, this cannot be assigned to any new value whereas the current class object might not be final and can be changed.
  • this can be used in the synchronized block.

What is object cloning?

The object cloning is used to create the exact copy of an object. The clone() method of the Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.

  1. protected Object clone() throws CloneNotSupportedException    
  2.       

 

What is object cloning?

The object cloning is a way to create an exact copy of an object. The clone() method of the Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException. The clone() method is defined in the Object class. The syntax of the clone() method is as follows:

protected Object clone() throws CloneNotSupportedException

How can you avoid serialization in child class if the base class is implementing the Serializable interface?

It is very tricky to prevent serialization of child class if the base class is intended to implement the Serializable interface. However, we cannot do it directly, but the serialization can be avoided by implementing the writeObject() or readObject() methods in the subclass and throw NotSerializableException from these methods. Consider the following example.

  1. import java.io.FileInputStream;   
  2. import java.io.FileOutputStream;   
  3. import java.io.IOException;   
  4. import java.io.NotSerializableException;   
  5. import java.io.ObjectInputStream;   
  6. import java.io.ObjectOutputStream;   
  7. import java.io.Serializable;   
  8. class Person implements Serializable   
  9. {   
  10. 10.     String name = " ";  
  11. 11.     public Person(String name)    
  12. 12.     {   
  13. 13.         this.name = name;   
  14. 14.     }         

15. }   

16. class Employee extends Person  

17. {   

  1. 18.     float salary;  
  2. 19.     public Employee(String name, float salary)    
  3. 20.     {   
  4. 21.         super(name);   
  5. 22.         this.salary = salary;   
  6. 23.     }   
  7. 24.     private void writeObject(ObjectOutputStream out) throws IOException   
  8. 25.     {   
  9. 26.         throw new NotSerializableException();   
  10. 27.     }   
  11. 28.     private void readObject(ObjectInputStream in) throws IOException   
  12. 29.     {   
  13. 30.         throw new NotSerializableException();   
  14. 31.     }   
  15. 32.         

33. }   

34. public class Test   

35. {   

  1. 36.     public static void main(String[] args)    
  2. 37.             throws Exception    
  3. 38.     {   
  4. 39.         Employee emp = new Employee("Sharma", 10000);   
  5. 40.             
  6. 41.         System.out.println("name = " + emp.name);   
  7. 42.         System.out.println("salary = " + emp.salary);   
  8. 43.             
  9. 44.         FileOutputStream fos = new FileOutputStream("abc.ser");   
  10. 45.         ObjectOutputStream oos = new ObjectOutputStream(fos);   
  11. 46.                 
  12. 47.         oos.writeObject(emp);   
  13. 48.                 
  14. 49.         oos.close();   
  15. 50.         fos.close();   
  16. 51.                 
  17. 52.         System.out.println("Object has been serialized");   
  18. 53.             
  19. 54.         FileInputStream f = new FileInputStream("ab.txt");   
  20. 55.         ObjectInputStream o = new ObjectInputStream(f);   
  21. 56.                 
  22. 57.         Employee emp1 = (Employee)o.readObject();   
  23. 58.                 
  24. 59.         o.close();   
  25. 60.         f.close();   
  26. 61.                 
  27. 62.         System.out.println("Object has been deserialized");   
  28. 63.             
  29. 64.         System.out.println("name = " + emp1.name);   
  30. 65.         System.out.println("salary = " + emp1.salary);   
  31. 66.     }   

67. }   

 

What is the difference between Serializable and Externalizable interface?

No.

Serializable

Externalizable

1)

The Serializable interface does not have any method, i.e., it is a marker interface.

The Externalizable interface contains

is not a marker interface,

It contains two methods, i.e.,

 writeExternal() and readExternal().

2)

It is used to "mark" Java classes so that objects of these classes may get the certain capability.

The Externalizable interface provides control

of the serialization logic to the programmer.

3)

It is easy to implement but has the higher performance cost.

It is used to perform the serialization and

often result in better performance.

4)

No class constructor is called in serialization.

We must call a public default constructor

while using this interface.

 

 

What are the main differences between the Java platform and other platforms?

There are the following differences between the Java platform and other platforms.

  • Java is the software-based platform whereas other platforms may be the hardware platforms or software-based platforms.
  • Java is executed on the top of other hardware platforms whereas other platforms can only have the hardware components.

What gives Java its 'write once and run anywhere' nature?

The bytecode. Java compiler converts the Java programs into the class file (Byte Code) which is the intermediate language between source code and machine code. This bytecode is not platform specific and can be executed on any computer.

 

Can an Interface have a class?

Yes, they are static implicitly.

More details.

 

What are the disadvantages of using inner classes?

There are the following main disadvantages of using inner classes.

  • Inner classes increase the total number of classes used by the developer and therefore increases the workload of JVM since it has to perform some routine operations for those extra classes which result in slower performance.
  • IDEs provide less support to the inner classes as compare to the top level classes and therefore it annoys the developers while working with inner classes.
posted @ 2020-04-18 21:30  CodingYM  阅读(197)  评论(0编辑  收藏  举报