Java Interview questions and answers
Yahoo | ||||
1. Different between protected and private? · Private Access Modifier – Private: o Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.o Private access modifier is the most restrictive access level. Class and interfaces cannot be private.o Variables that are declared private can be accessed outside the class if public getter methods are present in the class.· Protected Access Modifier – Protected: o Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.o The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in an interface cannot be declared protected. o Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.2. Write an N factorial Program? · Using Recursion: publicint fact(int n){ if(n==1) return 1; else return n * fact(n-1); } · Using Non Recursion: publicint fact(int n){ for(int i=n-1;i>=1;i--) n*=i; return n; }fact(5); 3. Write a program to evaluate area of the circle? · class CircleArea{ public static void main(String[] args){ int r=0; try{ BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Radius of Circle : "); r = Integer.parseInt(br1.readLine()); double area = java.lang.Math.PI*r*r; System.out.println("Area of Circle : "+area); double perimeter =2*java.lang.Math.PI*r ; System.out.println("Perimeter of Circle : "+perimeter); } catch(Exception e){ System.out.println("Error : "+e); } } } 4. Puzzle on 3Litre and 5Litre and a pool of water. How can we measure 4lt using those buckets? (in 3 possible ways) · Solution Step 1:- Fill 5 Littre Jug completely 5 Littre Jug 3 Littre Jug · Solution Step 2:- Pour into 3 Littre Jug until 3 Littre not completes. Now there is 2 Littre water in 5 Littre Jug. Note 5 Littre JUG now has 2 Litters of water 5 Littre Jug 3 Littre Jug · Solution Step 3:- Empty 3 Littre JUG 5 Littre Jug 3 Littre Jug · Solution Step 4:- Pour 2 Littre from 5 Littre JUG into 3 Littre JUG. 5 Littre Jug 3 Littre Jug · Solution Step 5:- Fill 5 Littre JUG completely 5 Littre Jug 3 Littre Jug · Solution Step 6:- Now 3 Littre JUG has only 1 Littre capacity left. Pour water from 5 Littre JUG into 3 Littre JUG, until 3 Littre JUG is completely full. That will leave 4 Littre water in 5 Littre JUG. Problem solved 5 Littre Jug 3 Littre Jug · 5. Regular Expression for searching a pattern in string? · String Str = new String("Welcome to Madhu's blog"); System.out.println (Str.matches ("Welcome (.*)")); 6. Have you ever worked with XML and XSL? · I answered in a way that I have worked in my previous company like: There was a client requirement to format the XML in a tabular Format. And I have coded the XSL for the XML in a way that when he opens the XML, it will look in a tabular format. |
1. Write Fibonacci series program? · publicclass Fibonacci { publicstaticlong fib(int n) { if (n <= 1) return n; elsereturnfib(n-1) + fib(n-2); } publicstaticvoid main(String[] args) { int N = 10; for (int i = 0; i <= N; i++) System.out.println(i + ": " + fib(i)); } } 2. Write a divide by zero error handle exception public class Exceptionjava { public static void main(String[] args) { division(100, 0); } public static void division(int numerator, int denominator) { try { int average = numerator / denominator; System.out.println("Average : " + average); } catch (Exception ex) { System.out.println("Divide" + ex.getMessage() + "Exception" + "\n" + "Please check the denominator"); } } } |
1. Performance issues in your previous project 2. Collection – Hash map used in your project 3. Singleton usage? 4. Hibernate usage? 5. Marge 5 text files to 1 text file. 6. Avoid multiple request comes from form submit. 7. Explain about MVC in your project |
1. What is auto-boxing? · Java provides equivalent class types for primitive types. int - Integer double - Double etc... These classes are called wrapper classes, because they are wrapping the primitive values. Before java 1.5 to wrap a primitive value there are workarounds. From java 1.5 it is automated. That is why this is called auto-boxing. from java 1.5 we can write Integer i=10; Double d=10.5; you don't need to write any object creation code Example: Double d=new double(); 2. If already there are primitive types why wrapper classes like Integer are needed? · Primitive types can’t be stored in any of the Collection classes; for the methods who accept only object to work on; 3. Considering phone as a class what will be the methods and what will be instance variables? · public methods – makingCall, receivingCall; private methods – callWaiting; variables – caller / person; 4. What access modifier to use for the caller in the above stated scenario? · private – to prevent the data (person/caller) from modified from outside 5. Difference between protected and default access modifier? · In different package protected will be available through only inheritance with default not 6. What do you understand of final? · final method – can’t be overridden, final class – can’t be sub-classed, final variable – treated as final, once assigned the value can never be changed 7. What is the difference between static and final variables/ constants? · both are treated as constant; static is called without any object and to final variable object is needed · public class MyFactorial { public intcalculateFactorial (int n) throws Exception { int result = 1; if (n < 0) { throw new Exception("Please choose a number more than 1"); } else if (n == 0) { result = 1; } else { for (int i = 2; i <= n; i++) { result = result * i; } } return result; } public static void main(String[] args) { MyFactorial f = new MyFactorial(); try { intval = f.calculateFactorial(4); System.out.println("Result : " + val); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } } } |
1. Explain the OOPs Concepts? · Java language is developed using object oriented programming (OOP) concept as its platform. This object oriented programming language concept organizes data into different classes providing the data proper hierarchy through inheritance mode. There are four basic principles defined under the OOP concept in Java Abstraction Principle, Encapsulation Principle, Inheritance Principle, and Polymorphism Principle. 2. Write a program to evaluate area of the circle? · class CircleArea{ public static void main(String[] args){ int r=0; try{ BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Radius of Circle : "); r = Integer.parseInt(br1.readLine()); double area = java.lang.Math.PI*r*r; System.out.println("Area of Circle : "+area); double perimeter =2*java.lang.Math.PI*r ; System.out.println("Perimeter of Circle : "+perimeter); } catch(Exception e){ System.out.println("Error : "+e); } } } 3. Difference between public and protected? · Public variables are variables that are visible to all classes. · Private variables are variables that are visible only to the class to which they belong. · Protected variables are variables that are visible only to the class to which they belong, and any subclasses. 4. Difference between Abstraction and Encapsulation?· Data Abstraction - Is the separation of a data type's logical properties from its implementation. To hide the irrelevant details of the computer's view of data from our own, we use data abstraction to create another view. · Data Encapsulation - The separation of the representation of data from the application that use the data at a logical level; a programming language feature that enforces information hiding. The physical representation of the data remains hidden. Data hiding is a form of encapsulation in which we define access to data as a responsibility. So all data hiding is encapsulation, but not all encapsulation is data hiding. 5. Write an N factorial Program? · Using Recursion: publicint fact(int n){ if(n==1) return 1; else return n * fact(n-1); } · Using Non Recursion: publicint fact(int n){ for(int i=n-1;i>=1;i--) n*=i; return n; }fact(5); 6. Usage of static keyword at field and method level? · Basically static means that there will only be only one instance of that object (the object that is declared static) in the class. If an object is not declared static a new copy of that object is made for every instance of the class that is initialized. Another thing about static objects is that you can call them directly without having to initialize the class at all, which is why if you declare the function main as static then java does not have to initialize the object at all to access the entry point (main function). 7. Puzzle on 3Litre and 5Litre and a pool of water. How can we measure 4lt using those buckets? (in 3 possible ways) · Solution Step 1:- Fill 5 Littre Jug completely 5 Littre Jug 3 Littre Jug · Solution Step 2:- Pour into 3 Littre Jug until 3 Littre not completes. Now there is 2 Littre water in 5 Littre Jug. Note 5 Littre JUG now has 2 Litters of water 5 Littre Jug 3 Littre Jug · Solution Step 3:- Empty 3 Littre JUG 5 Littre Jug 3 Littre Jug · Solution Step 4:- Pour 2 Littre from 5 Littre JUG into 3 Littre JUG. 5 Littre Jug 3 Littre Jug · Solution Step 5:- Fill 5 Littre JUG completely 5 Littre Jug 3 Littre Jug · Solution Step 6:- Now 3 Littre JUG has only 1 Littre capacity left. Pour water from 5 Littre JUG into 3 Littre JUG, until 3 Littre JUG is completely full. That will leave 4 Littre water in 5 Littre JUG. Problem solved 5 Littre Jug 3 Littre Jug 8. Regular Expression for searching a pattern in string? · If str1 is pattern str.matches(str1) 9. Have you ever worked with XML and XSL? · I answered in a way that I have worked in my previous company like: There was a client requirement to format the XML in a tabular Format. And I have coded the XSL for the XML in a way that when he opens the XML, it will look in a tabular format. |
1. Write a class with multiplication and division methods by passing two integers? · Class A{ int mul(int I,int j){ Return i*j; } int div (int I ,int j){} //code } 2. In the class asked about pass by reference? · Class A{ Int I,j; int mul(A a){ Return a.i*a.j } } 3. Write a program for factorial numbers? · Class A{ Public static void main (string [] args){ Fact(n) } Fact(int n){ If(n==1){ Return 1; }else{ Return n*Fact(n-1); } } 4. Regular Expression · String Str = new String("Welcome to Madhu's Blog"); System.out.println (Str.matches ("Welcome (.*)")); 5. Static method, variable… why static method? · Static methods use no instance variables of any object of the class they are defined in. If you define a method to be static, you will be given a rude message by the compiler if you try to access any instance variables. You can access static variables, but except for constants, this is unusual. Static methods typically take all those data from parameters and compute something from those parameters, with no reference to variables. This is typical of methods which do some kind of generic calculation. A good example of this is the many utility methods in the predefined Math class. Access method directly without instantiating class 6. Puzzle 3l and 5 l get 4l · Solution Step 1 :- Fill 5 Litre Jug completely 5 Litre Jug 3 Litre Jug · Solution Step 2:- Pour into 3 Litre Jug until 3 Litre not complete. Now there is 2 Litre water in 5 Litre Jug. Note 5 Litre JUG now has 2 Litres of water 5 Litre Jug 3 Litre Jug · Solution Step 3:- Empty 3 Litre JUG 5 Litre Jug 3 Litre Jug · Solution Step 4:- Pour 2 Litre from 5 Litre JUG into 3 Litres JUG. 5 Litre Jug 3 Litre Jug · Solution Step 5:- Fill 5 Litre JUG completely 5 Litre Jug 3 Litre Jug · Solution Step 6:- Now 3 Litre JUG has only 1 Litre capacity left. Pour water from 5 Litre JUG into 3 Litre JUG, until 3 Litre JUG is completely full. That will leave 4 Litre water in 5 Litre JUG. Problem solved 5 Litre Jug 3 Litre Jug |
1. Tell me about your self · Explained my experience and technologies I know and worked and roles and responsibilities. 2. Explain about any of your 1 project · Explained a project 3. Explain oops concepts · Java language is developed using object oriented programming (OOP) concept as its platform. This object oriented programming language concept organizes data into different classes providing the data proper hierarchy through inheritance mode. There are four basic principles defined under the OOP concept in Java Abstraction Principle, Encapsulation Principle, Inheritance Principle, and Polymorphism Principle. 4. Difference between abstract and Interface · Abstract: An abstract class can have instance methods that implement a default behavior An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods · Interface: An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. All public members and no implementation 5. Explain serialization and how do you implement in Java · Serialization means persisting objects in java. If you want to save the state of the object and want to rebuild the state later (may be in another JVM) serialization can be used. Note that the properties of an object are only going to be saved. If you want to resurrect the object again you should have the class file, because the member variables only will be stored and not the member functions. Example: ObjectInputStream oos = new ObjectInputStream(new FileInputStream( new File("o.ser")) ) ; SerializationSample SS = (SearializationSample) oos.readObject(); The Serializable is a marker interface which marks that your class is serializable. Marker interface means that it is just an empty interface and using that interface will notify the JVM that this class can be made serializable. 6. Explain synchronization and why we use synchronization · Synchronization in Java is an important concept since Java is a multi-threaded language where multiple threads run in parallel to complete program execution. In multi-threaded environment synchronization of java object or synchronization of java class becomes extremely important. Synchronization in Java is possible by using java keyword "synchronized" and "volatile”. Concurrent access of shared objects in Java introduces to kind of errors: thread interference and memory consistency errors and to avoid these errors you need to properly synchronize your java object to allow mutual exclusive access of critical section to two threads. · If your code is executing in multi-threaded environment you need synchronization for objects which are shared among multiple threads to avoid any corruption of state or any kind of unexpected behavior. Synchronization in Java will only be needed if shared object is mutable. If your shared object is read only or immutable object you don't need synchronization despite running multiple threads. Same is true with what threads are doing with object if all the threads are only reading value then you don't require synchronization in java. JVM guarantees that Java synchronized code will only be executed by one thread at a time. 7. Explain Design Patterns with some examples (Singleton and factory design pattern) · Singleton Pattern This is one of the most commonly used patterns. There are some instances in the application where we have to use just one instance of a particular class. · Factory Pattern we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern 8. Explain XML and how do your parse XML file in java · I have explained about JAXP, SAX and dom. Parsing program using SAX parser. 9. Explain XSL and why do you use XSL and for what · XSL is a language for expressing style sheets. An XSL style sheet is, like with CSS, a file that describes how to display an XML document of a given type. XSL shares the functionality and is compatible with CSS2 (although it uses a different syntax). It also adds: o A transformation language for XML documents: XSLT. Originally intended to perform complex styling operations, like the generation of tables of contents and indexes, it is now used as a general purpose XML processing language. XSLT is thus widely used for purposes other than XSL, like generating HTML web pages from XML data. o Advanced styling features, expressed by an XML document type which defines a set of elements called Formatting Objects, and attributes (in part borrowed from CSS2 properties and adding more complex ones. 10. Write an XSL to find a value of a given element in XML. <employees> <employee> <firstname></firstname> <lastname></lastname> </employee> </employees> 11. Explain for tags in XSL o Extensible Style sheet Language (XSL) is a way to add styles to XML and other marked up text. 12. Explain Regular Expression and few characters in it
13. Write an Regular Expression for Email ID and IP Address Email ID: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$ IP Address: "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; 14. Explain some Unix commands o Contents cat --- for creating and displaying short files chmod --- change permissions cd --- change directory cp --- for copying files date --- display date echo --- echo argument ftp --- connect to a remote machine to download or upload files grep --- search file head --- display first part of file ls --- see what files you have lpr --- standard print command (see also print ) more --- use to read files mkdir --- create directory mv --- for moving and renaming files ncftp --- especially good for downloading files via anonymous ftp. print --- custom print command (see also lpr ) pwd --- find out what directory you are in rm --- remove a file rmdir --- remove directory rsh --- remote shell setenv --- set an environment variable sort --- sort file tail --- display last part of file tar --- create an archive, add or extract files telnet --- log in to another machine wc --- count characters, words, lines 15. Explain algorithm by using 2 pointers which finds middle term o Array = [1,2,3,4,5,6,7,8,9,10] o 1 pointer: i = i+1; o 2 pointer: j = j+2; “i” reached middle term when “J” reached end of the term 16. Explain Collection Framework · Java provides the Collections Framework. In the Collection Framework, a collection represents the group of the objects. And a collection framework is the unified architecture that represents and manipulates collections. The collection framework provides a standard common programming interface to many of the most common abstraction without burdening the programmer with many procedures and interfaces. It provides a system for organizing and handling collections. This framework is based on: o Interfaces that categorize common collection types. o Classes which proves implementations of the Interfaces. o Algorithms which prove data and behaviors need when using collections i.e. search, sort, iterate etc. Following is the hierarchical representation for the relationship of all four interfaces of the collection framework which illustrates the whole implementation of the framework. During the designing of a software (application) it need to be remember the following relationship of the four basic interfaces of the framework are as follows: o The Collection interface which is the collection of objects. That permits the duplication of the value or objects. o Set is the interface of the collections framework which extends the Collection but forbids duplicates. o Another interface is the List which also extends the Collection. It allows the duplicates objects on different position because it introduces the positional indexing. o And Map is also an interface of the collection framework which extends neither Set nor Collection. 17. Difference between Hash Map and Map · Map is Interface and Hash map is class that implements that 18. Difference enumeration and iterator · Functionalities of both Iterator & Enumeration interfaces are similar that means both generates a series of all elements of the object which is to have its values iterated that can be traversed one at a time using next () method in case of Iterator and nextElement() method in case of Enumeration. The more powerful newer interface Iterator takes place of the old interface Enumeration in the Java Collections Framework Differences: (a) Iterators allows to safe removal of elements from the collection during the iteration by using remove method of Iterator (not by collection's remove method). Enumeration does not have remove method. Iterators are fail-fast. I.e. when one thread changes the collection by add / remove operations , while another thread is traversing it through an Iterator using hasNext() or next() method, the iterator fails quickly by throwing ConcurrentModificationException . The fail-fast behavior of iterators can be used only to detect bugs. The Enumerations returned by the methods of classes like Hash table, Vector are not fail-fast that is achieved by synchronizing the block of code inside the nextElement() method that locks the current Vector object which costs lots of time. Enumerator interface has been superseded by the Iterator interface in Collections Framework. However, not all libraries / classes like ZipFile , DriverManager , etc.. supports the Iterator interface. Some of the classes that support these interfaces are as follows. Iterators can be used with ArrayList , HashMap , Hashtable , HashSet ,CopyOnWriteArraySet, etc.. Enumeration can be used with Vector , Hashtable , Dictionary, ConcurrentHashMap , ZipFile , DriverManager , etc... Sample code to iterate ArrayList using Iterators: List list=new ArrayList(); list.add("item1"); list.add("item2"); Iterator it=list.iterator(); while(it.hasNext()) System.out.println(it.next()+" "); Sample code to iterate Vectors using Enumeration: Vector v=new Vector(); v.add("ele1"); v.add("ele2"); Enumeration elements = v.elements() ; while (elements.hasMoreElements()) { System.out.println(elements.nextElement()); } 19. Explain about Reflection in java. · Classes, interfaces, methods, instance variables can be inspected at runtime by using reflection class To inspect he names of the classes, methods, fields etc. need not be known Reflection in Java is powerful and useful, when objects are needed to be mapped into tables in a database at runtime. Java reflection is useful to map the statements in a scripting language to that of method calls on objects at runtime. Reflection in Java invokes methods of another class dynamically at run time. Example: Send java.util.Stack as a command line argument: java ReflectionExample java.util.Stack import java.lang.reflect.*; public class ReflectionExample { public static void main(String args[]) { try { Class cls = Class.forName(args[0]); Method methods[] = cls.getDeclaredMethods(); for (int index = 0; index < methods.length; index++) System.out.println(methods[index].toString()); } catch (Throwable exp) { System.err.println(exp); } } } The produced result on the console is run as java ReflectionExample java.lang .Math |
10. Tell me about yourself? 11. Write one java class, using two methods one is for add, one is for multiplication? · Class A { Void add(int a, int b) { System.out.println(a+b); } Void mult(int a, int b) { System.out.println(a*b); } } Public Class Manager { Public static void main(String args[]) A a1=new A(); a1.add(5,10); a1.mult(2,3); } 12. Different between == and equals ()? · It is important to understand that the equals ( ) method and the == operator perform two different operations. As just explained, the equals ( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal · Example: public class EqualDemo2 { public static void main(String[] args) { String s1 = "Hello"; String s2 = "Hello"; String s3 = new String("Hello"); if (s1.equals(s2)) { System.out.println("TRUE"); } else { System.out.println("FALSE"); } if (s1 == s2) { System.out.println("TRUE"); } else { System.out.println("FALSE"); } if (s1.equals(s3)) { System.out.println("TRUE"); } else { System.out.println("FALSE"); } if (s1 == s3) { System.out.println("TRUE"); } else { System.out.println("FALSE"); } } } · Output: TRUE TRUE TRUE FALSE 13. Different between protected and private? · Private Access Modifier – Private: o Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.o Private access modifier is the most restrictive access level. Class and interfaces cannot be private.o Variables that are declared private can be accessed outside the class if public getter methods are present in the class.· Protected Access Modifier – Protected: o Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.o The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in an interface cannot be declared protected. o Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.14. Static Method () importance? · Static method can access with the class name, non-static method can access with the class name object. · A static method is a method that doesn't access non-static (i.e. instance) member data. For example, all the methods in the Math class are defined as static. This means they can be invoked directly with the class name, you don't need to create an instance (object) of the class 15. We have 2 buckets of 5lt and 3lt and a pool of water. How can we measure 4lt using those buckets? · Solution Step 1 :- Fill 5 Litre Jug completely 5 Litre Jug 3 Litre Jug Solution Step 2:- Pour into 3 Litre Jug until 3 Litre not complete. Now there is 2 Litre water in 5 Litre Jug. Note 5 Litre JUG now has 2 Litres of water 5 Litre Jug 3 Litre Jug Solution Step 3:- Empty 3 Litre JUG 5 Litre Jug 3 Litre Jug Solution Step 4:- Pour 2 Litre from 5 Litre JUG into 3 Litres JUG. 5 Litre Jug 3 Litre Jug Solution Step 5 :- Fill 5 Litre JUG completely 5 Litre Jug 3 Litre Jug Solution Step 6 :- Now 3 Litre JUG has only 1 Litre capacity left. Pour water from 5 Litre JUG into 3 Litre JUG, until 3 Litre JUG is completely full. That will leave 4 Litre water in 5 Litre JUG. Problem solved 5 Litre Jug 3 Litre Jug 16. Whatare XML and XSL write one example program? XML · XML was designed to transport and store data, with focus an data. · XML is about carrying information. · XML tags are not predefined. You must define your own tags. XSL Xsl is a style sheet for xml, XSL contains of three parts: XSLT – a language for transforming xml document into XHTML document or to another XML documents. X-Path – a language for navigating in xml documents. XSL-Fo – a language for formatting xml documents. · Example Bookcatalog.xml <?XML version=”1.0”> <?XML-stylesheet type=”text/xsl” href=”bookcatalog.xsl”?> <catalog> <book> <title>corejava</title> <auther>ramu</auther> <prise>650</price> </book> <book> <title>XML</title> <auther>nagesh</auther> <prise>450</price> </book> <book> <title>webservices</title> <auther>suresh</auther> <prise>400</price> </book> </catalog> bookcatalog.xsl <? xml version="1.0" encoding="ISO-8859-1"?> <!-- Edited by XMLSpy® --> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/book"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select=" auther "/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> |
Comments
Post a Comment
Please post comments here:-)