Core Java Interview Questions and Answers
Freshers / Beginner level questions & answers
Ques 1. What is Constructor in Java?
Constructor is a block of code which is executed at the time of Object creation. It is entirely different than methods. It has same name of class name and it cannot have any return type.
Ques 2. What is java.util package in Core Java?
Java.util package contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes.
- java.util.List
- java.util.Set
- java.util.Date
Ques 3. What is the argument type of a program's main() method?
A program's main() method takes an argument of the String[] type.
public static void main(String args[]) { System.out.println("WithoutBook"); }
Ques 4. What is difference between String and StringTokenizer?
A StringTokenizer is utility class used to break up string. Example:
StringTokenizer st = new StringTokenizer("Hello World"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); }Output:
Hello
World
Ques 5. What is this() keyword in core java and when should we use this() in core java?
public class Foo { private String name; // ... public void setName(String name) { // This makes it clear that you are assigning // the value of the parameter "name" to the // instance variable "name". this.name = name; } // ... }
class Foo{ void callMethod(){ Toy toy = new Toy(); toy.insertValue(this); //Here this means Foo current object } }
class Foo { public Foo() { this("Some default value for bar"); // Additional code here will be executed // after the other constructor is done. } public Foo(String bar) { // Do something with bar } // ... }
Ques 6. Java says "write once, run anywhere". What are some ways this isn't quite true?
As long as all implementaions of java are certified by sun as 100% pure java this promise of "Write once, Run everywhere" will hold true. But as soon as various java core implemenations start digressing from each other, this won't be true anymore. A recent example of a questionable business tactic is the surreptitious behavior and interface modification of some of Java's core classes in their own implementation of Java. Programmers who do not recognize these undocumented changes can build their applications expecting them to run anywhere that Java can be found, only to discover that their code works only on Microsoft's own Virtual Machine, which is only available on Microsoft's own operating systems.
Ques 7. What is the return type of a program's main() method?
A program's main() method has a void return type.
public static void main(String args[]) { System.out.println("WithoutBook"); }
Ques 8. What gives java it's "write once and run anywhere" nature?
Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platorm specific and hence can be fed to any platform. After being fed to the JVM, which is specific to a particular operating system, the code platform specific machine code is generated thus making java platform independent.
Ques 9. What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
public static void main(String args[])
{
System.out.println("WithoutBook");
}
Ques 10. What is java.lang package in Core java?
Ques 11. What is java.io package in Core Java?
Java.io package provides classes for system input and output through data streams, serialization and the file system.
Ques 12. What is data encapsulation?
Encapsulation may be used by creating 'get' and 'set' methods in a class (JAVABEAN) which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public. Encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for instance). Wrapping of data and function into a single unit is called as data encapsulation. Encapsulation is nothing but wrapping up the data and associated methods into a single unit in such a way that data can be accessed with the help of associated methods. Encapsulation provides data security. It is nothing but data hiding.
Ques 13. What is java.math package in Core Java?
Java.math package provides classes for performing arbitrary-precision integer arithmetic (BigInteger) and arbitrary-precision decimal arithmetic (BigDecimal).
Ques 14. What's the difference between J2SDK 1.5 and J2SDK 5.0?
There's no difference, Sun Microsystems just re-branded this version.
Ques 15. 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.
Ques 16. What are the implicit packages that need not get imported into a class file?
Ques 17. What do you mean by a Classloader?
Classloader is the one which loads the classes into the JVM.
Ques 18. Difference between JRE/JVM/JDK/OpenJDK?
Ques 19. 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.
Ques 20. Is JVM a compiler or an interpreter?
Interpreter
Ques 21. 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.
Ques 22. What is the advantage of OOP?
You will get varying answers to this question depending on whom you ask. Major advantages of OOP are:
1. Simplicity: software objects model real world objects, so the complexity is reduced and the program structure is very clear;
2. Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system;
3. Modifiability: it is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods;
4. Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones;
5. Maintainability: objects can be maintained separately, making locating and fixing problems easier;
6. Re-usability: objects can be reused in different programs
Ques 23. What are the methods in Object?
clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString
Ques 24. Which class should you use to obtain design information about an object?
The Class class is used to obtain information about an object's design.
Ques 25. What are the main differences between Java and C++?
Everything is an object in Java( Single root hierarchy as everything gets derived from java.lang.Object). Java does not have all the complicated aspects of C++ ( For ex: Pointers, templates, unions, operator overloading, structures etc..) The Java language promoters initially said "No pointers!", but when many programmers questioned how you can work without pointers, the promoters began saying "Restricted pointers." You can make up your mind whether it's really a pointer or not. In any event, there's no pointer arithmetic.
There are no destructors in Java. (automatic garbage collection),
Java does not support conditional compile (#ifdef/#ifndef type).
Thread support is built into java but not in C++.
Java does not support default arguments.
There's no scope resolution operator :: in Java. Java uses the dot for everything, but can get away with it since you can define elements only within a class. Even the method definitions must always occur within a class, so there is no need for scope resolution there either.
There's no "goto " statement in Java.
Java doesn't provide multiple inheritance (MI), at least not in the same sense that C++ does.
Exception handling in Java is different because there are no destructors.
Java has method overloading, but no operator overloading.
The String class does use the + and += operators to concatenate strings and String expressions use automatic type conversion, but that's a special built-in case.
Java is interpreted for the most part and hence platform independent
Ques 26. If you're overriding the method equals() of an object, which other method you might also consider?
Ques 27. 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.
Ques 28. What's the difference between == and equals method?
equals checks for the content of the string objects while == checks for the fact that the two String objects point to same memory location ie they are same references.
Ques 29. What is the volatile modifier for?
The volatile modifier is used to identify variables whose values should not be optimized by the Java Virtual Machine, by caching the value for example. The volatile modifier is typically used for variables that may be accessed or modified by numerous independent threads and signifies that the value may change without synchronization.
Ques 30. Is null a keyword?
The null value is not a keyword.
Ques 31. 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.
Ques 32. Is 'abc' a primitive value?
The String literal 'abc' is not a primitive value. It is a String object.
Ques 33. 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.
Ques 34. 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.
Ques 35. Are true and false keywords?
The values true and false are not keywords.
Ques 36. Is sizeof a keyword?
The sizeof operator is not a keyword.
Ques 37. What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
Ques 38. What is the difference between a break statement and a continue statement?
A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.
Ques 39. Name the eight primitive Java types.
The eight primitive types are byte, char, short, int, long, float, double, and boolean.
Ques 40. Does Java have "goto"?
No.
Ques 41. Explain the usage of the keyword transient?
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).
For example:
class T {
transient int a; // will not persist
int b; // will persist
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;
public class Logon implements Serializable {
private Date date = new Date();
private String username;
private transient String password;
public Logon(String name, String pwd) {
username = name;
password = pwd;
}
public String toString() {
String pwd = (password == null) ? "(n/a)" : password;
return "logon info: n username: " + username + "n date: " + date
+ "n password: " + pwd;
}
public static void main(String[] args) throws Exception {
Logon a = new Logon("Hulk", "myLittlePony");
System.out.println("logon a = " + a);
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
"Logon.out"));
o.writeObject(a);
o.close();
Thread.sleep(1000); // Delay for 1 second
// Now get them back:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"Logon.out"));
System.out.println("Recovering object at " + new Date());
a = (Logon) in.readObject();
System.out.println("logon a = " + a);
}
}
Ques 42. What is the difference between constructors and other methods in core java?
- Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.
- Constructor needs to have the same name as that of the class whereas functions need not be the same.
- There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value.
- There is no return statement in the body of the constructor.
- The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.
Ques 43. What is the range of the char type?
The range of the char type is 0 to 2^16 - 1.
Ques 44. 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.
Ques 45. 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.
Ques 46. What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) { ... }A single ampersand here would lead to a NullPointerException.
Ques 47. What's the difference between a queue and a stack?
Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule.
You can think of a queue like a line at the bank. The first person to get there will get to the teller first. If a bunch of people come while all the tellers are busy, they stand in line in the order in which they arrived. That is to say, new people (items) are added to the end of the line and the first person in line is the only one who is called to a teller. In real life this is known as "first come, first served." In programming terms it's known as first-in-first-out, or FIFO.
You can think of a stack like a deck of cards. You can put down cards into a pile on your table one at a time, but if you want to draw cards, you can only draw them from the top of the deck one at a time. Unlike a queue, the first card to be put down is the last card to be used. This is known as first-in-last-out, or FILO (also called LIFO for last-in-first-out).
A queue is a first-in-first-out data structure. When you add an element to the queue you are adding it to the end, and when you remove an element you are removing it from the beginning.
A stack is a first-in-last-out data structure. When you add an element to a stack you are adding it to the end, and when you remove an element you are removing it from the end.
Ques 48. 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
A final variable cannot be reassigned,
but it is not constant. For instance,
final StringBuffer x = new StringBuffer()
x.append("hello");
is valid. X cannot have a new value in it,but nothing stops operations on the object
that it refers, including destructive operations. Also, a final method cannot be overridden
or hidden by new access specifications.This means that the compiler can choose
to in-line the invocation of such a method.(I don't know if any compiler actually does
this, but it's true in theory.) The best example of a final class is
String, which defines a class that cannot be derived.
Ques 49. Is the ternary operator written x : y ? z or x ? y : z ?
It is written x ? y : z.
Ques 50. How do you know if an explicit object casting is needed?
If you assign a superclass 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 superclass type, the casting is performed automatically.
Ques 51. What are native methods? How do you use them?
Native methods are methods written in other languages like C, C++, or even assembly language. You can call native methods from Java using JNI. Native methods are used when the implementation of a particular method is present in language other than Java say C, C++. To use the native methods in java we use the keyword native
public native method_a(). This native keyword is signal to the java compiler that the implementation of this method is in a language other than java. Native methods are used when we realize that it would take up a lot of rework to write that piece of already existing code in other language to Java.
Ques 52. 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.
Ques 53. 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)
Ques 54. 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.
Ques 55. 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.
Ques 56. 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.
Ques 57. Can a for statement loop indefinitely?
Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;
Ques 58. What is the % operator?
It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.
Ques 59. What are abstract classes, abstract methods?
Simply speaking a class or a method qualified with "abstract" keyword is an abstract class or abstract method. You create an abstract class when you want to manipulate a set of classes through a common interface. All derived-class methods that match the signature of the base-class declaration will be called using the dynamic binding mechanism. If you have an abstract class, objects of that class almost always have no meaning. That is, abstract class is meant to express only the interface and sometimes some default method implementations, and not a particular implementation, so creating an abstract class object makes no sense and are not allowed ( compile will give you an error message if you try to create one). An abstract method is an incomplete method. It has only a declaration and no method body. Here is the syntax for an abstract method declaration: abstract void f(); If a class contains one or more abstract methods, the class must be qualified an abstract. (Otherwise, the compiler gives you an error message.). It's possible to create a class as abstract without including any abstract methods. This is useful when you've got a class in which it doesn't make sense to have any abstract methods, and yet you want to prevent any instances of that class. Abstract classes and methods are created because they make the abstractness of a class explicit, and tell both the user and the compiler how it was intended to be used.
For example:
abstract class Instrument { int i; // storage allocated for each public abstract void play(); public String what() { return "Instrument"; } public abstract void adjust(); } class Wind extends Instrument { public void play() { System.out.println("Wind.play()"); } public String what() { return "Wind"; } public void adjust() {} }Abstract classes are classes for which there can be no instances at run time. i.e. the implementation of the abstract classes are not complete. Abstract methods are methods which have no defintion. i.e. abstract methods have to be implemented in one of the sub classes or else that class will also become Abstract.
Ques 60. What does the "abstract" keyword mean in front of a method? A class?
Abstract keyword declares either a method or a class.
If a method has a abstract keyword in front of it,it is called abstract method.Abstract method hs no body.It has only arguments and return type.Abstract methods act as placeholder methods that are implemented in the subclasses.
Abstract classes can't be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract
Ques 61. 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.
Ques 62. Can there be an abstract class with no abstract methods in it?
Yes
Ques 63. 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:
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.
Ques 64. What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass.
Ques 65. How to define an Abstract class?
A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.
Example of Abstract class:
abstract class testAbstractClass { protected String myString; public String getMyString() { return myString; } public abstract string anyAbstractFunction(); }
Ques 66. What are interfaces?
Interfaces provide more sophisticated ways to organize and control the objects in your system.
The interface keyword takes the abstract concept one step further. You could think of it as a 'pure' abstract class. It allows the creator to establish the form for a class: method names, argument lists, and return types, but no method bodies. An interface can also contain fields, but The interface keyword takes the abstract concept one step further. You could think of it as a 'pure'?? abstract class. It allows the creator to establish the form for a class: method names, argument lists, and return types, but no method bodies. An interface can also contain fields, but an interface says: 'This is what all classes that implement this particular interface will look like.'?? Thus, any code that uses a particular interface knows what methods might be called for that interface, and that'??s all. So the interface is used to establish a 'protocol'?? between classes. (Some object-oriented programming languages have a keyword called protocol to do the same thing.) Typical example from "Thinking in Java":
import java.util.*; interface Instrument { int i = 5; // static & final // Cannot have method definitions: void play(); // Automatically public String what(); void adjust(); } class Wind implements Instrument { public void play() { System.out.println("Wind.play()"); } public String what() { return "Wind"; } public void adjust() {} }
Ques 67. Can an Interface have an inner class?
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"); } } }
Ques 68. What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.
Ques 69. What must a class do to implement an interface?
It must provide all of the methods in the interface and identify the interface in its implements clause.
Ques 70. What is similarities/difference between an Abstract class and Interface?
Differences are as follows:
Interfaces provide a form of multiple inheritance. A class can extend only one other class. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.
Similarities:
Neither Abstract classes or Interface can be instantiated.
Ques 71. How to define an Interface in Java ?
In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Emaple of Interface:
public interface sampleInterface { public void functionOne(); public long CONSTANT_ONE = 1000; }
Ques 72. What are the differences between an interface and an abstract class?
- 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.
- Abstract class are used only when there is a "IS-A" type of relationship between the classes. Interfaces can be implemented by classes that are not related to one another and there is "HAS-A" relationship.
- You cannot extend more than one abstract class. You can implement more than one interface.
- Abstract class can implement some methods also. Interfaces can not implement methods.
- With abstract classes, you are grabbing away each class’s individuality. With Interfaces, you are merely extending each class’s functionality.
- As per Java 8, interface can have method body as well.
Ques 73. 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.
Ques 74. Access specifiers: "public", "protected", "private", nothing?
public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default : What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.
Ques 75. Can a abstract method have the static qualifier?
No
Ques 76. What are the different types of qualifier and what is the default qualifier?
Ques 77. Can an Interface be final?
No
Ques 78. Can we define private and protected modifiers for variables in interfaces?
No
Ques 79. 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.
Ques 80. 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.
Ques 81. What modifiers may be used with an interface declaration?
An interface may be declared as public or abstract.
Ques 82. 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.
Ques 83. 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;
Ques 84. What is a transient variable?
transient variable is a variable that may not be serialized.
Ques 85. 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.
Ques 86. 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
Ques 87. 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
Ques 88. 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.
Ques 89. If a variable is declared as private, where may the variable be accessed?
A private variable may only be accessed within the class in which it is declared.
Ques 90. If a class is declared without any access modifiers, where may the class be accessed?
A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
Ques 91. What is a native method?
A native method is a method that is implemented in a language other than Java.
Ques 92. How can you achieve Multiple Inheritance in Java?
interface CanFight { void fight(); } interface CanSwim { void swim(); } interface CanFly { void fly(); } class ActionCharacter { public void fight() {} } class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly { public void swim() {} public void fly() {} }
interface A { void methodA(); } class AImpl implements A { void methodA() { //do stuff } } interface B { void methodB(); } class BImpl implements B { void methodB() { //do stuff } } class Multiple implements A, B { private A a = new A(); private B b = new B(); void methodA() { a.methodA(); } void methodB() { b.methodB(); } }
class Multiple implements A, B { private A a = new AImpl(); private B b = new BImpl(); void methodA() { a.methodA(); } void methodB() { b.methodB(); } }
Ques 93. Does Java have multiple inheritance?
Java does not support multiple inheritence directly but it does thru the concept of interfaces.
We can make a class implement a number of interfaces if we want to achieve multiple inheritence type of functionality of C++.
Ques 94. What is the super class of Hashtable?
Ques 95. Is a class a subclass of itself?
A class is a subclass of itself.
Ques 96. 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.
Ques 97. 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.
Ques 98. Which class is extended by all other classes?
The Object class is extended by all other classes.
Ques 99. Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.
Ques 100. How would you make a copy of an entire Java object with its state?
Have this class implement Cloneable interface and call its method clone().
Ques 101. How can a subclass call a method or a constructor defined in a superclass?
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.
Ques 102. 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.
Ques 103. What is composition?
Holding the reference of the other class within some other class is known as composition.
Ques 104. 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.
Ques 105. 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
Ques 106. What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.
Ques 107. How could Java classes direct program messages to the system console, but error messages, say to a file?
By default, both System console and err point at the system console.Stream st = new Stream (new FileOutputStream ("withoutbook_com.txt"));
System.setErr(st);
System.setOut(st);
Ques 108. Which class is the wait() method defined in?
The wait() method is defined in the Object class, which is the ultimate superclass of all others. So the Thread class and any Runnable implementation inherit this method from Object. The wait() method is normally called on an object in a multi-threaded program to allow other threads to run. The method should should only be called by a thread that has ownership of the object monitor, which usually means it is in a synchronized method or statement block.
Ques 109. What is a thread?
Thread is a block of code which can execute concurrently with other threads in the JVM.
Ques 110. 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.
class RunnableThread implements Runnable { Thread runner; public RunnableThread() { } public RunnableThread(String threadName) { runner = new Thread(this, threadName); // (1) Create a new thread. System.out.println(runner.getName()); runner.start(); // (2) Start the thread. } public void run() { //Display info about this particular thread System.out.println(Thread.currentThread()); } }
Ques 111. What are the states of a thread?
A thread state. A thread can be in one of the following states:
- NEW
A thread that has not yet started is in this state. - RUNNABLE
A thread executing in the Java virtual machine is in this state. - BLOCKED
A thread that is blocked waiting for a monitor lock is in this state. - WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state. - TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. - TERMINATED
A thread that has exited is in this state.
A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states.
Ques 112. 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
Ques 113. 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.
Ques 114. 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).
Ques 115. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
Ques 116. Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
if you go for synchronized block it will lock a specific object.
if you go for synchronized method it will lock all the objects.
in other way Both the synchronized method and block are used to acquires the lock for an object. But the context may vary. Suppose if we want to invoke a critical method which is in a class whose access is not available then synchronized block is used. Otherwise synchronized method can be used.
Synchronized methods are used when we are sure all instance will work on the same set of data through the same function Synchronized block is used when we use code which we cannot modify ourselves like third party jars etc
For a detail clarification see the below code
for example:
//Synchronized block class A { public void method1() {...} } class B { public static void main(String s[]) { A objecta=new A(); A objectb=new A(); synchronized(objecta) { objecta.method1(); } objectb.method1(); //not synchronized } }
//synchronized method class A { public synchronized void method1() { ...} } class B { public static void main(String s[]) { A objecta=new A(); A objectb =new A(); objecta.method1(); objectb.method2(); } }
Ques 117. What are the differences between the methods sleep() and wait()?
- 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.
Ques 118. How can you force garbage collection?
You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.
The following code of program will help you in forcing the garbage collection. First of all we have created an object for the garbage collector to perform some operation. Then we have used the System.gc(); method to force the garbage collection on that object. Then we have used the System.currentTimeMillis(); method to show the time take by the garbage collector.
import java.util.Vector; public class GarbageCollector{ public static void main(String[] args) { int SIZE = 200; StringBuffer s; for (int i = 0; i < SIZE; i++) { } System.out.println("Garbage Collection started explicitly."); long time = System.currentTimeMillis(); System.gc(); System.out.println("It took " +(System.currentTimeMillis()-time) + " ms"); } }
Ques 119. What comes to mind when you hear about a young generation in Java?
Ques 120. How does exception handling work in Java?
1.It separates the working/functional code from the error-handling code by way of try-catch clauses.
2.It allows a clean path for error propagation. If the called method encounters a situation it can't manage, it can throw an exception and let the calling method deal with it.
3.By enlisting the compiler to ensure that "exceptional" situations are anticipated and accounted for, it enforces powerful coding.
4.Exceptions are of two types: Compiler-enforced exceptions, or checked exceptions. Runtime exceptions, or unchecked exceptions. Compiler-enforced (checked) exceptions are instances of the Exception class or one of its subclasses '?? excluding the RuntimeException branch. The compiler expects all checked exceptions to be appropriately handled. Checked exceptions must be declared in the throws clause of the method throwing them '?? assuming, of course, they're not being caught within that same method. The calling method must take care of these exceptions by either catching or declaring them in its throws clause. Thus, making an exception checked forces the us to pay heed to the possibility of it being thrown. An example of a checked exception is java.io.IOException. As the name suggests, it throws whenever an input/output operation is abnormally terminated.
Ques 121. Does Java have destructors?
Garbage collector does the job working in the background
Java does not have destructors; but it has finalizers that does a similar job.
the syntax is
public void finalize(){
}
if an object has a finalizer, the method is invoked before the system garbage collects the object
Ques 122. 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.
Ques 123. Can an exception be rethrown?
Yes, an exception can be rethrown.
Ques 124. What class of exceptions are generated by the Java run-time system?
The Java runtime system generates RuntimeException and Error exceptions.
Ques 125. 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.
Ques 126. 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
Ques 127. 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.
Ques 128. 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.
Ques 129. What kind of thread is the Garbage collector thread?
It is a daemon thread.
Ques 130. What is the base class for Error and Exception?
Throwable
Ques 131. What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
Ques 132. What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
Ques 133. Can an object be garbage collected while it is still reachable?
A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.
Ques 134. What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.
Ques 135. 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).
Ques 136. Which package is always imported by default?
The java.lang package is always imported by default.
Ques 137. What is a package?
To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability.
Ques 138. If a class is located in a package, what do you need to change in the OS environment to be able to use it?
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:devcomxyzhrEmployee.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
Ques 139. Explain the usage of Java packages.
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.
Ques 140. 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?
Ques 141. What is the difference between a Vector and an Array. Discuss the advantages and disadvantages of both?
Vector can contain objects of different types whereas array can contain objects only of a single type.
- Vector can expand at run-time, while array length is fixed.
- Vector methods are synchronized while Array methods are not
Ques 142. What is the major difference between LinkedList and ArrayList?
LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.
Ques 143. What is Collection API ?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
Ques 144. Is Iterator a Class or Interface? What is its use?
Answer: Iterator is an interface which is used to step through the elements of a Collection.
Ques 145. What is the main difference between a Vector and an ArrayList?
Sometimes Vector is better; sometimes ArrayList is better; sometimes you don‘t want to use either. I hope you weren‘t looking for an easy answer because the answer depends upon what you are doing. There are four factors to consider:
Ques 146. What is Locale?
A Locale object represents a specific geographical, political, or cultural region
Ques 147. How will you load a specific locale?
Using ResourceBundle.getBundle(');
Ques 148. 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 ' }
Ques 149. What is the difference between StringBuffer and String class?
A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
The String class represents character strings. All string literals in Java programs, such as "abc" are constant and implemented as instances of this class; their values cannot be changed after they are created. Strings in Java are known to be immutable.
Explanation: What it means is that every time you need to make a change to a String variable, behind the scene, a "new" String is actually being created by the JVM. For an example: if you change your String variable 2 times, then you end up with 3 Strings: one current and 2 that are ready for garbage collection. The garbage collection cycle is quite unpredictable and these additional unwanted Strings will take up memory until that cycle occurs. For better performance, use StringBuffers for string-type data that will be reused or changed frequently. There is more overhead per class than using String, but you will end up with less overall classes and consequently consume less memory. Describe, in general, how java's garbage collector works? The Java runtime environment deletes objects when it determines that they are no longer being used. This process is known as garbage collection. The Java runtime environment supports a garbage collector that periodically frees the memory used by objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector that scans Java's dynamic memory areas for objects, marking those that are referenced. After all possible paths to objects are investigated, those objects that are not marked (i.e. are not referenced) are known to be garbage and are collected. (A more complete description of our garbage collection algorithm might be "A compacting, mark-sweep collector with some conservative scanning".) The garbage collector runs synchronously when the system runs out of memory, or in response to a request from a Java program. Your Java program can ask the garbage collector to run at any time by calling System.gc(). The garbage collector requires about 20 milliseconds to complete its task so, your program should only run the garbage collector when there will be no performance impact and the program anticipates an idle period long enough for the garbage collector to finish its job. Note: Asking the garbage collection to run does not guarantee that your objects will be garbage collected. The Java garbage collector runs asynchronously when the system is idle on systems that allow the Java runtime to note when a thread has begun and to interrupt another thread (such as Windows 95). As soon as another thread becomes active, the garbage collector is asked to get to a consistent state and then terminate.
Ques 150. What is the eligibility for a object to get cloned?
It must implement the Cloneable interface.
Ques 151. What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.
Ques 152. 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.
Ques 153. What are E and PI?
E is the base of the natural logarithm and PI is mathematical value pi.
Ques 154. What happens when you add a double value to a String?
The result is a String object.
Ques 155. 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.
Ques 156. 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.
Ques 157. 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.
Ques 158. To what value is a variable of the String type automatically initialized?
The default value of an String type is null.
Ques 159. What is the range of the short type?
The range of the short type is -(2^15) to 2^15 - 1.
Ques 160. What is Downcasting ?
Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy
Ques 161. 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.
Ques 162. 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, ')
Ques 163. What is the basic difference between string and stringbuffer object?
String is an immutable object. StringBuffer is a mutable object.
Ques 164. What is the byte range?
128 to 127
Ques 165. Can a double value be cast to a byte?
Yes, a double value can be cast to a byte.
Ques 166. Can a Byte object be cast to a double value?
No, an object cannot be cast to a primitive value.
Ques 167. How is rounding performed under integer division?
The fractional part of the result is truncated. This is known as rounding toward zero.
Ques 168. What would you use to compare two String variables - the operator == or the method equals()?
I would 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.
Ques 169. 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
Ques 170. What is a hashCode?
hash code value for this object which is unique for every object.
Ques 171. What modifiers can be used with a local inner class?
A local inner class may be final or abstract.
Ques 172. Why are the methods of the Math class static?
So they can be invoked as if they are a mathematical code library.
Ques 173. 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.
Ques 174. What is the use of serializable?
To persist the state of an object into any perminant storage device.
Ques 175. What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.
Ques 176. 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.
Ques 177. 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.
Ques 178. 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.
Ques 179. 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.
Ques 180. What is a socket?
A socket is an endpoint for communication between two machines.
Ques 181. 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.
Ques 182. What is the SwingUtilities.invokeLater(Runnable) method for?
The static utility method invokeLater(Runnable) is intended to execute a new runnable thread from a Swing application without disturbing the normal sequence of event dispatching from the Graphical User Interface (GUI). The method places the runnable object in the queue of Abstract Windowing Toolkit (AWT) events that are due to be processed and returns immediately. The runnable object run() method is only called when it reaches the front of the queue. The deferred effect of the invokeLater(Runnable) method ensures that any necessary updates to the user interface can occur immediately, and the runnable work will begin as soon as those high priority events are dealt with. The invoke later method might be used to start work in response to a button click that also requires a significant change to the user interface, perhaps to restrict other activities, while the runnable thread executes.
Ques 183. 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
Ques 184. What is a heavyweight component?
For every paint call, there will be a native call to get the graphical units. Example, AWT.
Ques 185. 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.
Ques 186. Which containers use a border layout as their default layout?
The Window, Frame and Dialog classes use a border layout as their default layout.
Ques 187. What are java beans?
JavaBeans is a portable, platform-independent component model written in the Java programming language, developed in collaboration with industry leaders. It enables developers to write reusable components once and run them anywhere ' benefiting from the platform-independent power of Java technology. JavaBeans acts as a Bridge between proprietary component models and provides a seamless and powerful means for developers to build components that run in ActiveX container applications. JavaBeans are usual Java classes which adhere to certain coding conventions:
1. Implements java.io.Serializable interface
2. Provides no argument constructor
3. Provides getter and setter methods for accessing it'??s properties
Ques 188. What is DriverManager?
The basic service to manage set of JDBC drivers.
Ques 189. 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() ).
Ques 190. 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 (Java Virtual Machine) though it is somewhere.
Ques 191. What is the protocol used by RMI?
Ques 192. 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.
Ques 193. 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)
Ques 194. When should I use abstract methods?
Abstract methods are usually declared where two or more subclasses are expected to fulfil a similar role in different ways. Often the subclasses are required to the fulfil an interface, so the abstract superclass might provide several of the interface methods, but leave the subclasses to implement their own variations of the abstract methods. Abstract classes can be thought of as part-complete templates that make it easier to write a series of subclasses.
For example, if you were developing an application for working with different types of documents, you might have a Document interface that each document must fulfil. You might then create an AbstractDocument that provides concrete openFile() and closeFile() methods, but declares an abstract displayDocument(JPanel) method. Then separate LetterDocument, StatementDocument or InvoiceDocument types would only have to implement their own version of displayDocument(JPanel) to fulfil the Document interface.
Ques 195. Why use an abstract class instead of an interface?
The main reason to use an abstract class rather than an interface is because abstract classes can carry a functional "payload" that numerous subclasses can inherit and use directly. Interfaces can define the same abstract methods as an abstract class but cannot include any concrete methods.
In a real program it is not a question of whether abstract classes or interfaces are better, because both have features that are useful. It is common to use a mixture of interface and abstract classes to create a flexible and efficient class hierarchy that introduces concrete methods in layers. In practical terms it is more a question of the appropriate point in the hierarchy to define "empty" abstract methods, concrete methods and combine them through the extends and implements keywords.
The example below compares a "Spectrum" type defined by an interface and an abstract class and shows how the abstract class can provide protected methods that minimise the implementation requirements in its subclasses.
Ques 196. If an object is garbage collected, can it become reachable again?
Once an object is garbage collected, It can no longer become reachable again.
Ques 197. What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup, before the object gets garbage collected. For example, closing an opened database Connection.
Ques 198. 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.
Ques 199. 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.
Ques 200. What kind of thread is the Garbage collector thread?
It is a daemon thread.
Ques 201. Explain Garbage collection mechanism in Java?
Garbage collection is one of the most important features of Java. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use.
In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is an automatic process and can't be forced. There is no guarantee that Garbage collection will start immediately upon request of System.gc().
Ques 202. What is polymorphism in Java? Method overloading or overriding?
What is polymorphism in Java
Polymorphism is an Oops concept which advice use of common interface instead of concrete implementation while writing code. When we program for interface our code is capable of handling any new requirement or enhancement arise in near future due to new implementation of our common interface. If we don't use common interface and rely on concrete implementation, we always need to change and duplicate most of our code to support new implementation. Its not only java but other object oriented language like C++ also supports polymorphism and it comes as fundamental along with encapsulation , abstraction and inheritance.
Method overloading and method overriding in Java
Method is overloading and method overriding uses concept of polymorphism in java where method name remains same in two classes but actual method called by JVM depends upon object. Java supports both overloading and overriding of methods. In case of overloading method signature changes while in case of overriding method signature remains same and binding and invocation of method is decided on runtime based on actual object. This facility allows java programmer to write very flexibly and maintainable code using interfaces without worrying about concrete implementation. One disadvantage of using polymorphism in code is that while reading code you don't know the actual type which annoys while you are looking to find bugs or trying to debug program. But if you do java debugging in IDE you will definitely be able to see the actual object and the method call and variable associated with it.
Ques 203. What is FileOutputStream in java?
Java.io.FileOutputStream is an output stream for writing data to a File or to a FileDescriptor. Following are the important points about FileOutputStream:
This class is meant for writing streams of raw bytes such as image data.
For writing streams of characters, use FileWriter
public class FileOutputStream extends OutputStream
1 | FileOutputStream(File file) This creates a file output stream to write to the file represented by the specified File object. |
2 | FileOutputStream(File file, boolean append) This creates a file output stream to write to the file represented by the specified File object. |
3 | FileOutputStream(FileDescriptor fdObj) This creates an output file stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system. |
4 | FileOutputStream(String name) This creates an output file stream to write to the file with the specified name. |
5 | FileOutputStream(String name, boolean append) This creates an output file stream to write to the file with the specified name. |
file = new File("c:/newfile.txt"); fop = new FileOutputStream(file); if (!file.exists()) { file.createNewFile(); } // get the content in bytes byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close();
Ques 204. What is multithreading in Java?
Java is a multithreaded programming language which means we can develop multithreaded program using Java. A multithreaded program contains two or more parts that can run concurrently and each part can handle different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.
By definition multitasking is when multiple processes share common processing resources such as a CPU. Multithreading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application.
Multithreading enables you to write in a way where multiple activities can proceed concurrently in the same program.
Ques 205. What is keyword in Core Java?
A keyword is a word with a predefined meaning in Java programming language syntax. Reserved for Java, keywords may not be used as identifiers for naming variables, classes, methods or other entities.
Ques 206. What is identifier in java?
An identifier is a sequence of one or more characters. The first character must be a valid first character (letter, $, _) in an identifier of the Java programming language. Each subsequent character in the sequence must be a valid nonfirst character (letter, digit, $, _) in a Java identifier.
Ques 207. What is literals in core java?
Intermediate / 1 to 5 years experienced level questions & answers
Ques 208. What is Cloneable Interface in Core Java?
A clone of an object is an object with distinct identity and equal contents. To define clone, a class must implement cloneable interface and must override Object’s clone method with a public modifier. At this point, it is worth nothing that cloneable interface does not contain the clone method, and Object’s clone method is protected.
Ques 209. What is abstraction?
something which is not concrete , something which is imcomplete.
java has concept of abstract classes , abstract method but a variable can not be abstract.
an abstract class is something which is incomplete and you can not create instance of it for using it.if you want to use it you need to make it complete by extending it.
an abstract method in java doesn't have body , its just a declaration.
so when do you use abstraction ? ( most important in my view )
when I know something needs to be there but I am not sure how exactly it should look like.
e.g. when I am creating a class called Vehicle, I know there should be methods like start() and Stop() but don't know start and stop mechanism of every vehicle since they could have different start and stop mechanism e..g some can be started by kick or some can be by pressing buttons .
the same concept apply to interface also , which we will discuss in some other post.
so implementation of those start() and stop() methods should be left to there concrete implementation e.g. Scooter , MotorBike , Car etc.
In Java Interface is an another way of providing abstraction, Interfaces are by default abstract and only contains public static final constant or abstract methods. Its very common interview question is that where should we use abstract class and where should we use Java Interfaces in my view this is important to understand to design better java application, you can go for java interface if you only know the name of methods your class should have e.g. for Server it should have start() and stop() method but we don't know how exactly these start and stop method will work. if you know some of the behavior while designing class and that would remain common across all subclasses add that into abstract class.
in Summary
1) Use abstraction if you know something needs to be in class but implementation of that varies.
2) In Java you can not create instance of abstract class , its compiler error.
3) abstract is a keyword in java.
4) a class automatically becomes abstract class when any of its method declared as abstract.
5) abstract method doesn't have method body.
6) variable can not be made abstract , its only behavior or methods which would be abstract.
Ques 210. String vs StringBuffer vs StringBuilder in Java
String in Java
1) String is immutable in Java: String is by design immutable in java you can check this post for reason. Immutability offers lot of benefit to the String class e.g. his hash code value can be cached which makes it a faster hashmap key; it can be safely shared between multithreaded applications without any extra synchronization. To know why strings are immutable in java see the link
2)when we represent string in double quotes like "abcd" they are referred as String literal and String literals are created in String pools.
3) "+" operator is overloaded for String and used to concatenated two string. Internally "+" operation is implemented using either StringBuffer or StringBuilder.
4) Strings are backed up by Character Array and represented in UTF-16 format.
5) String class overrides equals() and hashcode() method and two Strings are considered to be equal if they contain exactly same character in same order and in same case. If you want ignore case comparison of two strings consider using equalsIgnoreCase() method. To learn how to correctly override equals method in Java see the link.
7) toString() method provides string representation of any object and its declared in Object class and its recommended for other class to implement this and provide string representation.
8) String is represented using UTF-16 format in Java.
9) In Java you can create String from byte array, char array, another string, from StringBuffer or from StringBuilder. Java String class provides constructor for all of these.
Problem with String in Java
One of its biggest strength "immutability" is a biggest problem of Java String if not used correctly. many a times we create a String and then perform a lot of operation on them e.g. converting string into uppercase, lowercase , getting substring out of it , concatenating with other string etc. Since String is an immutable class every time a new String is created and older one is discarded which creates lots of temporary garbage in heap. If String are created using String literal they remain in String pool. To resolve this problem Java provides us two Classes StringBuffer and StringBuilder. String Buffer is an older class but StringBuilder is relatively new and added in JDK 5.
Differences between String and StringBuffer in Java
Main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method. String vs StringBuffer or what is difference between StringBuffer and String is one of the popular interview questions for either phone interview or first round. Now days they also include StringBuilder and ask String vs StringBuffer vs StringBuilder. So be preparing for that. In the next section we will see difference between StringBuffer and StringBuilder in Java.
Difference between StringBuilder and StringBuffer in Java
StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of cases than StringBuffer class. You can also use "+" for concatenating two string because "+" operation is internal implemented using either StringBuffer or StringBuilder in Java. If you see StringBuilder vs StringBuffer you will find that they are exactly similar and all API methods applicable to StringBuffer are also applicable to StringBuilder in Java. On the other hand String vs StringBuffer is completely different and there API is also completely different, same is true for StringBuilders vs String.
Summary
1) String is immutable while StringBuffer and StringBuilder is mutable object.
2) StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.
3) Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder.
4) Use String if you require immutability, use Stringbuffer in java if you need mutable + threadsafety and use StringBuilder in Java if you require mutable + without thread-safety.
Ques 211. 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
Ques 212. 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.
Ques 213. How will you get the platform dependent values like line separator, path separator, etc., ?
Using Sytem.getProperty(') (line.separator, path.separator, ')
Ques 214. What comes to mind when someone mentions a shallow copy and deep copy in Java?
Object cloning.
Java provides a mechanism for creating copies of objects called cloning. There are two ways to make a copy of an object called shallow copy and deep copy.
Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the references are copied. Thus, if the object you are copying contains references to yet other objects, a shallow copy refers to the same subobjects.
Deep copy is a complete duplicate copy of an object. If an object has references to other objects, complete new copies of those objects are also made. A deep copy generates a copy not only of the primitive values of the original object, but copies of all subobjects as well, all the way to the bottom. If you need a true, complete copy of the original object, then you will need to implement a full deep copy for the object.
Java supports shallow and deep copy with the Cloneable interface to create copies of objects. To make a clone of a Java object, you declare that an object implements Cloneable, and then provide an override of the clone method of the standard Java Object base class. Implementing Cloneable tells the java compiler that your object is Cloneable. The cloning is actually done by the clone method.
Ques 215. 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.
Ques 216. Which Java operator is right associative?
The = operator is right associative.
Ques 217. Describe what happens when an object is created in Java?
Several things happen in a particular order to ensure the object is constructed properly:
1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implementation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its uppercase. This process continues until the constructor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java.
4. 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.
Ques 218. How are commas used in the intialization and iteration parts of a for statement?
Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.
Ques 219. 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?
Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.
Ques 220. How many methods in the Serializable interface?
There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.
Ques 221. How many methods in the Externalizable interface?
There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().
Ques 222. What is the difference between Serializalble and Externalizable interface?
When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.
Ques 223. What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.
Ques 224. 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.
Ques 225. 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.
Ques 226. 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().
Ques 227. What does the keyword "synchronize" mean in java. When do you use it? What are the disadvantages of synchronization?
Synchronize is used when you want to make your methods thread safe. The disadvantage of synchronize is it will end up in slowing down the program. Also if not handled properly it will end up in dead lock.
Ques 228. What synchronization constructs does Java provide? How do they work?
The two common features that are used are:
1. Synchronized keyword - Used to synchronize a method or a block of code. When you synchronize a method, you are in effect synchronizing the code within the method using the monitor of the current object for the lock.
The following have the same effect.
synchronized void foo() {
}
and
void foo() {
synchronized(this) {
}
If you synchronize a static method, then you are synchronizing across all objects of the same class, i.e. the monitor you are using for the lock is one per class, not one per object.
2. wait/notify. wait() needs to be called from within a synchronized block. It will first release the lock acquired from the synchronization and then wait for a signal. In Posix C, this part is equivalent to the pthread_cond_wait method, which waits for an OS signal to continue. When somebody calls notify() on the object, this will signal the code which has been waiting, and the code will continue from that point. If there are several sections of code that are in the wait state, you can call notifyAll() which will notify all threads that are waiting on the monitor for the current object. Remember that both wait() and notify() have to be called from blocks of code that are synchronized on the monitor for the current object.
Ques 229. Do I need to use synchronized on setValue(int)?
It depends whether the method affects method local variables, class static or instance variables. If only method local variables are changed, the value is said to be confined by the method and is not prone to threading issues.
Ques 230. Which class is the wait() method defined in? I get incompatible return type for my thread getState( ) method!
It sounds like your application was built for a Java software development kit before Java 1.5. The Java API Thread class method getState() was introduced in version 1.5. Your thread method has the same name but different return type. The compiler assumes your application code is attempting to override the API method with a different return type, which is not allowed, hence the compilation error.
Ques 231. What is a working thread?
A working thread, more commonly known as a worker thread is the key part of a design pattern that allocates one thread to execute one task. When the task is complete, the thread may return to a thread pool for later use. In this scheme a thread may execute arbitrary tasks, which are passed in the form of a Runnable method argument, typically execute(Runnable). The runnable tasks are usually stored in a queue until a thread host is available to run them. The worker thread design pattern is usually used to handle many concurrent tasks where it is not important which finishes first and no single task needs to be coordinated with another. The task queue controls how many threads run concurrently to improve the overall performance of the system. However, a worker thread framework requires relatively complex programming to set up, so should not be used where simpler threading techniques can achieve similar results.
Ques 232. What is a green thread?
A green thread refers to a mode of operation for the Java Virtual Machine (JVM) in which all code is executed in a single operating system thread. If the Java program has any concurrent threads, the JVM manages multi-threading internally rather than using other operating system threads. There is a significant processing overhead for the JVM to keep track of thread states and swap between them, so green thread mode has been deprecated and removed from more recent Java implementations. Current JVM implementations make more efficient use of native operating system threads.
Ques 233. What are the different level lockings using the synchronization keyword?
Ques 234. 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.
Ques 235. 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.
Ques 236. 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.
Ques 237. 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.
Ques 238. 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.
Ques 239. 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
Ques 240. 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.
Ques 241. What is the implementation of destroy method in java.. is it native or java code?
This method is not implemented.
Ques 242. How many times may an object's finalize() method be invoked by the garbage collector?
An object's finalize() method may only be invoked once by the garbage collector.
Ques 243. How can you minimize the need of garbage collection and make the memory use more effective?
Use object pooling and weak object references.
Pooling basically means utilizing the resources efficiently, by limiting access of the objects to only the period the client requires it.
Increasing utilization through pooling usually increases system performance.
Object pooling is a way to manage access to a finite set of objects among competing clients. in other words,
object pooling is nothing but sharing of objects between different clients.
Since object pooling allows sharing of objects ,the other clients/processes need to re-instantiate the object(which decreases the load time), instead they can use an existing object. After the usage , the objects are returned to the pool.
Ques 244. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.
Ques 245. If a class is located in a package, what do you need to change in the OS environment to be able to use it?
You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Lets 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
Ques 246. What interface do you implement to do the sorting?
Ques 247. What is the significance of ListIterator?
You can iterate back and forth.
Ques 248. 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
Ques 249. What is nested class?
If all the methods of a inner class is static then it is a nested class.
Ques 250. 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.
Ques 251. 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.
Ques 252. What value does read() return when it has reached the end of a file?
The read() method returns -1 when it has reached the end of a file.
Ques 253. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
Ques 254. How will you invoke any external process in Java?
Runtime.getRuntime().exec('.)
Ques 255. 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.
Ques 256. Can you write a Java class that could be used both as an applet as well as an application?
Yes. Add a main() method to the applet.
import java.awt.*; import java.applet.*; import java.util.*; public class AppApp extends Applet { public void init() { add(new TextArea("Welcome to withoutbook.com")); String ar[]=new String[2]; ar[0]="Welcome to withoutbook.com"; main(ar); } public void main(String args[]) { System.out.println(args[0]); } }
Ques 257. What is a DatabaseMetaData?
Comprehensive information about the database as a whole.
Ques 258. 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.
Ques 259. In which case, do we need abstract classes with no abstract methods?
An abstract class without any abstract methods should be a rare thing and you should always question your application design if this case arises. Normally you should refactor to use a concrete superclass in this scenario.
One specific case where abstract class may justifiably have no abstract methods is where it partially implements an interface, with the intention that its subclasses must complete the interface.
Ques 260. What's the use of concrete methods in abstract classes?
One of the design principles of Java inheritance is to create superclass methods that can be used by one or more subclasses, this avoids duplication of code and makes it easier to amend. The same principle holds with abstract classes that are fulfilled by numerous subclasses.
One useful technique with abstract classes is that a concrete method may be defined in anticipation of abstract methods being fulfilled in its subclasses. In the example below the AbstractShape class has a concrete printArea() method that calls the abstract getArea() method. Subclasses inherit the printArea() method and must implement the getArea() method to stand as concrete classes.
Ques 261. Can a method be static and synchronized?
A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang. Class instance associated with the object. It is similar to saying:
synchronized(XYZ.class) { }
Ques 262. What is Encapsulation in Java and OOPS with Example?
Encapsulation is nothing but protecting anything which is prone to change. rational behind encapsulation is that if any functionality which is well encapsulated in code i.e maintained in just one place and not scattered around code is easy to change. this can be better explained with a simple example of encapsulation in Java. we all know that constructor is used to create object in Java and constructor can accept argument.
Advantage of Encapsulation in Java and OOPS
Here are few advantages of using Encapsulation while writing code in Java or any Object oriented programming language:
1. Encapsulated Code is more flexible and easy to change with new requirements.
2. Encapsulation in Java makes unit testing easy.
3. Encapsulation in Java allows you to control who can access what.
4. Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading
environment.
5. Encapsulation reduce coupling of modules and increase cohesion inside a module because all piece of one thing
are encapsulated in one place.
6. Encapsulation allows you to change one part of code without affecting other part of code.
What should you encapsulate in code
Anythign which can be change and more likely to change in near future is candidate of Encapsulation. This also helps to write more specific and cohesive code. Example of this is object creation code, code which can be improved in future like sorting and searching logic.
Design Pattern based on Encapsulation in Java
Many design pattern in Java uses encapsulation concept, one of them is Factory pattern which is used to create objects. Factory pattern is better choice than new operator for creating object of those classes whose creation logic can vary and also for creating different implementation of same interface. BorderFactory class of JDK is a good example of encapsulation in Java which creates different types of Border and encapsulate creation logic of Border. Singleton pattern in Java also encpasulate how you create instance by providing getInstance() method. since object
is created inside one class and not from any other place in code you can easily change how you create object without
affect other part of code.
Ques 263. Difference between Thread and Runnable interface in Java?
Here are some of my thoughts on whether I should use Thread or Runnable for implementing task in Java, though you have another choice as "Callable" for implementing thread which we will discuss later.
1) Java doesn't support multiple inheritance, which means you can only extend one class in Java so once you extended Thread class you lost your chance and can not extend or inherit another class in Java.
2) In Object oriented programming extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread than use Runnable interface instead.
3) Runnable interface represent a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is good design decision.
4) Separating task as Runnable means we can reuse the task and also has liberty to execute it from different means. since you can not restart a Thread once it completes. again Runnable vs Thread for task, Runnable is winner.
5) Java designer recognizes this and that's why Executors accept Runnable as Task and they have worker thread which executes those task.
6) Inheriting all Thread methods are additional overhead just for representing a Task which can can be done easily with Runnable.
Ques 264. Difference between Wait and Sleep , Yield in Java
Difference between Wait and Sleep in Java
Main difference between wait and sleep is that wait() method release the acquired monitor when thread is waiting while Thread.sleep() method keeps the lock or monitor even if thread is waiting. Also wait method in java should be called from synchronized method or block while there is no such requirement for sleep() method. Another difference is Thread.sleep() method is a static method and applies on current thread, while wait() is an instance specific method and only got wake up if some other thread calls notify method on same object. also in case of sleep, sleeping thread immediately goes to Runnable state after waking up while in case of wait, waiting thread first acquires the lock and then goes into Runnable state. So based upon your need if you require a specified second of pause use sleep() method or if you want to implement inter-thread communication use wait method.
here is list of difference between wait and sleep in Java :
1) wait is called from synchronized context only while sleep can be called without synchronized block. see Why wait and notify needs to call from synchronized method for more detail.
2) wait is called on Object while sleep is called on Thread. see Why wait and notify are defined in object class instead of Thread.
3) waiting thread can be awake by calling notify and notifyAll while sleeping thread can not be awaken by calling notify method.
4) wait is normally done on condition, Thread wait until a condition is true while sleep is just to put your thread on sleep.
5) wait release lock on object while waiting while sleep doesn’t release lock while waiting.
Difference between yield and sleep in java
Major difference between yield and sleep in Java is that yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. Yield method doesn’t guarantee that current thread will pause or stop but it guarantee that CPU will be relinquish by current Thread as a result of call to Thread.yield() method in java.
Sleep method in Java has two variants one which takes millisecond as sleeping time while other which takes both mill and nano second for sleeping duration.
sleep(long millis)
or
sleep(long millis,int nanos)
Cause the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.
10 points about Thread sleep() method in Java
I have listed down some important and worth to remember points about Sleep() method of Thread Class in Java:
1) Thread.sleep() method is used to pause the execution, relinquish the CPU and return it to thread scheduler.
2) Thread.sleep() method is a static method and always puts current thread on sleep.
3) Java has two variants of sleep method in Thread class one with one argument which takes milliseconds as duration for sleep and other method with two arguments one is millisecond and other is nanosecond.
4) Unlike wait() method in Java, sleep() method of Thread class doesn't relinquish the lock it has acquired.
5) sleep() method throws Interrupted Exception if another thread interrupt a sleeping thread in java.
6) With sleep() in Java its not guaranteed that when sleeping thread woke up it will definitely get CPU, instead it will go to Runnable state and fight for CPU with other thread.
7) There is a misconception about sleep method in Java that calling t.sleep() will put Thread "t" into sleeping state, that's not true because Thread.sleep method is a static method it always put current thread into Sleeping state and not thread "t".
That’s all on Sleep method in Java. We have seen difference between sleep and wait along with sleep and yield in Java. In Summary just keep in mind that both sleep() and yield() operate on current thread.
Ques 265. Difference between Vector and ArrayList in Java
1) Vector and ArrayList are index based and backed up by an array internally.
2) Both ArrayList and Vector maintains the insertion order of element. Means you can assume that you will get the object in the order you have inserted if you iterate over ArrayList or Vector.
3) Both iterator and ListIterator returned by ArrayList and Vector are fail-fast.
Key Differences between Vector and ArrayList in Java
1) First and foremost difference is Vector is synchronized and ArrayList is not, what it means is that all the method which structurally modifies Vector e.g. add () or remove () are synchronized which makes it thread-safe and allows it to be used safely in a multi-threaded environment. On the other hand ArrayList methods are not synchronized thus not suitable for use in multi-threaded environment.
2) ArrayList is faster than Vector. Since Vector is synchronized it pays price of synchronization which makes it little slow. On the other hand ArrayList is not synchronized and fast which makes it obvious choice in a single-threaded access environment. You can also use ArrayList in a multi-threaded environment if multiple threads are only reading values from ArrayList.
3) Whenever Vector crossed the threshold specified it increases itself by value specified in capacityIncrement field while you can increase size of arrayList by calling ensureCapacity () method.
4) Vector can return enumeration of items it hold by calling elements () method which is not fail-fast as opposed to iterator and ListIterator returned by ArrayList.
5) Another point worth to remember is Vector is one of those classes which comes with JDK 1.0 and initially not part of Collection framework but in later version it's been re-factored to implement List interface so that it could become part of collection framework
Conclusion is use ArrayList wherever possible and avoids use of Vector until you have no choice.
Ques 266. Difference between wait, notify and notifyAll in Core Java.
Ques 267. What is Checked Exception and its use in java?
- IOException
- SQLException
- DataAccessException
- ClassNotFoundException
- InvocationTargetException
Ques 268. What is Unchecked Exception in java?
Ques 269. What is Anonymous (inner) Class in java?
button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // do something. } });
Experienced / Expert level questions & answers
Ques 270. What is phantom memory?
Phantom memory is false memory. Memory that does not exist in reality.
Ques 271. How can I swap two variables without using a third variable?
Add two variables and assign the value into First variable. Subtract the Second value with the result Value. and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable.
Example:
int a=5,b=10;a=a+b; b=a-b; a=a-b;
Ques 272. Explain working of Java Virtual Machine (JVM)?
JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes.
Ques 273. Why String is immutable or final in Java?
1)Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say
String A = "Test"
String B = "Test"
Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.
2)String has been widely used as parameter for many java classes e.g. for opening network connection you can pass hostname and port number as stirng , you can pass database URL as string for opening database connection, you can open any file by passing name of file as argument to File I/O classes.
In case if String is not immutable , this would lead serious security threat , I mean some one can access to any file for which he has authorization and then can change the file name either deliberately or accidentally and gain access of those file.
3)Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java.
4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java. This one is also suggested by Jaroslav Sedlacek in comments below.
5) Another good reason of Why String is immutable in Java suggested by Dan Bergh Johnsson on comments is: The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects.
Ques 274. In Java, you can create a String object as below : String str = "abc"; & String str = new String("abc"); Why cant a button object be created as : Button bt = "abc"? Why is it compulsory to create a button object as: Button bt = new Button("abc"); Why this is not compulsory in String's case?
Button bt1= "abc"; It is because "abc" is a literal string (something slightly different than a String object, by-the-way) and bt1 is a Button object. That simple. The only object in Java that can be assigned a literal String is java.lang.String. Important to not that you are NOT calling a java.lang.String constuctor when you type String s = "abc";
For example String x = "abc"; String y = "abc"; refer to the same object. While String x1 = new String("abc");
String x2 = new String("abc"); refer to two different objects.
Ques 275. Can you call one constructor from another if a class has multiple constructors?
Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; }
Ques 276. 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).
Ques 277. When can an object reference be cast to an interface reference?
An object reference be cast to an interface reference when the object implements the referenced interface.
Ques 278. What is the algorithm used in Thread scheduling?
Fixed priority scheduling.
Ques 279. What are the threads will start, when you start the java program?
Finalizer/DestroyJavaVM, Main, Reference Handler, Signal Dispatcher
Ques 280. 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.
Ques 281. What is an object's lock and which object's have locks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.
Ques 282. 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?
If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.
Ques 283. 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.
Ques 284. Can an inner class declared inside of a method access local variables of this method?
It is possible if these variables are final.
Ques 285. When you think about optimization, what is the best way to findout the time/memory consuming process?
Using profiler
Ques 286. 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();
Ques 287. What is the advantage of the event-delegation model over the earlier event-inheritance model?
The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.
Ques 288. Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why?
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.
Ques 289. What is reflection API? How are they implemented?
What is reflection API? How are they implemented?
Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method.
Ques 290. When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded in Java?
Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, they do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields.
Ques 291. What is reason of NoClassDefFoundError in Java?
NoClassDefFoundError in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time. for example if we have a method call from a class or accessing any static member of a Class and that class is not available during run-time then JVM will throw NoClassDefFoundError. It’s important to understand that this is different than ClassNotFoundException which comes while trying to load a class at run-time only and name was provided during runtime not on compile time. Most of the java developer mingle this two Error and gets confused.
Ques 292. How to resolve NoClassDefFoundError?
Obvious reason of NoClassDefFoundError is that a particular class is not available in Classpath, so we need to add that into Classpath or we need to check why it’s not available in Classpath if we are expecting it to be. There could be multiple reasons like:
1) Class is not available in Java Classpath.
2) You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
3) Any startup script is overriding Classpath environment variable.
Ques 293. Difference between ClassNotFoundException and NoClassDefFoundError in Java?
Many a times we confused ourselves with ClassNotFoundException and NoClassDefFoundError, though both of them related to Java Classpath they are completely different to each other. ClassNotFoundException comes when JVM tries to load a class at runtime dynamically means you give the name of class at runtime and then JVM tries to load it and if that class is not found in classpath it throws ClassNotFoundException. While in case of NoClassDefFoundError the problematic class was present during Compile time and that's why program was successfully compile but not available during runtime by any reason. NoClassDefFoundError is easier to solve than ClassNotFoundException in my opinion because here we know that Class was present during build time.
Let me know how exactly you are facing NoClassDefFoundError and I will guide you how to troubleshoot it, if you are facing with something new way than I listed above we will probably document if for benefit of others and again don’t afraid with Exception in thread "main" java.lang.NoClassDefFoundError
Ques 294. What is java.lang.OutOfMemoryError in Java?
OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and JVM throws java.lang.OutOfMemoryError when it ran out of memory in heap. OutOfMemoryError in Java can come any time in heap mostly while you try to create an object and there is not enough space in heap to allocate that object. javavdoc of OutOfMemoryError is not very informative about this though.
Ques 295. Types of OutOfMemoryError in Java.
I have seen mainly two types of OutOfMemoryError in Java:
1) Java.lang.OutOfMemoryError: Java heap space
2) Java.lang.OutOfMemoryError: PermGen space
Though both of them occur because JVM ran out of memory they are quite different to each other and there solutions are independent to each other.
Ques 296. Difference between "java.lang.OutOfMemoryError: Java heap space" and "java.lang.OutOfMemoryError: PermGen space"
If you are familiar with different generations on heap and How garbage collection works in java and aware of new, old and permanent generation of heap space then you would have easily figured out this OutOfMemoryError in Java. Permanent generation of heap is used to store String pool and various Meta data required by JVM related to Class, method and other java primitives. Since in most of JVM default size of Perm Space is around "64MB" you can easily ran out of memory if you have too many classes or huge number of Strings in your project. Important point to remember is that it doesn't depends on –Xmx value so no matter how big your total heap size you can ran OutOfMemory in perm space. Good think is you can specify size of permanent generation using JVM options "-XX:PermSize" and "-XX:MaxPermSize" based on your project need.
One small thing to remember is that "=" is used to separate parameter and value while specifying size of perm space in heap while "=" is not required while setting maximum heap size in java, as shown in below example.
export JVM_ARGS="-Xmx1024m -XX:MaxPermSize=256m"
Another reason of "java.lang.OutOfMemoryError: PermGen" is memory leak through Classloaders and it’s very often surfaced in WebServer and application server like tomcat, webshere, glassfish or weblogic. In Application server different classloaders are used to load different web application so that you can deploy and undeploy one application without affecting other application on same server, but while undeploying if container some how keeps reference of any class loaded by application class loader than that class and all other related class will not be garbage collected and can quickly fill the PermGen space if you deploy and undeploy your application many times. "java.lang.OutOfMemoryError: PermGen” has been observed many times in tomcat in our last project but solution of this problem are really tricky because first you need to know which class is causing memory leak and then you need to fix that. Another reason of OutOfMemoryError in PermGen space is if any thread started by application doesn't exit when you undeploy your application.
These are just some example of infamous classloader leaks, anybody who is writing code for loading and unloading classes have to be very careful to avoid this. You can also use visualgc for monitoring PermGen space, this tool will show graph of PermGen space and you can see how and when Permanent space getting increased. I suggest using this tool before reaching to any conclusion.
Another rather unknown but interesting cause of "java.lang.OutOfMemoryError: PermGen" we found is introduction of JVM options "-Xnoclassgc". This option sometime used to avoid loading and unloading of classes when there is no further live references of it just to avoid performance hit due to frequent loading and unloading, but using this option is J2EE environment can be very dangerous because many framework e.g. Struts, spring etc uses reflection to create classes and with frequent deployment and undeployment you can easily ran out of space in PermGen if earlier references was not cleaned up. This instance also points out that some time bad JVM arguments or configuration can cause OutOfMemoryError in Java.
Ques 297. How HashMap works in Java?
"How does get () method of HashMap works in Java"
And then you get answers like I don't bother its standard Java API, you better look code on java; I can find it out in Google at any time etc.
But some interviewee definitely answer this and will say "HashMap works on principle of hashing, we have put () and get () method for storing and retrieving data from hashMap. When we pass an object to put () method to store it on hashMap, hashMap implementation calls
hashcode() method hashMap key object and by applying that hashcode on its own hashing funtion it identifies a bucket location for storing value object , important part here is HashMap stores both key+value in bucket which is essential to understand the retrieving logic. if people fails to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in HashMap . This answer is very much acceptable and does make sense that interviewee has fair bit of knowledge how hashing works and how HashMap works in Java.
But this is just start of story and going forward when depth increases a little bit and when you put interviewee on scenarios every java developers faced day by day basis. So next question would be more likely about collision detection and collision resolution in Java HashMap ->
"What will happen if two different objects have same hashcode?"
Now from here confusion starts some time interviewer will say that since Hashcode is equal objects are equal and HashMap will throw exception or not store it again etc. then you might want to remind them about equals and hashCode() contract that two unequal object in Java very much can have equal hashcode. Some will give up at this point and some will move ahead and say "Since hashcode () is same, bucket location would be same and collision occurs in hashMap, Since HashMap use a linked list to store in bucket, value object will be stored in next node of linked list." great this answer make sense to me though there could be some other collision resolution methods available this is simplest and HashMap does follow this.
"How will you retreive if two different objects have same hashcode?"
Interviewee will say we will call get() method and then HashMap uses keys hashcode to find out bucket location and retrieves object but then you need to remind him that there are two objects are stored in same bucket , so they will say about traversal in linked list until we find the value object , then you ask how do you identify value object because you don't value object to compare ,So until they know that HashMap stores both Key and Value in linked list node they won't be able to resolve this issue and will try and fail.
But those bunch of people who remember this key information will say that after finding bucket location , we will call keys.equals() method to identify correct node in linked list and return associated value object for that key in Java HashMap. Perfect this is the correct answer.
In many cases interviewee fails at this stage because they get confused between hashcode () and equals () and keys and values object in hashMap which is pretty obvious because they are dealing with the hashcode () in all previous questions and equals () come in picture only in case of retrieving value object from HashMap.
Some good developer point out here that using immutable, final object with proper equals () and hashcode () implementation would act as perfect Java HashMap keys and improve performance of Java hashMap by reducing collision. Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g Integer provided by Java Collection API are very good HashMap keys.
Now if you clear all this java hashmap interview question you will be surprised by this very interesting question "What happens On HashMap in Java if the size of the Hashmap exceeds a given threshold defined by load factor ?". Until you know how hashmap works exactly you won't be able to answer this question.
if the size of the map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%. Java Hashmap does that by creating another new bucket array of size twice of previous size of hashmap, and then start putting every old element into that new bucket array and this process is called rehashing because it also applies hash function to find new bucket location.
If you manage to answer this question on hashmap in java you will be greeted by "do you see any problem with resizing of hashmap in Java" , you might not be able to pick the context and then he will try to give you hint about multiple thread accessing the java hashmap and potentially looking for race condition on HashMap in Java.
So the answer is Yes there is potential race condition exists while resizing hashmap in Java, if two thread at the same time found that now Java Hashmap needs resizing and they both try to resizing. on the process of resizing of hashmap in Java , the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because java hashmap doesn't append the new element at tail instead it append new element at head to avoid tail traversing. if race condition happens then you will end up with an infinite loop. though this point you can potentially argue that what the hell makes you think to use HashMap in multi-threaded environment to interviewer.
Ques 298. What is the difference between Synchronized Collection classes and Concurrent Collection Classes ? When to use what ?
The synchronized collections classes, Hashtable and Vector, and the synchronized wrapper classes, Collections.synchronizedMap and Collections.synchronizedList, provide a basic conditionally thread-safe implementation of Map and List.
However, several factors make them unsuitable for use in highly concurrent applications -- their single collection-wide lock is an impediment to scalability and it often becomes necessary to lock a collection for a considerable time during iteration to prevent ConcurrentModificationExceptions.
The ConcurrentHashMap and CopyOnWriteArrayList implementations provide much higher concurrency while preserving thread safety, with some minor compromises in their promises to callers. ConcurrentHashMap and CopyOnWriteArrayList are not necessarily useful everywhere you might use HashMap or ArrayList, but are designed to optimize specific common situations. Many concurrent applications will benefit from their use.
So what is the difference between hashtable and ConcurrentHashMap , both can be used in multithreaded environment but once the size of hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration.
Since ConcurrentHashMap indroduced concept of segmentation , how large it becomes only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete.
In Summary ConcurrentHashMap only locked certain portion of Map while Hashtable lock full map while doing iteration.
Ques 299. How to use Comparator and Comparable in Java? With example.
Comparators and comparable in Java are two of fundamental interface of Java API which is very important to understand to implement sorting in Java. It’s often required to sort objects stored in any collection class or in Array and that time we need to use compare () and compare To () method defined in java.util.Comparator and java.lang.Comparable class. Let’s see some important points about both Comparable and Comparator in Java before moving ahead
Difference between Comparator and Comparable in Java
1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package.
2) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. While Comparable interface has method public int compareTo(Object o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.
4) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.
5) If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined by CompareTo method.
6)Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.
Ques 300. What is dead lock in thread?
A special type of error that you need to avoid that relates specifically to multitasking is deadlock, which occurs when two threads have a circular dependency on a pair of synchronized objects.
For example, suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will block as expected. However, if the thread in Y, in turn, tries to call any synchronized method on X, the thread waits forever, because to access X, it would have to release its own lock on Y so that the first thread could complete.
Ques 301. What is thread pool in java?
A thread pool is a group of threads initially created that waits for jobs and executes them. The idea is to have the threads always existing, so that we won't have to pay overhead time for creating them every time. They are appropriate when we know there's a stream of jobs to process, even though there could be some time when there are no jobs.
Ques 302. What is concurrency in java?
Concurrency is the ability to run several programs or several parts of a program in parallel. If a time consuming task can be performed asynchronously or in parallel, this improve the throughput and the interactivity of the program.
A modern computer has several CPU's or several cores within one CPU. The ability to leverage these multi-cores can be the key for a successful high-volume application.
Concurrency Issues:
Threads have their own call stack, but can also access shared data. Therefore you have two basic problems, visibility and access problems.
A visibility problem occurs if thread A reads shared data which is later changed by thread B and thread A is unaware of this change.
An access problem can occur if several thread access and change the same shared data at the same time.
Visibility and access problem can lead to
Liveness failure: The program does not react anymore due to problems in the concurrent access of data, e.g. deadlocks.
Safety failure: The program creates incorrect data.
Ques 303. What is Dictionary Class in Java?
Dictionary is an abstract class that represents a key/value storage repository and operates much like Map.
Given a key and value, you can store the value in a Dictionary object. Once the value is stored, you can retrieve it by using its key. Thus, like a map, a dictionary can be thought of as a list of key/value pairs.
The Dictionary class is obsolete. You should implement the Map interface to obtain key/value storage functionality.
Ques 304. What is Reference Handler Thread in Java?
- I suspect it handles running finalizers for the JVM. It's an implementation detail and as such not specified in the JVM spec.
- This only means that the java.lang.ref.Reference$Lock was locked in the method mentioned in the line preceding it (i.e in ReferenceHandler.run().
- "Native Method" simply means that the method is implemented in native (i.e. non-Java) code (think JNI).
- Unknown Source only means that the .class file doesn't contain any source code location information (at least for this specific point). This can happen either when the method is a synthetic one (doesn't look like it here), or the class was compiled without debug information.
- When a thread waits on some object, then it must have locked that object at some point down the call trace, so you can't really have a waiting on without a corresponding locked.
Ques 305. What is Main thread in Java?
3191 // Attach the main thread to this os thread 3192 JavaThread* main_thread = new JavaThread(); 3193 main_thread->set_thread_state(_thread_in_vm); 3194 // must do this before set_active_handles and initialize_thread_local_storage 3195 // Note: on solaris initialize_thread_local_storage() will (indirectly) 3196 // change the stack size recorded here to one based on the java thread 3197 // stacksize. This adjusted size is what is used to figure the placement 3198 // of the guard pages. 3199 main_thread->record_stack_base_and_size(); 3200 main_thread->initialize_thread_local_storage();
3335 // Initialize java_lang.System (needed before creating the thread) 3336 if (InitializeJavaLangSystem) { 3337 initialize_class(vmSymbols::java_lang_System(), CHECK_0); 3338 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK_0); 3339 Handle thread_group = create_initial_thread_group(CHECK_0); 3340 Universe::set_main_thread_group(thread_group()); 3341 initialize_class(vmSymbols::java_lang_Thread(), CHECK_0); 3342 oop thread_object = create_initial_thread(thread_group, main_thread, CHECK_0); 3343 main_thread->set_threadObj(thread_object); 3344 // Set thread status to running since main thread has 3345 // been started and running. 3346 java_lang_Thread::set_thread_status(thread_object, 3347 java_lang_Thread::RUNNABLE);
967 // Creates the initial Thread 968 static oop create_initial_thread(Handle thread_group, JavaThread* thread, TRAPS) { 969 klassOop k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_ NULL); 970 instanceKlassHandle klass (THREAD, k); 971 instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_NULL); 972 973 java_lang_Thread::set_thread(thread_oop(), thread); 974 java_lang_Thread::set_priority(thread_oop(), NormPriority); 975 thread->set_threadObj(thread_oop()); 976 977 Handle string = java_lang_String::create_from_str("main", CHECK_NULL); 978 979 JavaValue result(T_VOID); 980 JavaCalls::call_special(&result, thread_oop, 981 klass, 982 vmSymbols::object_initializer_name(), 983 vmSymbols::threadgroup_string_void_signature(), 984 thread_group, 985 string, 986 CHECK_NULL); 987 return thread_oop(); 988 }
Ques 306. What is Signal Dispatcher thread in Java?
Signal Dispatcher is a thread that handles the native signals sent by the OS to your JVM.
Most helpful rated by users:
- How could Java classes direct program messages to the system console, but error messages, say to a file?
- What are the differences between an interface and an abstract class?
- Why would you use a synchronized block vs. synchronized method?
- How can you force garbage collection?
- What are the differences between the methods sleep() and wait()?