Archive

Archive for the ‘Java Interview Questions’ Category

why string is immutable ?

February 13, 2010 1 comment

In java, Strings are handling in Pool format.

For example:

String str1 = “xyz”;

This string(str1) will be stored into memory in particular address. When we defining new String with same array of characters like

String str2 = “xyz”;

Now JVM will check in String Pool where there is same characters are available or not. If two Strings are match the JVM will refer str1 address to str2. Now the str1 and str2 referring the same characters in same memory location. This is a good idea for increasing memory efficiency.

When we change the str1 characters, the changes will be reflected to str2. Because both str1 and str2 variables are referring the same memory location. For avoiding this we are keeping String as immutable. However we can use StringBuffer if you want to do modifications in the string.

Making String immutable, makes it thread safe and thus imporves performance.

Once a string object is created no changes can be made to it. If a string is modified in code a new object will be

created. That is why string is immutable.

What is the Difference between jar, ear and war?

February 9, 2010 Leave a comment

.jar files: These files are with the .jar extension. The .jar files contain the libraries, resources and accessories files like property files.

.war files: These files are with the .war extension. The war file contains the web application that can be deployed on the any servlet/jsp container. The .war file contains jsp, html, java script and other files for necessary for the development of web applications.

.ear files: WAR(Web module) + JAR(can be EJB module or application client module). An EAR(Enterprise archive) is a top-level container which contains modules like: EJB modules, web modules, application client modules etc.

What’s the difference between “JDK” and “JRE”?

January 12, 2010 Leave a comment

The “JDK” is the Java Development Kit.the JDK is bundle of software that you can use to develop Java based software. The “JRE” is the Java Runtime Environment.the JRE is an implementation of the Java Virtual Machine which actually executes Java programs.

Each JDK contains one (or more) JRE’s along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc.

JRE is a subset of JDK.

  • Two steps for a java program ie.,compile and interpret.
  • JDK does compilation but JRE can’t.
  • Both JRE and JDK does interpretaion.

JVM :

The use of the JVM : – To convert the byte code into the machine specific code. So the JVM converts the byte code(ie the code which we get when we compile the .java class) into the code that your machine/OS understands. JVM is machine specific. So JVM for windows will be different from JVM for Mac or Unix. JVM is one of the most crucial part in the java engine. It is due to JVM only that we say java code is “Compile Once, Run Anywhere” programming language.

The byte code generated when we compile the code will be the same doesn’t matter we compiled the code in Windows OS or some other. However JVM makes sure that the byte code should be interpreted properly in the OS under concerned so interpret the byte code differently for different OS.

Servlet

January 4, 2010 Leave a comment

What is the difference between GenericServlet and HttpServlet?

Ans: – GenericServlet is for servlets that might not use HTTP, like for instance FTP servlets. Of course, it turns out that there’s no such thing as FTP servlets, but they were trying to plan for future growth when they designed the spec. Maybe some day there will be another subclass, but for now, always use HttpServlet.

In short GenericServlet is protocol independent, whereas HttpServlet is protocol dependent

In GenericServlets you cannot use Cookies or HttpSession.Session tracking is not possible, redirection is not possible.

Http servlets overrides doGet and doPost methods. Generic servlet overides service method.

1.generic servlet is superclass for HttpServlet.

2.httpservlet class can also have service() method.it’s not necessary that you can only have doGet() and doPost() method defined.

3.Generic servlet is used for small data transfer whereas HttpServlet is used for huge data transfer.

GenericServlet is might not used be for the http services and may be used for the FTP services , and it is protocol independant where as HttpServlet is Protocol dependant.HttpServlet is subclass to GenericServlet. GenericServlet extends java.lang.Object and implements servlet ,ServletConfig , Serializable interface.


Core Java Interview Questions

January 4, 2009 5 comments

This site is developed for all IT people who work in the field of Java.

This site covers all Core Java, J2EE and Sql’s Frequently Asked Questions that are asked in most technical interviews.

Core Java Interview Questions:

  1. What is a class? A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind.
  2. What is an object? An object is a software bundle of variables and related methods. An instance of a class depicting the state and behavior at that particular time in real world.
  3. What is a method? Encapsulation of a functionality which can be called to perform specific tasks.
  4. What is encapsulation? Explain with an example. Encapsulation is the term given to the process of hiding the implementation details of the object. Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they are packaged and are only indirectly accessible via the interface of the object
  5. What is inheritance? Explain with an example. Inheritance in object oriented programming means that a class of objects can inherit properties and methods from another class of objects.
  6. What is polymorphism? Explain with an example. In object-oriented programming, polymorphism refers to a programming language’s ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented programming language
  7. Is multiple inheritances allowed in Java? No, multiple inheritance is not allowed in Java.
  8. What is interpreter and compiler? Java interpreter converts the high level language code into a intermediate form in Java called as byte code, and then executes it, where as a compiler converts the high level language code to machine language making it very hardware specific
  9. What is JVM? The Java interpreter along with the runtime environment required to run the Java application in called as Java virtual machine(JVM)
  10. What are the different types of modifiers? There are access modifiers and there are other identifiers. Access modifiers are public, protected and private. Other is final and static.
  11. What are the access modifiers in Java? There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly identifier explicitly.
  12. What is a wrapper class? They are classes that wrap a primitive data type so it can be used as a object
  13. What is a static variable and static method? What’s the difference between two? The modifier static can be used with a variable and method. When declared as static variable, there is only one variable no matter how instances are created, this variable is initialized when the class is loaded. Static method do not need a class to be instantiated to be called, also a non static method cannot be called from static method.
  14. What is garbage collection? Garbage Collection is a thread that runs to reclaim the memory by destroying the objects that cannot be referenced anymore.
  15. What is abstract class? Abstract class is a class that needs to be extended and its methods implemented, aclass has to be declared abstract if it has one or more abstract methods.
  16. What is meant by final class, methods and variables? This modifier can be applied to class method and variable. When declared as final class the class cannot be extended. When declared as final variable, its value cannot be changed if is primitive value, if it is a reference to the object it will always refer to the same object, internal attributes of the object can be changed.
  17. What is interface? Interface is a contact that can be implemented by a class, it has method that need implementation.
  18. What is method overloading? Overloading is declaring multiple method with the same name, but with different argument list.
  19. What is method overriding? Overriding has same method name, identical arguments used in subclass.
  20. What is singleton class? Singleton class means that any given time only one instance of the class is present, in one JVM.
  21. What is the difference between an array and a vector? Number of elements in an array are fixed at the construction time, whereas the number of elements in vector can grow dynamically.
  22. What is a constructor? In Java, the class designer can guarantee initialization of every object by providing a special method called a constructor. If a class has a constructor, Java automatically calls that constructor when an object is created, before users can even get their hands on it. So initialization is guaranteed.
  23. What is casting? Conversion of one type of data to another when appropriate. Casting makes explicitly converting of data.
  24. What is the difference between final, finally and finalize? The modifier final is used on class variable and methods to specify certain behavior explained above. And finally is used as one of the loop in the try catch blocks, It is used to hold code that needs to be executed whether or not the exception occurs in the try catch block. Java provides a method called finalize( ) that can be defined in the class. When the garbage collector is ready to release the storage ed for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the objects memory. So finalize( ), gives you the ability to perform some important cleanup at the time of garbage collection.
  25. What are are packages? A package is a collection of related classes and interfaces providing access protection and namespace management.
  26. What is a super class and how can you call a super class? When a class is extended that is derived from another class there is a relationship is created, the parent class is referred to as the super class by the derived class that is the child. The derived class can make a call to the super class using the keyword super. If used in the constructor of the derived class it has to be the first statement.
  27. What is meant by a Thread? Thread is defined as an instantiated parallel process of a given program.
  28. What is multi-threading? Multi-threading as the name suggest is the scenario where more than one threads are running.
  29. What are two ways of creating a thread? Which is the best way and why? Two ways of creating threads are, one can extend from the Java.lang.Thread and can implement the rum method or the run method of a different class can be called which implements the interface Runnable, and the then implement the run() method. The latter one is mostly used as first due to Java rule of only one class inheritance, with implementing the Runnable interface that problem is sorted out.
  30. What is deadlock? Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread. In Java, this resource is usually the object lock obtained by the synchronized keyword.
  31. What are the three types of priority? MAX_PRIORITY which is 10, MIN_PRIORITY which is 1, NORM_PRIORITY which is 5.
  32. What is the use of synchronizations? Every object has a lock, when a synchronized keyword is used on a piece of code the, lock must be obtained by the thread first to execute that code, other threads will not be allowed to execute that piece of code till this lock is released.

33. How could Java classes direct program messages to the system console, but error messages, say to a file?


A. The class System has a variable out that represents the standard output, and the variable err that represent the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:

Stream st = new Stream(new FileOutputStream(“output.txt”)); System.setErr(st); System.setOut(st);


34. What’s the difference between an interface and an abstract class?


A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.


35. Why would you use a synchronized block vs. synchronized method?


A. Synchronized blocks place locks for shorter periods than synchronized methods.


36. Explain the usage of the keyword transient?


A. This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

37. How can you force garbage collection?


A. You can’t force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.


38. How do you know if an explicit object casting is needed?


A. If you assign a super class object to a variable of a subclass’s data type, you need to do explicit casting. For example:

Object a; Customer b; b = (Customer) a;


When you assign a subclass to a variable having a sup class type, the casting is performed automatically.


39. What’s the difference between the methods sleep() and wait()


A. The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.


40. Can you write a Java class that could be used both as an applet as well as an application?


A. Yes. Add a main() method to the applet.


41. What’s the difference between constructors and other methods?


A. Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.


42. Can you call one constructor from another if a class has multiple constructors?


A. Yes. Use this() syntax.


43. Explain the usage of Java packages.


A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.


44. If a class is located in a package, what do you need to change in the OS environment to be able to use it?


A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let’s say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you’d need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:

c:\>java com.xyz.hr.Employee


45. What’s the difference between J2SDK 1.5 and J2SDK 5.0?


A. There’s no difference, Sun Microsystems just re-branded this version.

46. What would you use to compare two String variables – the operator == or the method equals()?


A. I’d use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

47. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?


A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception’s subclasses have to be caught first.


48. Can an inner class declared inside of a method access local variables of this method?


A. It’s possible if these variables are final.


49. What can go wrong if you replace && with & in the following code:

String a=null; if (a!=null && a.length()>10) {…}

A. A single ampersand here would lead to a NullPointerException.


50. What’s the main difference between a Vector and an ArrayList


A. Java Vector class is internally synchronized and ArrayList is not.

51. When should the method invokeLater()be used?


A. This method is used to ensure that Swing components are updated through the event-dispatching thread.

52 . How can a subclass call a method or a constructor defined in a super class?


A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass’s constructor.

53. What’s the difference between a queue and a stack?


A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

54. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?


A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.

55. What comes to mind when you hear about a young generation in Java?


A. Garbage collection.

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


A. Object cloning.

57. If you’re overriding the method equals() of an object, which other method you might also consider?


A. hashCode()

Read more…

Some Interview Questions on String.

January 24, 2007 Leave a comment

Que:-1 Difference Between String and String Buffer?

Ans:- String is a Collection or array of Characters.when u create a string object u r creating a string that can’t be changed. this approach is used becoz fixed, immutable strings can be implemented more efficiently then the muttable (Changeable Ones ) strings.

StringBuffer – StringBuffer Represents growable and writeable character sequences.StringBuffer may have characters and substrings inserted in the middle or append to end.

StringBuffer allocates room for 16 additional Characters when no specific buffer length is requested, becoz reallocation is a costly process in terms of time.

Que:-2  difference between verses (==) and .equals().

Ans.  .equals() is used for comparing values of a string objects and verses ( ==) is used to compare there memory reference.