100+ Core Java Interview Questions

Share Embed Donate


Short Description

java...

Description

2/17/14

100+ Core Java Interview Questions

beginnersbook.com Home Contact us JSP JSTL Build Website Internet Java Collections Java I/O SEO Tech Pages SharePoint WordPress C Tutorial OOPs Concepts

100+ Core Java Interview Questions by Chaitanya Singh in Java Q&A

Java – OOPs Interview questions Q) Three Principles of OOPS language? Inheritance Polymorphism Data Encapsulation Q) Java vs. C ++? Simple Multi-threaded Distributed Application Robust Security Complexities are removed (Pointers, Operator overloading, Multiple inheritance). Q) What is javac ? It produces the java byte code when *.java is given as input and it is the intermediate representation of your source code that contains instructions that the java interpreter will execute. Q) What all terms are related to OOPs? Class beginnersbook.com/2013/05/java-interview-questions/

1/25

2/17/14

100+ Core Java Interview Questions

Object Methods Inheritance Polymorphism Overriding Abstraction Encapsulation Interface Q) What is class? Class is nothing but a template, which describes the various properties and functions. Q) What is an object? Object has its own properties and functionality; also it’s an instance of the class. Q) How many times does the garbage collector calls the finalize() method for an object? The garbage collector calls the finalize() method Only once for an object. Q) What are two different ways to call garbage collector? System.gc() OR Runtime.getRuntime().gc(). Q) Can the Garbage Collection be forced by any means? No, its not possible. you cannot force garbage collection. you can call system.gc() methods for garbage collection but it does not guarantee that garbage collection would be done. Q) Abstract class? A class for which object can’t be instantiated/created, such class are called as Abstract class. Also a class, which is, generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Q) Multiple Inheritances? Inheriting more than one parent class. Java doesn’t supports multiple inheritances whereas c++ supports. Q) What is the method overriding? In inheritance, when a child class writes a method with the same name as method in super-class is called method overriding. Method call on the child class will execute the child class method not the super class method. There can be no object of an abstract class. Constructors or static methods cannot be declared as abstract. Q) Can this keyword be assigned null value? No, this keyword cannot have null values assigned to it. Q) What is a WeakHashMap? a) A hash table map with duplictate keys. b) A general purpose hash table-based implementation to better store. c) A hash table-based Map implementation with weak keys. beginnersbook.com/2013/05/java-interview-questions/

2/25

2/17/14

100+ Core Java Interview Questions

d) A list with weak references to objects. Ans is option (c). WeakHashMap is a hash table-based Map implementation with weak keys. Q) Which of the following lines allow main method to be executed by ClassLoader? a) public static String main(String a[]); b) protected static void main(String a[]); c) final public static void main(String a[]); d) public static void main(); e) private static void main(String a[]); f) public void main(String a[]); Ans is (c). In order for the ClassLoader to execute the main() method, it has to be declared atleast as public, static & void. Q) Which modifiers a method of local inner class can have? Only abstract or final keyword is allowed. Q) Do we need to implement any method of Serializable interface to make an object serializable? No.In order to make an object serializable we just need to implement the interface Serializable. We don’t need to implement any methods. Q) What is a transient variable? transient variables are not included in the process of serialization. They are not the part of the object’s serialized state. Variables which we don’t want to include in serialization are declared as transient. Q) Does a static nested class have access to the enclosing class’ non-static methods or instance variables? No. A static nested class doesn’t have access to the enclosing class’ non-static methods or instance variables. Q) Which modifiers can be applied to the inner class? public ,private , abstract, final, protected. Q) Polymorphism? In a class, 2 methods with same name having different number of arguments is called polymorphism. Is also called as function overloading. Q) Does Java support operator overloading? Operator overloading is not supported in Java. Q) Encapsulation? Group of Data & functions are said to be an Encapsulation with single entity. Objects should not be allowed to access the properties of class instead could have separate methods thru which the property can be accessed. Q) Interface? Interfaces are a collection of method prototypes, the implementation of which has to be done by a class that inherits it. When it is declared as public, any class can use the interface. Once an interface3 has been defined, any classes can implements that interface. Interfaces are java’s substitute for multiple inheritances. Interfaces can be extended. One interface can inherit another by use of keyword extends. When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the beginnersbook.com/2013/05/java-interview-questions/

3/25

2/17/14

100+ Core Java Interview Questions

interface chain.

Core Java – Interview Questions Q) Different Data types in Java. Byte – 8 bit

(are esp. useful when working with a stream of data from a network or a file).

Short – 16 bit Char – 16 bit Unicode Int

– 32 bit (whole number)

Float – 32 bit (real number) Long – 64 bit (Single precision) Double - 64 bit (double precision) Note: Any time you have an integer expression involving bytes, shorts, ints and literal numbers, the entire expression is promoted to int before the calculation is done. Q) What is Unicode? Java uses Unicode to represent the characters. Unicode defines a fully international character set that can represent all of the characters found in human languages. Q) What is Literals? A literal is a value that may be assigned to a primitive or string variable or passed as an argument to a method. Q) Dynamic Initialization? Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared. Q) What is Type casting in Java? To create a conversion between two incompatible types, you must use a cast. There are automatic casting and explicit casting. Q) Arrays? An array is to store the group of like-typed variables that are referred to by a common name. Q) Explain about BREAK stmt in java? In Java, the break stmt has 3 uses. First, it terminates a statement sequence in a switch statement. Second, it can be used to exit a loop Third, it can be used as “go to” keyword Q) What are Constructors? Constructors are special methods belonging to a class. These methods are basically used to do initialization of instance variables. They are automatically called whenever an instance of a class is created. Q)THIS keyword? beginnersbook.com/2013/05/java-interview-questions/

4/25

2/17/14

100+ Core Java Interview Questions

The THIS keyword is a reference to the current object which is automatically created. Q) Garbage collection in java? Since objects are dynamically allocated by using the new operator, java handles the de-allocation of the memory automatically when no references to an object exist for a long time is called garbage collection. Q) Use of finalize() method in java? FINALIZE () method is used to free the allocated resource. Q) Explain ways to pass the arguments in Java? In java, arguments can be passed in 2 ways, Pass by value – Changes made to the parameter of the subroutines have no effect on the argument used to call it. Pass by reference – Changes made to the parameter will affect the argument used to call the subroutine. Q) Explain SUPER in Java? First calls the superclass constructor. Second, is used to access a method of the superclass that has been hidden by a member of a subclass. A subclass can call a constructor method defined by its super class by using super (parameter-list). Super must always be the first statement. Q) What is a Object class? This is a special class defined by java; all other classes are subclasses of object class. Object class is superclass of all other classes. Object class has the following methods objectClone () – to creates a new object that is same as the object being cloned. boolean – determines whether one object is equal to another. finalize – called before an unused object is recycled. toString () – returns a string that describes the object. Q) What are Packages? Package is group of multiple classes under one name space. Q)What is the difference between import java.utilDate and java.util.* ? The star form may increase the compilation time – especially if you import several packages. However it doesn’t have any effect runtime performance. Q) Why can’t I do myArray.length () ? Arrays are just objects, right? Yes, the specification says that arrays are object references just like classes are. You can even invoke the methods of Object such as toString () and hashCode () on an array. However, length is a data item of an array and not a method. So you have to use myArray.length. Q) How can I put all my classes and resources into one file and run it? Use a JAR file. Put all the files in a JAR, then run the app like this: beginnersbook.com/2013/05/java-interview-questions/

5/25

2/17/14

100+ Core Java Interview Questions

Java -jar [-options] jarfile [args...] Q) Can I declare a data type inside loop in java? Any Data type declaration should not be inside the loop. Q) Advantage over jdk 1.0 vs. jdk 1.1 ? Jdk1.1 release consists of Java Unicode character to support the multiple language fonts, along with Event Handling, Java security, Java Beans, RMI, SQL are the major feature provided. Q) java.lang.* get imported by default. For using String and Exception classes, you don’t need explicitly to import this package. The major classes inside this package are Object class Data type wrapper classes Math class String class System and Runtime classes Thread classes Exception classes Process classes Class classes Q) Arrays can be defined in different ways. All ways are right. [code language="java"] int arr[] = null; int arr[][] = new int arr[][]; int [][] arr = new arr [][]; int [] arr [] = new arr[][];[/code] Q) What is static method means? When a member is declared as Static, it can be accessed before any objects of its class are created, and without references to any object. It allocates the memory once and uses the same until the end of the class. Note: It is illegal to refer to any instance variable inside of a static method. Q) Use of final keyword in Java? Final methods – mean methods cannot be override by any other method. Final variable – means constant, the value of the variable can’t be changed, its fixed. Final class – Means can’t be inherited to other class. This type of classes will be used when application required security or someone beginnersbook.com/2013/05/java-interview-questions/

6/25

2/17/14

100+ Core Java Interview Questions

don’t want that particular class.

Exception handling in Java – Interview Questions Q) Exceptions are defined in which java package? OR which package has definitions for all the exception classes? Java.lang.Exception This package contains definitions for Exceptions. Q) What is throw keyword in exception handling? throw keyword is used to throw the exception manually. While creating user defined exception you would be needing to use throw keyword. Q) Can static block throw exception? Yes, A static block can throw exceptions. It has its own limitations: It can throw only Runtime exception(Unchecked exceptions), In order to throw checked exceptions you can use a try-catch block inside it. Q) throw & throws statement? Throwing an exception, in its most basic form is simple. You need to do two things. First, you create an instance of an object that is a subclass of java.lang.Throwable. Next you use the throw keyword to actually throw the exception. If you write a method that might throw an exception (and this includes un-handled exceptions that are generated by other methods called from your method), then you must declare the possibility using a throws statement. Q) Different Exception types? Checked exceptions – describes problems that can arise in a correct program, typically difficulties with the environment such as user mistakes or I/O problems. These exceptions are not a programming error, rather more likely with the Environment behavior. Java.lang.Exception is the class used. Unchecked exception – Exception, which occurs at the runtime, is called Unchecked exception. Java.lang.RuntimeException class is used. Runtime exception describes the program bugs. Such exceptions arise from things like out-of-bounds a correctly coded program would avoid array access, Database connection, MalformedURLException, EOFException, NullPointerException, IllegalState Exception etc and normally this. Q) Interview questions about exception class – The Exceptions classes are derived from Throwable class. The structure is given below. Java.lang.Throwable class Java.lang.Exception (Checked Exception) Java.lang.RuntimeExceptions (Unchecked Exception). Java.lang.Error ArrayBoundOutOfException – Whenever an array is referenced outside its boundary. NumberFormatException – When we try Illegal operation with any data types. For e.g., performing arithmetic on String variable. NullPointerException – When the Dynamic Variable carries value as “null” during the condition will result in null pointer exception. ClassCastException – Attempting to use a reference as if it referred to an object of some class – but it doesn’t EmptyStackException – Tried to pop or peek from an empty stack IllegalStateException – A method was activated when the object was in a state that violates the method’s precondition. beginnersbook.com/2013/05/java-interview-questions/

7/25

2/17/14

100+ Core Java Interview Questions

NegativeArraysizeException – Allocating an array with a negative number of components IOException – An input or output error Q) finally block? Irrespective of success or failure of try/catch block, the finally block gets execute. Finally block will best utilized to close your open database connections, open files etc.

Java I/O Interview Questions Q) Write a Small program to read an input from command prompt ? [code language="java"] Public class ClassName{ public static void main(String a[]) try{ char ch = (char) system.in.read(); if (Character.isJavaIdentifiedPart(ch); System.out.println(“ is a Identifier”); if (Character.isJavaIdentifiedStart(ch); System.out.println(“can be start of Identifier”); }catch(Exception e){ System.out.println(e); } } }[/code] Points to remember: Math is a final class. Cannot be override. It can imported from java.lang.*. All the methods( ceil(), floor(), rint(), round(), random() ) in this class are static and they can be invoked automatically. An only double data type is the input for math methods. Q) List of classes under java.util. *? This package contains the basic classes, which form as a java’s data structure. Since java doesn’t support Structures, Unions, and Pointers as in c++, hence this package is used. Vector – is for growable array. It allows storing different objects of any type. StringTokenizer – Generating tokens for a given string based on delimiter. Stack – LIFO, FIFO Date - is depreciated in jdk 1.1, 1.2, use Calendar in-spite Calender – System data and calendar Enumeration – hasMoreElements(); nextElement() Hashtable – Key value pair. Q) Wrapper Classes? Vector and Stack classes allow operation only for object not for data types. Hence some of the data types are wrapped to convert them into object to put into vector. Such data type wrapper classes are Integer, Double, Float, Character etc. beginnersbook.com/2013/05/java-interview-questions/

8/25

2/17/14

100+ Core Java Interview Questions

For e.g. [code language="java"] Vector v = new Vector(); int I = 5; //this can’t be added to vector hence need to wrap Integer ii = new Integer(I); v.addElement(ii);[/code] Q) Different methods can operates on Vector are [code language="java"] v.elementAt(int); v.insertElementAt(object, int); removeElementAt(int); removeAllElements();[/code] Q) Hashtable ? Hashtable are used to store key and value pair. User need not to worry about whether the variable is stored rather we just need to know the key retrieve the corresponding “value”. Hashtable h1 – new Hashtable(); Methods are : [code language="java"] h1.put(“key”,”value”); h1.get(“key”); Sample program to find out the list of all keys from hastable. [code language="java"] Enumeration e = h1.keys(); While (e.hasMoreElements()) { object obj = e.nextElement(); h1.get(obj); }[/code] Go through all the Basic Arithmetic operators like (+, -, *, /, %, ++, --, += ). Boolean logical operators like (&, |, ^, ||, && ) The ? Operator (ternary operator). Shift operators (>>, <<, >>>). Very important. Q) How do I resize an array? You can't resize an array. Once an array is created, you will not be able to change the length of it. You can allocate a new array, copy the elements into the new array, and set the reference to the original array to point to the new array [code language="java"] ABC[] arr = new ABC[]; // Below I'm creating a new array with larger size XYZ[] newarr = new XYZ[5]; beginnersbook.com/2013/05/java-interview-questions/

9/25

2/17/14

100+ Core Java Interview Questions

System.arraycopy(arr, 0, newarr, 0, arr.length); arr = newarr;[/code] Q) What is a Java Bean? A JavaBean is a Java class that follows some simple conventions including conventions on the names of certain methods to get and set state called Introspection. Because it follows conventions, it can easily be processed by a software tool that connects Beans together at runtime. JavaBeans are reusable software components.

Applet Interview Questions Q) How do you do file I/O from an applet? Unsigned applets are simply not allowed to read or write files on the local file system . Unsigned applets can, however, read (but not write) non-class files bundled with your applet on the server, called resource files Q) What is container ? A component capable of holding another component is called as container. Container Panel Applet Window Frame Dialog Learning) 1. Flow Layout is default for panel. 2. Border Layout is default for Frames. Q) On Windows, generally frames are invisible, how to make it visible. ? [code language="java"] Frame f = new Frame(); f.setSize(300,200); //ht and width f.setVisible(true) ; // Frames appears [/code] Q) JFC – Java Foundation Class Swing AWT Java2D Drag and Drop Accessibility Learning) Listeners and Methods? ActionListerner - actionPerformed(); ItemListerner - itemStateChanged(); TextListener - textValueChanged(); FocusListener - focusLost(); & FocusGained(); beginnersbook.com/2013/05/java-interview-questions/

10/25

2/17/14

100+ Core Java Interview Questions

WindowListener windowActified(); windowDEactified(); windowIconified(); windowDeiconified(); windowClosed(); windowClosing(); windowOpened(); MouseMotionListener - mouseDragged(); & mouseMoved(); MouseListener - mousePressed(); mouseReleased(); mouseEntered(); mouseExited(); mouseClicked(); Learnings) parseInt – to convert string to int. getBytes – string to byte array Q) Applet Life cycle? Following stage of any applets life cycle, starts with init(), start(), paint(), stop() and destroy(). Q) showStatus() ?– To display the message at the bottom of the browser when applet is started. Q) What is the Event handling? Is irrespective of any component, if any action performed/done on Frame, Panel or on window, handling those actions are called Event Handling. Q) What is Adapter class? Adapter class is an abstract class. Advantage of adapter: To perform any window listener, we need to include all the methods used by the window listener whether we use those methods are not in our class like Interfaces whereas with adapter class, its sufficient to include only the methods required to override. Straight opposite to Interface. Q) Diaglog can be modal, non-modal dialog. Dialog d = new Dialog(this,”Title”,true) - 3rd parameter indicated whether dialog frame is modal or non-modal. Q) Handling keyboard events? [code language="java"] import java.awt.*, java.awt.event.*, java.applet.*; public class CN extend Applet implements KeyListener { String msg = “”: int X= 10, Y =20; public void init(){ addKeyListener(this); requestFocus(); } public void keyPressed(KeyEvent ke){ showStatus(“Key Down”); } public void keyReleased(KeyEvent ke){ showStatus(“Key UP”); } public void keyTyped(KeyEvent ke){ beginnersbook.com/2013/05/java-interview-questions/

11/25

2/17/14

100+ Core Java Interview Questions

msg += ke.getKeyChar(); repaint(); } public void paint(Graphics g){ g.drawString(msg,X,Y); } }[/code]

Java Multithreading Interview Questions Q) Thread? In concurrent programs, several independent activities happen at the same time. Java models this through an interface, Runnable that embodies generic activities and a class, Thread that is responsible for the independent execution of Runnable. Thread Life cycle: Starts with init(), start(), run(), stop() and destroy(). Learning) Other Thread methods 1. 2. 3. 4. 5. 6.

stop() kills the thread. (Different from Applet.stop().) sleep(ms): non-busy wait for ms milliseconds, then throws InterruptedExceptions. setPriority(int pr): lowest = 1, highest = 10 , normal =5 yield(): signals its willingness to give up CPU. Control transferred only when there is a ready thread of the same or higher priority. wait() vs. notify() suspend() vs. resume()

Q) Java Threads 1. interface Runnable 2. abstract class Thread Two different ways to implement threads Extends Thread class 1. create a subclass of Thread class 2. implement void run() method, which will be the main body of the thread. 3. initiated by start(), and terminates when run() ends. Implements Runnable interface 1. 2. 3. 4.

create a class implementing Runnable interface. create a Thread instance inside the class (with this as an argument). invoke start() method. initiated by creating the class instance, terminates when run() ends.

Q) Synchronization? I have good news and bad news for you. The bad news is that you can run into big problems when two or more threads share parameters. Recall that the threads run independently and re likely to interfere during complex operations. One has to enforce proper synchronization between threads. In Java, synchronized is a keyword applied to methods: public synchronized void someMethod() Each Java object has a lock. To execute synchronized code on an object, a thread must own the object's lock. When two threads execute code synchronized on the same object, only one of them acquires the lock and proceeds. The other is paused until the first beginnersbook.com/2013/05/java-interview-questions/

12/25

2/17/14

100+ Core Java Interview Questions

one releases the lock. Thanks to synchronization each thread has a chance to use the object with no meddling from the other thread. Learning) A thread that waits on an object is automatically woken up by other threads calling notifyAll() on the same object. wait() is efficient and consumes no CPU cycles. notify() is faster than notifyAll() but it can be dangerous when several threads wait on the same object. In practice, it is seldom used and I suggest you stick to the safer notifyAll(). If no result is available getResult() waits: [code language="java"] public synchronized Object getResult() throws InterruptedException { while (result == null) wait(); return result; }[/code]

Interview Questions related to Java Strings? Q) StringBuffer class ? An instance of this class represents a string that can be dynamically modified. A String buffer has a capacity, which is the maximumlength string it can represent without needing to allocate more memory. A string buffer can grow beyond this as necessary, so usually do not have worry about capacity. Different methods are [code language="java"] StringBuffer sb = new StringBuffer(“Planetasia”); sb.insert(3,”xyz”); // plaxyznetasia sb.append(“abc”); // plaxyznetasiaabc [/code] Q) Different methods operated on String? String s1 = “Planetasia”; String s2 = “bangalore”; int i = 3; s1.charAt(i); - will find the character at that position. s1.indexOf(“t”); - will return the position of “t” in the string “s1”. s1.lastIndexOf(“a”); - will return the position of “a” starting the index at the end. s1.equals(s2) – String s1 and s2 content will be compared, return true if they are equal. s1 == s2

- The reference of both the string will be compared.

s1.compareTo(s2) – will compare 2 strings and result three possible value 0

– if both the strings are equal.

>1

- if s1 is greater than s2

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF