34
What is meant by Object Oriented Programming? Ans: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. What is a Class? Ans:Class is a template for a set of objects that share a common structure and a common behaviour. What is an Object? Ans:Object is an instance of a class. It has state,behaviour and identity. It is also called as an instance of a class. What is an Instance? Ans: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. What do you mean by Patform independence? Ans:Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc). What is Byte code? Ans:Byte code is a set of instructions generated by the compiler. JVM executes the byte code. How does Java acheive platform independence? Ans:A Java source file on compilation produces an intermediary .class rather than a executable file. This .class file is interpreted by the JVM. Since JVM acts as an intermediary layer. What is a pointer and does Java support pointers? 1

Comprehensive Viva of Java

Embed Size (px)

Citation preview

Page 1: Comprehensive Viva of Java

What is meant by Object Oriented Programming?

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

What is a Class?

Ans:Class is a template for a set of objects that share a common structure and a common behaviour.

What is an Object?

Ans:Object is an instance of a class. It has state,behaviour and identity. It is also called as an instance of a class.

What is an Instance?

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

What do you mean by Patform independence?

Ans:Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).

What is Byte code?

Ans:Byte code is a set of instructions generated by the compiler. JVM executes the byte code.

How does Java acheive platform independence?Ans:A Java source file on compilation produces an intermediary .class rather than a executable file. This .class file is interpreted by the JVM. Since JVM acts as an intermediary layer.

What is a pointer and does Java support pointers?

Ans:Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn't support the usage of pointers.

What are the good programming practices for better memory management?

Ans:a. We shouldn't declare unwanted variables and objects. b. We should avoid declaring variables or instantiating objects inside loops.

1

Page 2: Comprehensive Viva of Java

c. When an object is not required, its reference should be nullified.d. We should minimize the usage of String object and SOP's.

What is meant by abstraction?

Ans:Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. Its the process of focussing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model.

What is meant by Encapsulation?

Ans:Encapsulation is the process of compartmentalising the elements of an abtraction that defines the structure and behaviour. Encapsulation helps to separate the contractual interface of an abstraction and implementation.

What is meant by Polymorphism?

Ans:Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behavior or value in a subclass, to something that was declared in a parent class.

What is meant by Inheritance? Ans:Inheritance is a relationship among classes, wherein one class shares the structure or behaviour defined in another class. This is called Single Inheritance. If a class shares the structure or behaviour from multiple classes, then it is called Multiple Inheritance. Inheritance defines "is-a" hierarchy among classes in which one subclass inherits from one or more generalised superclasses.

What is meant by static binding?

Ans:Static binding is a binding in which the class association is made during compile time. This is also called as Early binding.

What is meant by Dynamic binding?

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

Expain the meaning of each keyword of ” public static void main(String args[])?”

2

Page 3: Comprehensive Viva of Java

Ans: public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.

static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.

void: main does not return anything so the return type must be void

The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line.

Why Java doesn't support multiple inheritance?

Ans:When a class inherits from more than class, it will lead to the diamond problem - say A is the super class of B and C & D is a subclass of both B and C. D inherits properties of A from two different inheritance paths ie via both B & C. This leads to ambiguity and related problems, so multiple inheritance is not allowed in Java.

Is Java a pure object oriented language?

Ans:Java is a pure object oriented language. Except for the primitives everything else are objects in Java.

What is the difference between a constructor and a method?

Ans:A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

What is the purpose of garbage collection in Java, and when is it used?

Ans:The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.  

Describe synchronization in respect to multithreading.

Ans:With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without

3

Page 4: Comprehensive Viva of Java

synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.   Explain different way of using thread?

Ans:The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.

What is an Abstract Class?

Ans:Abstract class is a class that has no instances. An abstract class is written with the expectation that its concrete subclasses will add to its structure and behaviour, typically by implementing its abstract operations.

What are Interfaces ?

Ans:Java does not allow multiple inheritance for classes (ie. a subclass being the extension of more than one superclass). To tie elements of different classes together Java uses an interface. Interfaces are similar to abstract classes but all methods are abstract and all properties are static final. As an example, we will build a Working interface for the subclasses of Animal. Since this interface has the method called work(), that method must be defined in any class using the Working interface.

public interface Working

{

public void work();

}

When you create a class that uses an interface, you reference the interface with the reserved word implements Interface_list. Interface_list is one or more interfaces as multiple interfaces are allowed. Any class that implements an interface must include code for all methods in the interface. This ensures commonality between interfaced objects.

public class WorkingDog extends Dog implements Working

{

public WorkingDog(String nm)

{

super(nm); // builds ala parent

}

4

Page 5: Comprehensive Viva of Java

public void work() // this method specific to WorkingDog

{

speak();

System.out.println("I can herd sheep and cows");

}

}

Interfaces can be inherited (ie. you can have a sub-interface). As with classes the extends keyword is used. Multiple inheritance can be used with interfaces.

Why is an Interface be able to extend more than one Interface but a Class can't extend more than one Class?

Ans:Basically Java doesn't allow multiple inheritance, so a Class is restricted to extend only one Class. But an Interface is a pure abstraction model and doesn't have inheritance hierarchy like classes(do remember that the base class of all classes is Object). So an Interface is allowed to extend more than one Interface.What is the difference between an Interface and an Abstract class?

Ans:An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

What is the difference between a constructor and a method?

Ans:A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

What is a destructor?

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

How to pass an argument to main method?

5

Page 6: Comprehensive Viva of Java

Ans:You should pass the argument as a command line argument. Command line arguments are seprated by a space. The following is an example:

java Hello Tom Jerry

In the above command line Hello is the class, Tom is the first argument and Jerry is the second argument.

Why Java doesn’t support muliple inheritance?

Ans:When a class inherits from more than class, it will lead to inheritance path amibiguity (this is normally calledthe diamond problem). Say A is the super class of B and C & D is a subclass of both B and C. D inherits properties of A from two different inheritance paths ie via both B & C. This leads to ambiguity and related problems, so multiple inheritance is not allowed in Java.Q: What is the difference between static and non-static variables?

Or

What are class variables?

Or

What is static in java?

Or

What is a static method?

Ans: A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class. These are declared outside a class and stored in static memory. Class variables are mostly used for constants. Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesn’t apply to an object or even require that any objects of the class have been instantiated.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can’t override a static method with a non-static

6

Page 7: Comprehensive Viva of Java

method. In other words, you can’t change a static method into an instance method in a subclass.

Non-static variables take on unique values with each object instance.

What is a default constructor?

Ans:Default constructor is a no argument constructor which initialises the instance variables to their default values. This will be provided by the compiler at the time of compilation. Default constructor will be provided only when you don’t have any constructor defined.

Explain about “this” operator?

Ans:“this” is used to refer the currently executing object and it’s state. “this” is also used for chaining constructors and methods. 

Explain about “super” operator?

Ans:“super” is used to refer to the parent object of the currently running object. “super” is also to invoke super class methods and classes.

What is a package?

Ans:Package is a collection of related classes and interfaces. package declaration should be first statement in a java class.

What is the impact using a * during importing(for example import java.io.*;?

Ans:When a * is used in a import statement, it indicates that the classes used in the current source can be available in the imported package. Using slightly increases the compilation time but has no impact on the execution time.

What is meant by default access?

Ans:default access means the class,method,construtor or the variable can be accessed only within the package.

What is the purpose of declaring a variable as final?

Ans:A final variable's value can't be changed. final variables should be initialized before using them.

Can a final variable be declared inside a method?

Ans:No. Local variables cannot be declared as final.

What is the impact of declaring a method as final?

7

Page 8: Comprehensive Viva of Java

Ans:A method declared as final can't be overridden. A sub-class doesn't have the independence to provide different implementation to the method.

Can a abstract class be declared final?

Ans:Not possible. An abstract class without being inherited is of no use and a final class cannot be inherited. So if a abstract class is declared as final, it will result in compile time error.What will Math.abs() do?

Ans:It simply returns the absolute value of the value supplied to the method, i.e. gives you the same value. If you supply negative value it simply removes the sign.

What will Math.ceil() do?

Ans: method returns always double, which is not less than the supplied value. It returns next available whole number

What will Math.floor() do?

Ans: method returns always double, which is not greater than the supplied value.

What will Math.max() do?

Ans:max() method returns greater value out of the supplied values.

What will Math.min() do?

Ans:The min() method returns smaller value out of the supplied values.

What is the difference between final, finally and finalize? What do you understand by the java final keyword?

Or

What is final, finalize() and finally?

Or

What is finalize() method?

Or

What is the difference between final, finally and finalize?

Or

8

Page 9: Comprehensive Viva of Java

What does it mean that a class or member is final?

Ans: o final - declare constanto finally - handles exceptiono finalize - helps in garbage collection

Variables defined in an interface are implicitly final. A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.

What is the importance of == and equals() method with respect to String object?

Ans:”== “is used to check whether the references are of the same object..equals() is used to check whether the contents of the objects are the same.But with respect to strings, object refernce with same content will refer to the same object.

String str1="Hello";String str2="Hello";

(str1==str2) and str1.equals(str2) both will be true.

If you take the same example with Stringbuffer, the results would be different.Stringbuffer str1="Hello";Stringbuffer str2="Hello";str1.equals(str2) will be true. str1==str2 will be false.

What is Thread Priority ?

Ans:Priority is thread ranking. Some threads can either run for a longer timeslice or run more often (depending on the operating system). Peers (or equals) get the same time/number of runs. Higher priority threads interrupt lower priority ones. Priority is set from constants MIN_PRIORITY (currently 1) to MAX_PRIORITY (currently 10) using the setPriority(int) method. NORM_PRIORITY is the midrange value (currently 5). These are defined in the Thread class.What are the two ways to create a new thread?

9

Page 10: Comprehensive Viva of Java

Ans: a)Extend the Thread class and override the run() method. b)Implement the Runnable interface and implement the run() method.

What is the difference between sleep() and yield()?

Ans:When a Thread calls the sleep() method, it will return to its waiting state. When a Thread calls the yield() method, it returns to the ready state.

What is a Daemon Thread?

Ans:Daemon is a low priority thread which runs in the backgrouund.

What does the start() method of Thread do?

Ans:The thread's start() method puts the thread in ready state and makes the thread eligible to run. start() method automatically calls the run () method.

What is a Monitor?

Ans:A monitor is an object which contains some synchronized code in it.

What is the difference between a Choice and a List?

Ans:A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.

Name few LayoutManagers in Java.

Ans:1)Flow Layout Manager2)Grid Layout Manager3)Border Layout Manager4)Box Layout Manager5)Card Layout Manager6)GridBag Layout Manager

What are two steps in Garbage Collection?

Ans:1. Detection of garbage collectible objects and marking them for garbage collection. 2. Freeing the memory of objects marked for GC.

When is the finalize() called?

Ans:finalize() method is called by the GC just before releasing the object's memory. It is normally advised to release resources held by the object in finalize() method.

10

Page 11: Comprehensive Viva of Java

What is an Applet?

Ans:Applet is a java program which is included in a html page and executes in java enabled client browser. Applets are used for creating dynamic and interactive web applications.

What is the difference between an Applet and a Java Application?

Ans:The following are the major differences between an Applet and an Application:a. Applets execute within a java enabled browser but an application is a standalone Java program outside of a browser. Both require a JVM (Java Virtual Machine). b. Application requires main() method to trigger execution but applets doesn't need a main() method. Applets use the init(),start(),stop() and destroy() methods for their life cycle. c. Applets typically use a fairly restrictive security policy. In a standalone application, however, the security policy is usually more relaxed.

What happens when an applet is loaded?

Ans:The following sequence happens when an applet is loaded: a) An instance of the applet's controlling class (an Applet subclass) is created. b) The applet initializes itself. c) The applet starts running.

What are the restrictions imposed on an applet?

Ans:Due to Security reasons, the following restriction are imposed on applets: a. An applet cannot load libraries or define native methods. b. It cannot ordinarily read or write files on the host that's executing it. c. It cannot make network connections except to the host that it came from. d. It cannot start any program on the host that's executing it. e. It cannot read certain system properties.

Q:State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.

Ans:public : Public class is visible in other packages, field is visible everywhere (class must be public too)private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.protected : Is available to all classes in the same package and also

11

Page 12: Comprehensive Viva of Java

available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package. What is mean by Static?

Ans:Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass. What is mean by final?

Ans:A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

Q:What are Checked and UnChecked Exception?

Ans:A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch theexception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be. What is Overriding?

Ans:When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from

12

Page 13: Comprehensive Viva of Java

superclass. Methods may be overridden to be more public, not more private.  want to print "Hello" even before main is executed. How will you acheive that?

Ans:Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main method.

What are different types of inner classes?

Ans:Nested top-level classes, Member classes, Local classes, Anonymous classes

Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement amore publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?

13

Page 14: Comprehensive Viva of Java

Ans:No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage. What are Wrapper classes?

Ans:Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc.

What are Runtime exceptions?

Ans: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. What is the difference between error and an exception?

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

What is the difference between throw and throws?

Ans: throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions. throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throws IOException,MyException{}

What is the importance of finally block in exception handling?

Ans:Finally block will be executed whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally block will be executed. Finally is used to free up resources like database connections, IO handles, etc.

If I write System.exit (0); at the end of the try block, will the finally block still execute?

14

Page 15: Comprehensive Viva of Java

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

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?When should you use which approach?Ans:In the first approach as a programmer of the method, you urself 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. What is Synchronization?

Ans:With respect to multithreading, synchronization is the capability to controlthe 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.

What are synchronized methods and synchronized statements?

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

Does garbage collection guarantee that a program will not run out of memory?

Ans: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.What is the difference between paint(), repaint() and update() methods within an applet which contains images?

15

Page 16: Comprehensive Viva of Java

Ans:paint : is only called when the applet is displayed for the first time, or when part of the applet window has to be redisplayed after it was hidden. repaint : is used to display the next image in a continuous loop by calling the update method. update : you should be aware that, if you do not implement it yourself, there is a standard update method that does the following : it will reset the applet window to the current background color (i.e. it will erase the current image) it will call paint to construct the new image

What is the difference between a while statement and a do statement?

Ans: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. Explain Java Collections Framework?

Ans:Java Collections Framework provides a well designed set of interfaces and classes that support operations on a collections of objects.

Explain Iterator Interface.

Ans:An Iterator is similar to the Enumeration interface.With the Iterator interface methods, you can traverse a collection from start to end and safely remove elements from the underlying Collection. The iterator() method generally used in query operations.Basic methods:iterator.remove();iterator.hasNext();iterator.next();

Explain Enumeration Interface.

Ans:The Enumeration interface allows you to iterate through all the elements of a collection. Iterating through an Enumeration is similar to iterating through an Iterator. However, there is no removal support with Enumeration.Basic methods:boolean hasMoreElements();Object nextElement();

What is the difference between Enumeration and Iterator interface?

Ans:The Enumeration interface allows you to iterate through all the elements of a collection. Iterating through an Enumeration is similar to iterating through an Iterator. However, there is no removal support with Enumeration.

16

Page 17: Comprehensive Viva of Java

What is reflection API? How are they implemented?

Ans: Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method.

What is the difference between ArrayList and LinkedList?

Ans:The ArrayList Class implements java.util.List interface and uses array for storage. An array storage's are generally faster but we cannot insert and delete entries in middle of the list.To achieve this kind of addition and deletion requires a new array constructed. You can access any element at randomly.

The LinkedList Class implements java.util.List interface and uses linked list for storage.A linked list allow elements to be added, removed from the collection at any location in the container by ordering the elements.With this implementation

What is JDBC?

Ans:JDBC is a layer of abstraction that allows users to choose between databases. JDBC allows you to write database applications in Java without having to concern yourself with the underlying details of a particular database

How many types of JDBC Drivers are present and what are they?

Ans:There are 4 types of JDBC Drivers Type 1: JDBC-ODBC Bridge Driver Type 2: Native API Partly Java Driver Type 3: Network protocol Driver Type 4: JDBC Net pure Java Driver

What are the steps in the JDBC connection?

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

17

Page 18: Comprehensive Viva of Java

Statement stmt = Connection.Statement(\"select * from TABLE NAME\");

Step 4 : Exceute the query :

stmt.exceuteUpdate();

Which statement throws ClassNotFoundException in SQL code block? and why? Ans:Class.forName("") method throws ClassNotFoundException. This exception is thrown when the JVM is not able to find the class in the classpath.

What do mean by Connection pooling?

Ans:Opening and closing of database connections is a costly excercise. So a pool of database connections is obtained at start up by the application server and maintained in a pool. When there is a request for a connection from the application, the application server gives the connection from the pool and when closed by the application is returned back to the pool. Min and max size of the connection pool is configurable. This technique provides better handling of database connectivity

How does a try statement determine which catch clause should be used to handle an exception?

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

What method must be implemented by all threads?

Ans:All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.

Is Empty .java file a valid source file?

Ans:Yes, an empty .java file is a perfectly valid source file. Is main a keyword in Java?

Ans:No, main is not a keyword in Java.  What happens if you dont initialize an instance variable of any of the primitive types in Java?

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

18

Page 19: Comprehensive Viva of Java

 What will be the initial value of an object reference which is defined as an instance variable?

Ans: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 NullPointerExceptions everywhere you try to use such default initialized references. What are the different scopes for Java variables?

Ans: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 accessbile only during the course of method excecution. 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. What will be the output of the following statement?System.out.println ("1" + 3);

Ans:It will print 13. What will be the default values of all the elements of an array defined as an instance variable?

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

19

Page 20: Comprehensive Viva of Java

/*swap two variables without using a third variable in c language*/

#include<stdio.h>#include<conio.h>void main(){

int a=5,b=10;clrscr();printf("Values before swaping are:");printf("a=%d b=%d",a,b);a=a+b;b=a-b;a=a-b;printf("\nValues after swaping are:");printf("a=%d b=%d",a,b);getch();

}

Output:

Values before swaping are:a=5 b=10Values after swaping are:a=10 b=5

20

Page 21: Comprehensive Viva of Java

//swap two variables without using a third variable in //c++

#include<iostream.h>#include<conio.h>void main(){

int a=5,b=10;clrscr();cout<<"Values before swaping are:";cout<<"a="<<a<<" b="<<b;a=a+b;b=a-b;a=a-b;cout<<"\nValues after swaping are:";cout<<"a="<<a<<" b="<<b;getch();

}

Output:

Values before swaping are:a=5 b=10Values after swaping are:a=10 b=5

21

Page 22: Comprehensive Viva of Java

//swap two variables without using a third variable in //Java

class Swap{

public static void main (String[] args){

int a=5,b=10;System.out.println("Value before swaping are:");System.out.println("a="+a+" b="+b);a=a+b;b=a-b;a=a-b;System.out.println("Value after swaping are:");System.out.println("a="+a+" b="+b);

}}

Output:

22

Page 23: Comprehensive Viva of Java

//swap two variables without using a third variable in //c#

using System;

class Swap{

public static void Main(string []args){

int a=5,b=10;Console.WriteLine("Values before swaping are:");Console.WriteLine("a="+a+" b="+b);a=a+b;b=a-b;a=a-b;Console.WriteLine("Values after swaping are:");Console.WriteLine("a="+a+" b="+b);

}}

Output:

23

Page 24: Comprehensive Viva of Java

INDEX

Topic Remarks

What is meant by Object Oriented Programming?

What is a Class? What is an Object? What is an Instance? What do you mean by Patform independence?

What is Byte code?

How does Java acheive platform independence?

What is a pointer and does Java support pointers?

What are the good programming practices for better memory management?

What is meant by abstraction?

What is meant by Encapsulation?

What is meant by Polymorphism?

What is meant by Inheritance?

What is meant by static binding?

What is meant by Dynamic binding?

Expain the meaning of each keyword of ” public static void main(String args[])?”

Why Java doesn't support multiple inheritance?

Is Java a pure object oriented language?

What is the difference between a constructor and a method? What is the purpose of garbage collection in Java, and when is it used?Explain different way of using thread?

What is an Abstract Class?

24

Page 25: Comprehensive Viva of Java

What are Interfaces ?Why is an Interface be able to extend more than one Interface but a Class can't extend more than one Class?

What is the difference between an Interface and an Abstract class?

What is the difference between a constructor and a method?

What is a destructor?

How to pass an argument to main method?

Why Java doesn’t support muliple inheritance?

Q: What is the difference between static and non-static variables?

Or

What is a default constructor?Explain about “this” operator?

Explain about “super” operator?

What is a package?

What is the impact using a * during importing(for example import java.io.*;?

What is meant by default access?

What is the purpose of declaring a variable as final?

Can a final variable be declared inside a method?

What is the impact of declaring a method as final?

Can a abstract class be declared final?

What will Math.abs() do? What will Math.ceil() do? What will Math.floor() do?

What will Math.max() do? What will Math.min() do?

What is the difference between final, finally and finalize? What do you understand by the java final keyword?

25

Page 26: Comprehensive Viva of Java

What is the importance of == and equals() method with respect to String object?

What is Thread Priority ?

What are the two ways to create a new thread?

What is the difference between sleep() and yield()?

What does the start() method of Thread do?

What is an Applet? What is the difference between an Applet and a Java Application?

What happens when an applet is loaded?

What are Runtime exceptions?

What is the difference between error and an exception?

What is Synchronization?What is JDBC?

How many types of JDBC Drivers are present and what are they?

Which statement throws ClassNotFoundException in SQL code block? and why?What will be the default values of all the elements of an array defined as an instance variable?

/*swap two variables without using a third variable in c language*/

//swap two variables without using a third variable in //c++

//swap two variables without using a third variable in //Java

//swap two variables without using a third variable in //c#

Comprehensive VIVA-VOICE

26

Page 27: Comprehensive Viva of Java

For

JAVA

Topic JAVA TERMS

Submitted To: Submitted By:

Miss. Manpreet Kaur Richa Aggarwal MCA 5th (B)613210800

LOVELY INSTITUTE OF MANAGEMENT

27