Core Java Interview Questions
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:
- 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.
- 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.
- What is a method? Encapsulation of a functionality which can be called to perform specific tasks.
- 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
- 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.
- 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
- Is multiple inheritances allowed in Java? No, multiple inheritance is not allowed in Java.
- 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
- What is JVM? The Java interpreter along with the runtime environment required to run the Java application in called as Java virtual machine(JVM)
- 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.
- 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.
- What is a wrapper class? They are classes that wrap a primitive data type so it can be used as a object
- 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.
- What is garbage collection? Garbage Collection is a thread that runs to reclaim the memory by destroying the objects that cannot be referenced anymore.
- 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.
- 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.
- What is interface? Interface is a contact that can be implemented by a class, it has method that need implementation.
- What is method overloading? Overloading is declaring multiple method with the same name, but with different argument list.
- What is method overriding? Overriding has same method name, identical arguments used in subclass.
- What is singleton class? Singleton class means that any given time only one instance of the class is present, in one JVM.
- 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.
- 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.
- What is casting? Conversion of one type of data to another when appropriate. Casting makes explicitly converting of data.
- 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.
- What are are packages? A package is a collection of related classes and interfaces providing access protection and namespace management.
- 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.
- What is meant by a Thread? Thread is defined as an instantiated parallel process of a given program.
- What is multi-threading? Multi-threading as the name suggest is the scenario where more than one threads are running.
- 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.
- 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.
- What are the three types of priority? MAX_PRIORITY which is 10, MIN_PRIORITY which is 1, NORM_PRIORITY which is 5.
- 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()
58. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
ArrayList or LinkedList?
A. ArrayList
59. How would you make a copy of an entire Java object with its state?
A. Have this class implement Cloneable interface and call its method clone().
60. How can you minimize the need of garbage collection and make the memory use more effective?
A. Use object pooling and weak object references.
61. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
A. If these classes are threads I’d consider notify() or notifyAll(). For regular classes you can use the Observer interface.
62. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
A. You do not need to specify any access level, and Java will use a default package access level.
Some Basic to Advance Core Java Questions
- Can there be an abstract class with no abstract methods in it? – Yes
- Can an Interface be final? – No
- Can an Interface have an inner class? – Yes.
public interface abc
{
static int i=0; void dd();
class a1
{
a1()
{
int j;
System.out.println("inside");
};
public static void main(String a1[])
{
System.out.println("in interfia");
}
}
}
- Can we define private and protected modifiers for variables in interfaces? – No
- What is Externalizable? – Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
- What modifiers are allowed for methods in an Interface? – Only public and abstract modifiers are allowed for methods in interfaces.
- What is a local, member and a class variable? – Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables). Variables declared within the class i.e not within any methods and are defined as “static” are class variables
- What are the different identifier states of a Thread? – The different identifiers of a Thread are: R – Running or runnable thread, S – Suspended thread, CW – Thread waiting on a condition variable, MW – Thread waiting on a monitor lock, MS – Thread suspended waiting on a monitor lock
- What are some alternatives to inheritance? – Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).
- Why isn’t there operator overloading? – Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().
- What does it mean that a method or field is “static”? – Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the java.lang.System class.
- How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
String hostname = InetAddress.getByName("192.18.97.39").getHostName();
- Difference between JRE/JVM/JDK?
- Why do threads block on I/O? – Threads block on i/o (that is enters the waiting state) so that other threads may execute while the I/O operation is performed.
- What is synchronization and why is it important? – With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.
- Is null a keyword? – The null value is not a keyword.
- Which characters may be used as the second character of an identifier, but not as the first character of an identifier? – The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.
- What modifiers may be used with an inner class that is a member of an outer class? – A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
- How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? – Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
- What are wrapped classes? – Wrapped classes are classes that allow primitive types to be accessed as objects.
- What restrictions are placed on the location of a package statement within a source code file? – A package statement must appear as the first line in a source code file (excluding blank lines and comments).
- What is the difference between preemptive scheduling and time slicing? – Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
- What is a native method? – A native method is a method that is implemented in a language other than Java.
- What are order of precedence and associativity, and how are they used? – Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left
- What is the catch or declare rule for method declarations? – If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
- Can an anonymous class be declared as implementing an interface and extending a class? – An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
- What is the range of the char type? – The range of the char type is 0 to 2^16 – 1.
Basic Java Interview Questions:
1. Why do you prefer Java?
Answer: write once ,run anywhere.
2. Name some of the classes which provide the functionality of collation?
Answer: collator, rulebased collator, collationkey, collationelement iterator.
3. Awt stands for? and what is it?
Answer: AWT stands for Abstract window tool kit. It is a is a package that provides an integrated set of classes to manage user interface components.
4. why a java program can not directly communicate with an ODBC driver?
Answer: Since ODBC API is written in C language and makes use of pointers which Java can not support.
5. Are servlets platform independent? If so Why? Also what is the most common application of servlets?
Answer: Yes, Because they are written in Java. The most common application of servlet is to access database and dynamically construct HTTP response
- What is garbage collection? What is the process that is responsible for doing that in java? – Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process
- What kind of thread is the Garbage collector thread? – It is a daemon thread.
- What is a daemon thread? – These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly.
- How will you invoke any external process in Java? – Runtime.getRuntime().exec(….)
- What is the finalize method do? – Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected.
- What is mutable object and immutable object? – If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …)
- What is the basic difference between string and stringbuffer object? – String is an immutable object. StringBuffer is a mutable object.
- What is the purpose of Void class? – The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.
- What is reflection? – Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.
- What is the base class for Error and Exception? – Throwable
- What is the byte range? -128 to 127
- What is the implementation of destroy method in java.. is it native or java code? – This method is not implemented.
- What is a package? – To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability.
- What are the approaches that you will follow for making a program very efficient? – By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more.
- What is a DatabaseMetaData? – Comprehensive information about the database as a whole.
- What is Locale? – A Locale object represents a specific geographical, political, or cultural region
- How will you load a specific locale? – Using ResourceBundle.getBundle(…);
- What is JIT and its use? – Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler — no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it’s an on-line problem.
- Is JVM a compiler or an interpreter? – Interpreter
- When you think about optimization, what is the best way to findout the time/memory consuming process? – Using profiler
- What is the purpose of assert keyword used in JDK1.4.x? – In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing.
- How will you get the platform dependent values like line separator, path separator, etc., ? – Using Sytem.getProperty(…) (line.separator, path.separator, …)
- What is skeleton and stub? what is the purpose of those? – Stub is a client side representation of the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use… it is deprecated long before in JDK.
- What is the final keyword denotes? – final keyword denotes that it is the final implementation for that method or variable or class. You can’t override that method/variable/class any more.
- What is the significance of ListIterator? – You can iterate back and forth.
- What is the major difference between LinkedList and ArrayList? – LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.
- What is nested class? – If all the methods of a inner class is static then it is a nested class.
- What is inner class? – If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.
- What is composition? – Holding the reference of the other class within some other class is known as composition.
- What is aggregation? – It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation.
- What are the methods in Object? – clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString
- Can you instantiate the Math class? – You can’t instantiate the math class. All the methods in this class are static. And the constructor is not public.
- What is singleton? – It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods … }
- What is DriverManager? – The basic service to manage set of JDBC drivers.
- What is Class.forName() does and how it is useful? – It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( “class-instance”.newInstance() ).
- Inq adds a question: Expain the reason for each keyword of
public static void main(String args[])
2.
- What is a Marker Interface? – An interface with no methods. Example: Serializable, Remote, Cloneable
- What interface do you implement to do the sorting? – Comparable
- What is the eligibility for a object to get cloned? – It must implement the Cloneable interface
- What is the purpose of abstract class? - It is not an instantiable class. It provides the concrete implementation for some/all the methods. So that they can reuse the concrete functionality by inheriting the abstract class.
- What is the difference between interface and abstract class? – Abstract class defined with methods. Interface will declare only the methods. Abstract classes are very much useful when there is a some functionality across various classes. Interfaces are well suited for the classes which varies in functionality but with the same method signatures.
- What do you mean by RMI and how it is useful? – RMI is a remote method invocation. Using RMI, you can work with remote object. The function calls are as though you are invoking a local variable. So it gives you a impression that you are working really with a object that resides within your own JVM though it is somewhere.
- What is the protocol used by RMI? – RMI-IIOP
- What is a hashCode? – hash code value for this object which is unique for every object.
- What is a thread? – Thread is a block of code which can execute concurrently with other threads in the JVM.
- What is the algorithm used in Thread scheduling? – Fixed priority scheduling.
- What is hash-collision in Hashtable and how it is handled in Java? – Two different keys with the same hash value. Two different entries will be kept in a single hash bucket to avoid the collision.
- What are the different driver types available in JDBC? – 1. A JDBC-ODBC bridge 2. A native-API partly Java technology-enabled driver 3. A net-protocol fully Java technology-enabled driver 4. A native-protocol fully Java technology-enabled driver For more information: Driver Description
- Is JDBC-ODBC bridge multi-threaded? – No
- Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? – No
- What is the use of serializable? – To persist the state of an object into any perminant storage device.
- What is the use of transient? – It is an indicator to the JVM that those variables should not be persisted. It is the users responsibility to initialize the value when read back from the storage.
- What are the different level lockings using the synchronization keyword? – Class level lock Object level lock Method level lock Block level lock
- What is the use of preparedstatement? – Preparedstatements are precompiled statements. It is mainly used to speed up the process of inserting/updating/deleting especially when there is a bulk processing.
- What is callable statement? Tell me the way to get the callable statement? – Callablestatements are used to invoke the stored procedures. You can obtain the callablestatement from Connection using the following methods prepareCall(String sql) prepareCall(String sql, int resultSetType, int resultSetConcurrency)
- In a statement, I am executing a batch. What is the result of the execution? – It returns the int array. The array contains the affected row count in the corresponding index of the SQL.
- Can a abstract method have the static qualifier? – No
- What are the different types of qualifier and what is the default qualifier? – public, protected, private, package (default)
- What is the super class of Hashtable? – Dictionary
- What is a lightweight component? – Lightweight components are the one which doesn’t go with the native call to obtain the graphical units. They share their parent component graphical units to render them. Example, Swing components
- What is a heavyweight component? – For every paint call, there will be a native call to get the graphical units. Example, AWT.
- What is an applet? – Applet is a program which can get downloaded into a client environment and start executing there.
- What do you mean by a Classloader? – Classloader is the one which loads the classes into the JVM.
- What are the implicit packages that need not get imported into a class file? – java.lang
- What is the difference between lightweight and heavyweight component? – Lightweight components reuses its parents graphical units. Heavyweight components goes with the native graphical unit for every component. Lightweight components are faster than the heavyweight components.
- What are the ways in which you can instantiate a thread? – Using Thread class By implementing the Runnable interface and giving that handle to the Thread class.
- What are the states of a thread? – 1. New 2. Runnable 3. Not Runnable 4. Dead
- What is a socket? – A socket is an endpoint for communication between two machines.
33. How will you establish the connection between the servlet and an applet? -
Using the URL, I will create the connection URL. Then by openConnection method of the URL, I will establish the connection, through which I can be able to exchange data.
34.What are the threads will start, when you start the java program? – Finalizer, Main, Reference Handler, Signal Dispatcher.
Simple Java Questions
- Meaning – Abstract classes, abstract methods
- Difference – Java,C++
- Difference between == and equals method
- Explain Java security model
- Explain working of Java Virtual Machine (JVM)
- Difference: Java Beans, Servlets
- Difference: AWT, Swing
- Disadvantages of Java
- What is BYTE Code ?
- What gives java it’s “write once and run anywhere” nature?
- Does Java have “goto”?
- What is the meaning of “final” keyword?
- Can I create final executable from Java?
- Explain Garbage collection mechanism in Java
- Why Java is not 100% pure object oriented language?
- What are interfaces? or How to support multiple inhertance in Java?
- How to use C++ code in Java Program?
- Differnece between “Applet” and “Application”?
Something New in Core Java Questions
Good Java Questions
- Is “abc” a primitive value? – The String literal “abc” is not a primitive value. It is a String object.
- What restrictions are placed on the values of each case of a switch statement? – During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.
- What modifiers may be used with an interface declaration? – An interface may be declared as public or abstract.
- Is a class a subclass of itself? – A class is a subclass of itself.
- What is the difference between a while statement and a do statement? – A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
- What modifiers can be used with a local inner class? – A local inner class may be final or abstract.
- What is the purpose of the File class? – The File class is used to create objects that provide access to the files and directories of a local file system.
- Can an exception be rethrown? – Yes, an exception can be rethrown.
- When does the compiler supply a default constructor for a class? – The compiler supplies a default constructor for a class if no other constructors are provided.
- If a method is declared as protected, where may the method be accessed? – A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
- Which non-Unicode letter characters may be used as the first character of an identifier? – The non-Unicode letter characters $ and _ may appear as the first character of an identifier
- What restrictions are placed on method overloading? – Two methods may not have the same name and argument list but different return types.
- What is casting? – There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
- What is the return type of a program’s main() method? – A program’s main() method has a void return type.
- What class of exceptions are generated by the Java run-time system? – The Java runtime system generates RuntimeException and Error exceptions.
- What class allows you to read objects directly from a stream? – The ObjectInputStream class supports the reading of objects from input streams.
- What is the difference between a field variable and a local variable? – A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.
- How are this() and super() used with constructors? – this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
- What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution? – A method’s throws clause must declare any checked exceptions that are not caught within the body of the method.
- Why are the methods of the Math class static? – So they can be invoked as if they are a mathematical code library.
- What are the legal operands of the instanceof operator? – The left operand is an object reference or null value and the right operand is a class, interface, or array type.
- What an I/O filter? – An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
- If an object is garbage collected, can it become reachable again? – Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.
- What are E and PI? – E is the base of the natural logarithm and PI is mathematical value pi.
- Are true and false keywords? – The values true and false are not keywords.
- What is the difference between the File and RandomAccessFile classes? – The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.
- What happens when you add a double value to a String? – The result is a String object.
- What is your platform’s default character encoding? – If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.
- Which package is always imported by default? – The java.lang package is always imported by default.
- What interface must an object implement before it can be written to a stream as an object? – An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.
- How can my application get to know when a HttpSession is removed? – Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method. Create an instance of that class and put that instance in HttpSession.
- Whats the difference between notify() and notifyAll()? – notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing a “writer” lock on a file might permit all “readers” to resume).
- Why can’t I say just abs() or sin() instead of Math.abs() and Math.sin()? – The import statement does not bring methods into your local name space. It lets you abbreviate class names, but not get rid of them altogether. That’s just the way it works, you’ll get used to it. It’s really a lot safer this way.
However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn’t need to inherit from anything else, make it inherit from java.lang.Math. That *does* bring all the methods into your local name space. But you can’t use this trick in an applet, because you have to inherit from java.awt.Applet. And actually, you can’t use it on java.lang.Math at all, because Math is a “final” class which means it can’t be extended. - Why are there no global variables in Java? – Global variables are considered bad form for a variety of reasons: Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables), State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state, When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once. For these reasons, Java decided to ban global variables.
- What does it mean that a class or member is final? – A final class can no longer be subclassed. Mostly 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. Methods may be declared final as well. This means they may not be overridden in a subclass. Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it’s initialized, and it must include an initializer statement where it’s declared. For example, public final double c = 2.998; It’s also possible to make a static field final to get the effect of C++’s const statement or some uses of C’s #define, e.g. public static final double c = 2.998;
- What does it mean that a method or class is abstract? – An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:
37.public abstract class Container extends Component {
Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example,
public abstract float price();
Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.
- What is a transient variable? – transient variable is a variable that may not be serialized.
- How are Observer and Observable used? – Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
- Can a lock be acquired on a class? – Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.
- What state does a thread enter when it terminates its processing? – When a thread terminates its processing, it enters the dead state.
- How does Java handle integer overflows and underflows? – It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
- What is the difference between the >> and >>> operators? – The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.
- Is sizeof a keyword? – The sizeof operator is not a keyword.
- Does garbage collection guarantee that a program will not run out of memory? – Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
- Can an object’s finalize() method be invoked while it is reachable? – An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.
- What value does readLine() return when it has reached the end of a file? – The readLine() method returns null when it has reached the end of a file.
- Can a for statement loop indefinitely? – Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;
- To what value is a variable of the String type automatically initialized? – The default value of an String type is null.
- What is a task’s priority and how is it used in scheduling? – A task’s priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.
- What is the range of the short type? – The range of the short type is -(2^15) to 2^15 – 1.
- What is the purpose of garbage collection? – The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused.
- What do you understand by private, protected and public? – These are accessibility modifiers. Private is the most restrictive, while public is the least restrictive. There is no real difference between protected and the default type (also known as package protected) within the context of the same package, however the protected keyword allows visibility to a derived class in a different package.
- What is Downcasting ? – Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy
- Can a method be overloaded based on different return type but same argument type ? – No, because the methods can be called without using their return type in which case there is ambiquity for the compiler
- What happens to a static var that is defined within a method of a class ? – Can’t do it. You’ll get a compilation error
- How many static init can you have ? – As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope.
- What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime ? – The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation
- Describe what happens when an object is created in Java? – Several things happen in a particular order to ensure the object is constructed properly: Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data. The instance variables of the objects are initialized to their default values. The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
- What does the “final” keyword mean in front of a variable? A method? A class? – FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class: cannot be derived
- What is the difference between instanceof and isInstance? – instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception. isInstance() Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.
.Why does it take so much time to access an Applet having Swing Components the first time?-
Because behind every swing component are many Java objects and resources. This takes time to create them in memory. JDK 1.3 from Sun has some improvements which may lead to faster execution of Swing applications.



on December 2, 2006 on 5:22 am
Hi, this is a comment.
To delete a comment, just log in, and view the posts’ comments, there you will have the option to edit or delete them.
on December 7, 2006 on 7:29 am
Some of these answers are inaccurate at best, if not wrong. Thankfully, interviewers have no clue about Java themselves.
on January 24, 2007 on 5:36 am
Market interface means interface which have no methods. Then why we call the Runnable interface as a marker interface, even though it has run() method?
on January 24, 2007 on 5:36 am
What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
on March 5, 2007 on 2:20 am
KVision Technologies provides services in website design, ecommerce web site design, seo services India and outsourcing web development. Expert in website development and Internet marketing.