Java Interview Questions -23

Java Interview Questions -23

1.What are checked exceptions?
Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.

2.How to create custom exceptions?
Your class should extend class Exception, or some more specific type thereof.

3.If I want an object of my class to be thrown as an exception object, what should I do?
The class should extend from Exception class. Or you can extend your class from some more precise exception type also.

4.If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?
One can not do anything in this scenario. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

5.What are runtime exceptions?
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

6.Is it necessary that each try block must be followed by a catch block?
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

7.If I write return at the end of the try block, will the finally block still execute?
Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.

8.If I write System.exit (0); at the end of the try block, will the finally block still execute?
No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.

9.What is the difference between error and an exception?
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).

10.How does an exception permeate through the code?
An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

11.What are the different ways to handle exceptions?
There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.

12.What is the basic difference between the 2 approaches to exception handling.
1. try catch block and
2. specifying the candidate exceptions in the throws clause?

13.When should you use which approach?
In the first approach as a programmer of the method, you yourself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

14.How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

15.What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.

16.How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

17.Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection .

18.What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

19.What is the difference between a while statement and a do statement?
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

20.What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

21.How are this() and super() used with constructors?
This() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

22.What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

23.What is daemon thread and which method is used to create the daemon thread?
Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.

24.When a thread is created and started, what is its initial state?
A thread is in the ready state after it has been created and started.

25.What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

26.Can an unreachable object become reachable again?
An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

27.What method must be implemented by all threads?
All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.

28.What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

29.What is Externalizable?
Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

30.What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.

31.What are some alternatives to inheritance?
Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

32.What is the Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

33.Can applets communicate with each other?
 

At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable.
An applet can also get references to all other applets on the same page using the getApplets() method of java.applet.AppletContext. Once you get the reference to an applet, you can communicate with it by using its public members.
It is conceivable to have applets in different virtual machines that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non-trivial.


34.What are the steps in the JDBC connection?
While making a JDBC connection we go through the following steps :
Step 1 : Register the database driver by using :
Class.forName(\" driver classs for that specific database\" );
Step 2 : Now create a database connection using :
Connection con = DriverManager.getConnection(url,username,password);
Step 3: Now Create a query using :
Statement stmt = Connection.Statement(\"select * from TABLE NAME\");
Step 4 : Exceute the query :
stmt.exceuteUpdate();

35.How does a try statement determine which catch clause should be used to handle an exception?
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exceptionis executed. The remaining catch clauses are ignored.

36.What does it mean that a method or field is "static"?
Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class.
Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work out is a static field in the java.lang.System class.

37.What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

38.What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

39.Is delete a keyword in Java?
No, delete is not a keyword in Java. Java does not make use of explicit destructors the way C++ does.

40.Is exit a keyword in Java?
No. To exit a program explicitly you use exit method in System object.

41.What happens if you don't initialize an instance variable of any of the primitive types in Java?
Java by default initializes it to the default value for that primitive type. Thus an int will be initialized to 0, a Boolean will be initialized to false.

42.What will be the initial value of an object reference which is defined as an instance variable?
The object references are all initialized to null in Java. However in order to do anything useful with these references, you must set them to a valid object, else you will get NullPointerException everywhere you try to use such default initialized references.

43.What are the different scopes for Java variables?
The scope of a Java variable is determined by the context in which the variable is declared. Thus a java variable can have one of the three scopes at any given point in time.
1. Instance : - These are typical object level variables, they are initialized to default values at the time of creation of object, and remain accessible as long as the object accessible.
2. Local : - These are the variables that are defined within a method. They remain accessible only during the course of method execution. When the method finishes execution, these variables fall out of scope.
3. Static: - These are the class level variables. They are initialized when the class is loaded in JVM for the first time and remain there as long as the class remains loaded. They are not tied to any particular object instance.

44.What is the default value of the local variables?
The local variables are not initialized to any default value, neither primitives nor object references. If you try to use these variables without initializing them explicitly, the java compiler will not compile the code. It will complain about the local variable not being initialized..

45.Is Empty .java file a valid source file?
Yes, an empty .java file is a perfectly valid source file.

46.Can a .java file contain more than one java classes?
Yes, a .java file contain more than one java classes, provided at the most one of them is a public class.

47.Is String a primitive data type in Java?
No String is not a primitive data type in Java, even though it is one of the most extensively used object. Strings in Java are instances of String class defined in java.lang package.

48.Is main a keyword in Java?
No, main is not a keyword in Java.
Is next a keyword in Java?
No, next is not a keyword.

49.How many objects are created in the following piece of code? MyClass c1, c2, c3;
c1 = new MyClass ();
c3 = new MyClass ();
Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized.

50.Can a public class MyClass be defined in a source file named YourClass.java?
No the source file name, if it contains a public class, must be the same as the public class name itself with a .java extension.

51.What will be the default values of all the elements of an array defined as an instance variable?
If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type. e.g. All the elements of an array of int will be initialized to 0, while that of Boolean type will be initialized to false. Whereas if the array is an array of references (of any type), all the elements will be initialized to null.

52.Can main method be declared final?
Yes, the main method can be declared final, in addition to being public static.

53.What will be the output of the following statement?
System.out.println ("1" + 3);
It will print 13.

54.Explain about Core Java?
Java is increasingly used for middleware applications to communicate between Server and clients. Java has features such as multithreading, portability and networking capabilities. Changes in the java library made java as a favorite programming language for developers it added functionality to their scripts.   

55.State some advantages of Java?
Platform independence is the key feature of Java during runtime. Syntax of java is similar to the popular object oriented languages such as C and C++. Java program can eliminate most of the bugs present in the program. Manual memory allocation and de allocation feature present in Java is automated.   

56.Explain about the security aspect of Java?
ava has some bugs in its applets. Java team stated that they have zero tolerance over security features and subsequent editions of Java are improving Bug free environment. Some of the features are overriding the runtime stack, disallowing the corruption of memory outside its own process, reading or writing on local files where it is actually forbidden to do these processes, etc.   

57.Explain about the interpreter in Java?
Machines should have Java interpreter for the Java byte code to get executed. Linking is a very easy process and this feature helps while developing applications. Java compiler which is available with software development kit is a bit slower in execution of scripts.

58.Explain about the performance aspects of Core Java?
Performance of interpreted byte codes is enough but it can be improved much more than that. Byte codes are translated into machine language within no time, this speed of execution can be achieved during application compiling time. JIT compilers are also present which compile the byte codes into native code.

59.Explain about the dynamic behavior of core java?
This language was designed to adapt the changing environment and behavior. New methods and instance variables can be added to the client side without any major changes happening at the client end. This function is very important for GUI builders, pluggable components, debuggers and object database.

60.Explain about Java SDK?
Java SDK is not so comfortable with people used to command line interpreter. IDEs include compilers, editors, debugging facilities, drag and drop techniques, etc. This compiler strives to generate hundreds of lines in code UI. This platform may become a universal platform.

61.What are the three best choices for development environment?
The three best choices for development environment include.
1) Java SDK and text editor can be a perfect choice.
2) Java SDK and a text editor which is built within the SDK.
3) Using IDE such as free Forte community edition.

62.Explain about Class in Java?
In Java every thing exists within a class. It defines the behavior of the class and its characteristics. Java applications and applets are built in the class. Rules present for class name are generous and some of the basic rules are names should start with a letter after that letter they can have any combination of letters and digits. It can contain names to any length.

63.explain about Java assignment statement?
After declaring a variable, it should be initialized explicitly. Uninitialized variable can never be used. To a declared variable you must assign a variable name on the left, equal sign and a java expression should have a appropriate value to the right.

64.Give the difference between the println method and sqrt method?
Println method operates on the object system.out and has the value which should be printed namely y. sqrt method is a static method. It does not operate on any object. It has the number stored in x for which the square toot should be found out.

65.Explain about strings in Java?
 Strings represent nothing but a string of characters. Java does not have any built in string type. It contains predefined class which can be called enough as a String. Instance of a string is called as a string. Much similar to many object oriented languages a + sign is used.

66.Explain the reason behind ending a program with a System.exit (0)?
The reason behind ending a program with System.exit (0) involves technicalities. When main method exits the new thread automatically does not end. The appearance of this thread is because of dialog box functionality. System.exit ends all the methods.

67.Explain about the dynamic behavior of core java?
This language was designed to adapt the changing environment and behavior. New methods and instance variables can be added to the client side without any major changes happening at the client end. This function is very important for GUI builders, pluggable components, debuggers and object database

68.Give the difference between the println method and sqrt method?
Println method operates on the object system.out and has the value which should be printed namely y. sqrt method is a static method. It does not operate on any object. It has the number stored in x for which the square toot should be found out.   

69.Explain about strings in Java?
Strings represent nothing but a string of characters. Java does not have any built in string type. It contains predefined class which can be called enough as a String. Instance of a string is called as a string. Much similar to many object oriented languages a + sign is used.   

70.Explain about inheritance hierarchies?
An inheritance hierarchy has a collection of all classes which fall under the main class. Inheritance chain defines the path from where all the sub classes originated and their relation ship. Controller normally handles user input. Inheritance hierarchy is very important in software modeling.   

71.Explain about the select method with an example?
Select part is useful in selecting text or part of the text. Arguments specified for the select command are the same as applicable to substring. First index is usually represents the start of the index. End of line makers are counted as one character. Example t.select (10,15)   

72.What is package-private ?
Package-private is a different name of default access specifier.

73.What is Class Loader in java ?
Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine on demand .
There are three types of class loaders. There are
Bootstrap class loader:
The bootstrap class loader loads the core Java libraries[5] located in the {JAVA_HOME}/lib directory
Extensions class loader:
The extensions class loader loads the code in the extensions directories {JAVA_HOME}/lib/ext directory
System Class  Path Loader:
The system class loader loads code found on java.class.path, which maps to the system CLASSPATH variable

74.What is the order of execution of Class Loader in java?
Java applications  involve three classloaders – Bootstrap, Extensions and System-Classpath classloaders
Bootstrap classloader is the parent of all classloaders ,extensions Classloader is the immediate child of Bootstrap classloader and System-Classpath classloader is the immediate child of Extensions classloader. Generally  Order of execution happens from sub-sequent children to parent.
So order of execution is starts from System-classpath-loader then extension then Bootstrap Loader.

75.What is differenence between ClassNotFoundException and NoClassDefFoundError ?
ClassNotFoundException is generated by a call to Class.forName() with a String that contains a class not available on the bundle's class path. For example when we are dynamically want to load the class using  Class.forName("oracle.jdbc.driver.OracleDriver"); if that class is not aviailable in runtion, it'll throw ClassNotFoundException
NoClassDefFoundError is thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class and that class or its dependancies are not available  in run time. For example if Class x extends Class y and Class y is extends  class Z .When class loader tries to load class x if any of the depenacies is missing it'll give

76.If we are using importing a class e.g java.util.ArrayList , and we are not using that class in side our program, does class loader will load the class?
No, it won't

77.Local variable, instance variable, method and object, amonng of these which one will store in heap and which one will store in stack?
local variable and method will store in stack
instance variable and object will store in heap

78.Emp e=new Employee(), where the "e" and "new Employee" will store?
"e" will store in stack and Emploee() ( or the object )  will store in heap.

79.Where we can can declare local variable ,where instance variable and where static variable?
Local : inside mehod, constructor, and block
instance: outside method, constructor and block
static: outside method, constructor and block

80.What are the default value of these variable?
Object reference, byte, short,int, boolean,char
Object reference null (not referencing any object)
byte, short, int, long 0
float, double 0.0
boolean false
char '\u0000'

81.Can I write main method as  private static void main(String a[])?
Ans: You won't get any compilation error, but JVM can not consider as main method. It will be a new method.

82.Can we write main method like this?
public static final void main(String ar[])
Ans: yes we can

83.Can we wtire a calss like?
public final abstract class A
Ans :no
Because, class is final means we can't extend that calss else where, but abstract means, it needs to be subclassed

84.Can I write one method like this
final static void methodA()
Ans: we can

85.What are similarities between abstact class and interface?
Ans Both we can't instantiate.
In which case we should use interface and which case abstact class?

86.Which lines are wrong?
 final static void methodA(){
         public int i=8;//1
         private int j=8;//2
         int x=6;//3
         static int y=9;//4
         final int z=8;//5
    }
Ans: only 3 and 5 are true and rest of lines is now allowed inside method.

87.What is the use of volatile modifier?
Ans:The volatile modifier applies only to instance variables .

88.What is transient modifiier in java?
Ans:Transient variable can not be serialized.

89.What is Java Serialization?
Ans:Serialization is a process to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again
For that we have to implements Serializable interface.

90.What is marker interface?
Ans:Interface which doesn't contain any method or variable called as marker interface. Exemple Serializable

91.What is Polymorphism?
It is a feature that allows one interface to be used for general class ofactions. The specific action is determined by the exact nature of the situation.In general polymorphism means one interface multiple methods Thismeans that it is possible to design a generic interface to a group of relatedactivities. This helps reduce complexity by allowing the same interface to beused to specify a general class of action. It is the compiler's job to selectthe specific action (that is method) as it applies to each situation.

92.How does Java implement polymorphism ?
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java). Polymorphism manifests itself in Java in the form of multiple methods having the same name.
In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods).
In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).

93.Explain the different forms of Polymorphism.
There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
Method overloading
Method overriding through inheritance
Method overriding through the Java interface

94.What is the difference between abstraction and encapsulation ?
Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it?s inside view, where the behavior of the abstraction is implemented.
Abstraction solves the problem in the design side while Encapsulation is the Implementation.
Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.

95.What are Objects ?
Everything in Java is an object. An object is a collection of data and actions that make up a programming entity. A 'car' object, for example, might have some data (i.e. 'speed,' 'direction,' 'lights on,' 'current fuel,' etc.) and some actions it can take ('turn right,' 'turn lights on,' 'accelerate,' etc.). Objects provide a number of advantages when programming; the include the ability to hide what's going on 'inside' the object from other programmers, which is useful for writing code that others can work with but not easily mess up. However, the biggest advantage to programming with objects is that objects simply 'make sense'; they form the nouns and verbs that you use to write the 'story' of your program.

96.What is meant by Object Oriented Programming ?
OOP is a method of programming in which programs are organised as cooperative collections of objects. Each object is an instance of a class and each class belong to a hierarchy.

97.What is an Instance ?
An instance has state, behaviour and identity. The structure and behaviour of similar classes are defined in their common class. An instance is also called as an object.

98.What is a Base Class ?
Base class is the most generalised class in a class structure. Most applications have such root classes. In Java, Object is the base class for all classes.

99.What is a Sub Class ?
Subclass is a class that inherits from one or more classes

100.What is a Super Class ?
Superclass is a class from which another class inherits.

101.What is a Constructor ?
Constructor is an operation that creates an object and/or initialises its state.
Constructor declarations look like method declarations,except that they use the name of the class and have no return type. For example, the class Bicycle has one constructor:
public Bicycle(int startCadence, int startSpeed, int startGear) {
   gear = startGear;
   cadence = startCadence;
   speed = startSpeed;
}

102.What is a Destructor ?
Destructor is an operation that frees the state of an object and/or destroys the object itself. In Java, there is no concept of destructors. Its taken care by the JVM using Garbage Collection.

103.What is meant by Binding ?
Binding denotes association of a name with a class.

104.What is meant by Static Binding ?
Static binding is a binding in which the class association is made during compile time. This is also called as Early binding.

105.What is meant by Dynamic Binding ?
Dynamic binding is a binding in which the class association is not made until the object is created at execution time. It is also called as Late binding.

106.Define Modularity ?
Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.

107.What is Colloboration ?
Colloboration is a process whereby several objects cooperate to provide some higher level behaviour.

108.In Java, How to make an object completely encapsulated ?
All the instance variables should be declared as private and public getter and setter methods should be provided for accessing the instance variables.

0 comments:

Post a Comment