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?
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()?