Java Access Modifiers

Access Modifiers in Java

Access to variables and methods in Java classes is accomplished through access modifiers. Access modifiers define varying levels of access between class members and the outside world (other objects). Access modifiers are declared immediately before the type of a member variable or the return type of a method.

There are four access modifiers in java :

* default
* public
* protected
* private

Access modifiers affect the visibility not only of class members, but also of classes themselves.

Default Access Modifier

The default access modifier specifies that only classes in the same package can have access to a class's variables and methods. Class members with default access have a visibility limited to other classes within the same package. There is no actual keyword for declaring the default access modifier, it is applied by default in the absence of an access modifier.

Code for default access variable and member:

long length;
void getLength() {
return length;
}

Notice that neither the member variable nor the method supplies an access modifier, so each
takes on the default access modifier implicitly.

public Access Modifier

The public access modifier specifies that class variables and methods are accessible to anyone, both inside and outside the class. This means that public class members have global
visibility and can be accessed by any other object.

Sample Code for public member variables:

public int count;
public boolean valid;

protected Access Modifier

The protected access modifier specifies that class members are accessible only to methods in that class and subclasses of that class. This means that protected class members have visibility limited to subclasses.

Sample code for protected variable and a protected method :

protected char Name;
protected char getName() {
return Name;
}

The private Access Modifier

The private access modifier is the most restrictive; it specifies that class members are accessible only by the class in which they are defined. This means that no other class has access to private class members, even subclasses.

Code example for private member variables:

private String firstName;
private double Value;

Access to classes, constructors, methods and fields are regulated using access modifiers. Access modifiers in Java determine the visibility and the scope of the Java elements.

Java Access Modifiers

Access Modifiers in Java

Access to variables and methods in Java classes is accomplished through access modifiers. Access modifiers define varying levels of access between class members and the outside world (other objects). Access modifiers are declared immediately before the type of a member variable or the return type of a method.

There are four access modifiers in java :

* default
* public
* protected
* private

Access modifiers affect the visibility not only of class members, but also of classes themselves.

Default Access Modifier

The default access modifier specifies that only classes in the same package can have access to a class's variables and methods. Class members with default access have a visibility limited to other classes within the same package. There is no actual keyword for declaring the default access modifier, it is applied by default in the absence of an access modifier.

Code for default access variable and member:

long length;
void getLength() {
return length;
}

Notice that neither the member variable nor the method supplies an access modifier, so each
takes on the default access modifier implicitly.

public Access Modifier

The public access modifier specifies that class variables and methods are accessible to anyone, both inside and outside the class. This means that public class members have global
visibility and can be accessed by any other object.

Sample Code for public member variables:

public int count;
public boolean valid;

protected Access Modifier

The protected access modifier specifies that class members are accessible only to methods in that class and subclasses of that class. This means that protected class members have visibility limited to subclasses.

Sample code for protected variable and a protected method :

protected char Name;
protected char getName() {
return Name;
}

The private Access Modifier

The private access modifier is the most restrictive; it specifies that class members are accessible only by the class in which they are defined. This means that no other class has access to private class members, even subclasses.

Code example for private member variables:

private String firstName;
private double Value;

Access to classes, constructors, methods and fields are regulated using access modifiers. Access modifiers in Java determine the visibility and the scope of the Java elements.

Java Static Modifier

Static Modifier in Java:

In java we can have a Static Block, Static Variable, Static Method. Static modifier specifies that a variable or method is the same for all objects of a particular class. Some times we need a common variable or method for all objects of a part icular class. Typically, new variables are allocated for each instance of a class.

Variable declared as being static is only allocated once, regardless of how many objects are instantiated and all instantiated objects share the same instance of the static variable. Similarly, a static method is one whose implementation is exactly the same for all objects of a part icular class. Static methods have access only to static variables.

Example of a static member variable and a static method:

static int refCount;
static int getRefCount() {
return refCount;
}

A beneficial side effect of static members is that they can be accessed without having to create an instance of a class. Static method or a variable is not attached to a particular object, but rather to the class as a whole. They are allocated when the class is loaded.

A static initializer block resembles a method with no name, no arguments, and no return type. It doesn't need a name, because there is no need to refer to it from outside the class definition. The code in a static initializer block is executed by the virtual machine when the class is loaded.

Example of a Static Block

static{
date1 = new Date();
for(int count = 0; count <>
var = var+1;
}

Static blocks are blocks defined within the body of a class using the static keyword but which are not inside any other blocks.

Java Static Modifier

Static Modifier in Java:

In java we can have a Static Block, Static Variable, Static Method. Static modifier specifies that a variable or method is the same for all objects of a particular class. Some times we need a common variable or method for all objects of a part icular class. Typically, new variables are allocated for each instance of a class.

Variable declared as being static is only allocated once, regardless of how many objects are instantiated and all instantiated objects share the same instance of the static variable. Similarly, a static method is one whose implementation is exactly the same for all objects of a part icular class. Static methods have access only to static variables.

Example of a static member variable and a static method:

static int refCount;
static int getRefCount() {
return refCount;
}

A beneficial side effect of static members is that they can be accessed without having to create an instance of a class. Static method or a variable is not attached to a particular object, but rather to the class as a whole. They are allocated when the class is loaded.

A static initializer block resembles a method with no name, no arguments, and no return type. It doesn't need a name, because there is no need to refer to it from outside the class definition. The code in a static initializer block is executed by the virtual machine when the class is loaded.

Example of a Static Block

static{
date1 = new Date();
for(int count = 0; count <>
var = var+1;
}

Static blocks are blocks defined within the body of a class using the static keyword but which are not inside any other blocks.

Java Garbage Collection

Garbage Collection in Java

Java has built-in facility to re-claim unwanted memory, this is known as garbage collection. Garbage collector plays its role if there is any memory defficiency. Usually an object no longer referenced, for example when you assign with null, it could be ready for garbage collection. In java all objects are created in heap memory, whereas primitive type and object reference are placed in stack memory. Object class has defined finalize() method that is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

The purpose of Java 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. Java Garbage collection is an automatic process and can't be forced.

Java Garbage Collection program

class GC
{
public static void main(String args[]){
MyObj obj = new MyObj();
obj=null;
System.gc();
}
}

class MyObj
{
public MyOb(){
System.out.println("Object created");
}
protected void finalize()
{
System.out.println("Garbage collector in action");
}
}

Garbage collection will start immediately upon request of System.gc(). 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.

Java Garbage Collection

Garbage Collection in Java

Java has built-in facility to re-claim unwanted memory, this is known as garbage collection. Garbage collector plays its role if there is any memory defficiency. Usually an object no longer referenced, for example when you assign with null, it could be ready for garbage collection. In java all objects are created in heap memory, whereas primitive type and object reference are placed in stack memory. Object class has defined finalize() method that is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

The purpose of Java 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. Java Garbage collection is an automatic process and can't be forced.

Java Garbage Collection program

class GC
{
public static void main(String args[]){
MyObj obj = new MyObj();
obj=null;
System.gc();
}
}

class MyObj
{
public MyOb(){
System.out.println("Object created");
}
protected void finalize()
{
System.out.println("Garbage collector in action");
}
}

Garbage collection will start immediately upon request of System.gc(). 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.

Java Program to list the Contents of a Zip File

Java Sample program to list the contents of a zip file

In this program we need to get the entries of the zip file, since each file in a zip file is represented by an entry. In this program assume that the filename of the zip file is 'Test.zip'. By calling the entries method of the ZipFile object we get an Enumeration back that can be used to loop through the entries of the file. We have to cast each element in the Enumeration to a ZipEntry.

import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.io.IOException;
import java.util.Enumeration;

public class ListZipFiles
{
public void doListFiles()
{
try
{
ZipFile zipFile = new ZipFile("Test.zip");
Enumeration zipEntries = zipFile.entries();

while (zipEntries.hasMoreElements())
{
//Process the name, here we just print it out
System.out.println(((ZipEntry)zipEntries.nextElement()).getName());
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
// Command line arguments
public static void main(String[] args) {

new Main().doListFiles();
}
}

Java Program to list the Contents of a Zip File

Java Sample program to list the contents of a zip file

In this program we need to get the entries of the zip file, since each file in a zip file is represented by an entry. In this program assume that the filename of the zip file is 'Test.zip'. By calling the entries method of the ZipFile object we get an Enumeration back that can be used to loop through the entries of the file. We have to cast each element in the Enumeration to a ZipEntry.

import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.io.IOException;
import java.util.Enumeration;

public class ListZipFiles
{
public void doListFiles()
{
try
{
ZipFile zipFile = new ZipFile("Test.zip");
Enumeration zipEntries = zipFile.entries();

while (zipEntries.hasMoreElements())
{
//Process the name, here we just print it out
System.out.println(((ZipEntry)zipEntries.nextElement()).getName());
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
// Command line arguments
public static void main(String[] args) {

new Main().doListFiles();
}
}

STRING OBJECTS in JAVA

The Java String class (java.lang.String) is a class of object that represents a character array of arbitrary length. While this external class can be used to handle string objects, Java integrates internal, built-in strings into the language.

An important attribute of the String class is that once a string object is constructed, its value cannot change (note that it is the value of an object that cannot change, not that of a string variable, which is just a reference to a string object). All String data members are private, and no string method modifies the string’s value.

CONVERTING OBJECTS TO STRINGS

The String + operator accepts a non-string operand, provided the other operand is a string. The action of the + operator on non-string operands is to convert the non-string to a string, then to do the concatenation. Operands of native types are converted to string by formatting their values. Operands of class types are converted to a string by the method toString()
that is defined for all classes. Any object or value can be converted to a string by explicitly using one of the static valueOf() methods defined in class String:

String str = String.valueOf (obj);

If the argument to valueOf() is of class type, then valueOf() calls that object’s toString() method. Any class can define its own toString() method, or just rely on the default. The output produced by toString() is suitable for debugging and diagnostics. It is not meant to be an elaborate text representation of the object, nor is it meant to be parsed. These conversion rules also apply to the right-hand side of the String += operator.

CONVERTING STRINGS TO NUMBERS

Methods from the various wrapper classes, such as Integer and Double, can be used to convert numerical strings to numbers. This is often necessary for command line arguments where the parameter list is available to the main () method as a string array. The wrapper classes contain static methods ( such as parseInt() ) which convert a string to its own internal data type.

These can be used with class names rather than creating a separate object. Be aware that these particular conversion methods throw a NumberFormatException and must be used in the context of a try and catch block combination.

STRING OBJECTS in JAVA

The Java String class (java.lang.String) is a class of object that represents a character array of arbitrary length. While this external class can be used to handle string objects, Java integrates internal, built-in strings into the language.

An important attribute of the String class is that once a string object is constructed, its value cannot change (note that it is the value of an object that cannot change, not that of a string variable, which is just a reference to a string object). All String data members are private, and no string method modifies the string’s value.

CONVERTING OBJECTS TO STRINGS

The String + operator accepts a non-string operand, provided the other operand is a string. The action of the + operator on non-string operands is to convert the non-string to a string, then to do the concatenation. Operands of native types are converted to string by formatting their values. Operands of class types are converted to a string by the method toString()
that is defined for all classes. Any object or value can be converted to a string by explicitly using one of the static valueOf() methods defined in class String:

String str = String.valueOf (obj);

If the argument to valueOf() is of class type, then valueOf() calls that object’s toString() method. Any class can define its own toString() method, or just rely on the default. The output produced by toString() is suitable for debugging and diagnostics. It is not meant to be an elaborate text representation of the object, nor is it meant to be parsed. These conversion rules also apply to the right-hand side of the String += operator.

CONVERTING STRINGS TO NUMBERS

Methods from the various wrapper classes, such as Integer and Double, can be used to convert numerical strings to numbers. This is often necessary for command line arguments where the parameter list is available to the main () method as a string array. The wrapper classes contain static methods ( such as parseInt() ) which convert a string to its own internal data type.

These can be used with class names rather than creating a separate object. Be aware that these particular conversion methods throw a NumberFormatException and must be used in the context of a try and catch block combination.

java guru: more java interview questions

java guru: more java interview questions: "Q: What is the difference between an Interface and an Abstract class? A: An abstract class can have instance methods that implement a defaul..."

java guru: more java interview questions

java guru: more java interview questions: "Q: What is the difference between an Interface and an Abstract class? A: An abstract class can have instance methods that implement a defaul..."

more java interview questions

Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

Q: Difference between HashMap and HashTable?
A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.

Q: What are Checked and UnChecked Exception?
A: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Q: What are different types of inner classes?
A: Nested top-level classes, Member classes, Local classes, Anonymous classes

Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.
Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a
more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

Q: When you serialize an object, what happens to the object references included in the object?
A: The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.

Q: Give a simplest way to find out the time a method takes for execution without using any profiling tool?
A: Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.

To put it in code...

long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();

System.out.println ("Time taken for execution is " + (end - start));

Q: What is daemon thread and which method is used to create the daemon thread?
A: Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.

Q: What modifiers are allowed for methods in an Interface?
A: Only public and abstract modifiers are allowed for methods in interfaces.

Q: What is transient variable?
A: Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

Q: Explain garbage collection?
A: Garbage collection is one of the most important feature of Java. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. 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. I 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.

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

more java interview questions

Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

Q: Difference between HashMap and HashTable?
A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.

Q: What are Checked and UnChecked Exception?
A: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Q: What are different types of inner classes?
A: Nested top-level classes, Member classes, Local classes, Anonymous classes

Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.
Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a
more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

Q: When you serialize an object, what happens to the object references included in the object?
A: The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.

Q: Give a simplest way to find out the time a method takes for execution without using any profiling tool?
A: Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.

To put it in code...

long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();

System.out.println ("Time taken for execution is " + (end - start));

Q: What is daemon thread and which method is used to create the daemon thread?
A: Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.

Q: What modifiers are allowed for methods in an Interface?
A: Only public and abstract modifiers are allowed for methods in interfaces.

Q: What is transient variable?
A: Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

Q: Explain garbage collection?
A: Garbage collection is one of the most important feature of Java. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. 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. I 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.

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

core java interview questions

1. Can there be an abstract class with no abstract methods in it?
Yes

2. Can an Interface be final?
No

3. Can an Interface have an inner class?
Yes.
public interface abc
{
static int i=0; void dd();
class a1
{
a1()
{
int j;
System.out.println("inside");
};
public static void main(String a1[])
{
System.out.println("in interface");
}
}
}


4. Can we define private and protected modifiers for variables in interfaces?
No

5. 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)

6. What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.

7. 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

8. 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

9. 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).

10. 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().

11. 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.

12. 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();

13. 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.

14. 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.

15. Is null a keyword?
The null value is not a keyword.

16. 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.

17. 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.

18. 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.

19. What are wrapper classes?
Wrapper classes are classes that allow primitive types to be accessed as objects.

20. 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).

21. 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.

22. What is a native method?
A native method is a method that is implemented in a language other than Java.

23. 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

24. 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.

25. 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.

26. What is the range of the char type?
The range of the char type is 0 to 2^16 - 1.

core java interview questions

1. Can there be an abstract class with no abstract methods in it?
Yes

2. Can an Interface be final?
No

3. Can an Interface have an inner class?
Yes.
public interface abc
{
static int i=0; void dd();
class a1
{
a1()
{
int j;
System.out.println("inside");
};
public static void main(String a1[])
{
System.out.println("in interface");
}
}
}


4. Can we define private and protected modifiers for variables in interfaces?
No

5. 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)

6. What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.

7. 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

8. 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

9. 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).

10. 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().

11. 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.

12. 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();

13. 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.

14. 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.

15. Is null a keyword?
The null value is not a keyword.

16. 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.

17. 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.

18. 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.

19. What are wrapper classes?
Wrapper classes are classes that allow primitive types to be accessed as objects.

20. 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).

21. 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.

22. What is a native method?
A native method is a method that is implemented in a language other than Java.

23. 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

24. 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.

25. 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.

26. What is the range of the char type?
The range of the char type is 0 to 2^16 - 1.

General Java Interview Questions

Core Java :
What is a virtual function in C++?
Simply put, the virtual keyword enables a function to be 'virtual' which then gives possibility for that function to be overridden (redefined) in one or more descendant classes. It is a good feature since the specific function to call is determined at run-time. In other words, a virtual function allows derived classes to replace the implementation provided by the base class.

--------------------------------------------------------------------------------

What is the difference between private, protected, and public?
These keywords are for allowing privilages to components such as functions and variables.
Public: accessible to all classes
Private: accessible only to the class to which they belong
Protected: accessible to the class to which they belong and any subclasses.

--------------------------------------------------------------------------------
What is a cartesian product in PL/SQL?
When a Join condition is not specified by the programmer or is invalid(fails), PL/SQL forms a Cartesian product.
In a Cartesian product, all combinations of rows will be displayed.
For example, All rows in the first table are joined to all rows in the second table. It joins a bunch of rows and it's result is rarely useful unless you have a need to combine all rows from all tables.
-------------------------------------------------------------------------------
What is mutual exclusion? How can you take care of mutual exclusion using Java threads?
Mutual exclusion is where no two processes can access critical regions of memory at the same time.
Java provides many utilities to deal with mutual exclusion with the use of threaded programming.
For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on.
The runtime system/Java compiler takes care of the gruesome details for you. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.
--------------------------------------------------------------------------------
What are some advantages and disadvantages of Java Sockets?
Some advantages of Java Sockets:

Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications.


Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.

Some disadvantages of Java Sockets:

Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network

Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

Since the data formats and protocols remain application specific, the re-use of socket based implementations is limited.

What is the difference between an Interface and an Abstract class?
An Abstract class declares have at least one instance method that is declared abstract which will be implemented by the subclasses. An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior.
--------------------------------------------------------------------------------
What is the purpose of garbage collection in Java, and when is it used?
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.
--------------------------------------------------------------------------------
Describe synchronization in respect to multithreading.?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
--------------------------------------------------------------------------------
Explain different way of using thread?
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.
--------------------------------------------------------------------------------
What are pass by reference and passby value?
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.
--------------------------------------------------------------------------------
What is HashMap and Map?
Map is Interface and Hashmap is class that implements that.
--------------------------------------------------------------------------------
Difference between HashMap and HashTable?
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is non synchronized and Hashtable is synchronized.
--------------------------------------------------------------------------------
Difference between Vector and ArrayList?
Vector is synchronized whereas arraylist is not.
--------------------------------------------------------------------------------
Difference between Swing and Awt?
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.
--------------------------------------------------------------------------------
What is the difference between a constructor and a method?
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
--------------------------------------------------------------------------------
What is an Iterators?
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.
--------------------------------------------------------------------------------
State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.?
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.
--------------------------------------------------------------------------------
What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
--------------------------------------------------------------------------------
What is static in java?
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

---------------------------------------------------------------------------------
What is final?
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
--------------------------------------------------------------------------------
Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol symbol : class ABCD location: package io import java.io.ABCD;
--------------------------------------------------------------------------------
Does importing a package imports the subpackages as well?
e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.
--------------------------------------------------------------------------------
What is the difference between declaring a variable and defining a variable?
In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization. e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.
--------------------------------------------------------------------------------
What is the default value of an object reference declared as an instance variable?
null unless we define it explicitly.
--------------------------------------------------------------------------------
Can a level class be private or protected?
No. A level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a level class can not be private. Same is the case with protected.
--------------------------------------------------------------------------------
What type of parameter passing does Java support?
In Java the arguments are always passed by value .
--------------------------------------------------------------------------------
Primitive data types are passed by reference or pass by value?
Primitive data types are passed by value.
--------------------------------------------------------------------------------
Objects are passed by value or by reference?
Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .
--------------------------------------------------------------------------------
What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
--------------------------------------------------------------------------------
How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
--------------------------------------------------------------------------------
Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.
--------------------------------------------------------------------------------
How can I customize the seralization process?
i.e. how can one have a control over the serialization process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.
--------------------------------------------------------------------------------
What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
---------------------------------------------------------------------------------
What is the common usage of serialization?
Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.
-------------------------------------------------------------------------------
What is Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.
--------------------------------------------------------------------------------
What happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.
--------------------------------------------------------------------------------
What one should take care of while serializing the object?
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.
--------------------------------------------------------------------------------
What if the main method is declared as private?
The program compiles properly but at runtime it will give "Main method not public." message.
--------------------------------------------------------------------------------
What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
--------------------------------------------------------------------------------
What if I write static public void instead of public static void?
Program compiles and runs properly.
--------------------------------------------------------------------------------
What if I do not provide the String array as the argument to the method?
Program compiles but throws a runtime error "NoSuchMethodError".
--------------------------------------------------------------------------------
What is the first argument of the String array in main method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.
--------------------------------------------------------------------------------
If I do not provide any arguments on the command line, then the String array of Main method will be empty of null?
It is empty. But not null.
--------------------------------------------------------------------------------
How can one prove that the array is not null but empty?
Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.
--------------------------------------------------------------------------------
What environment variables do I need to set on my machine in order to be able to run Java programs?
CLASSPATH and PATH are the two variables.
--------------------------------------------------------------------------------
Can an application have multiple classes having main method?
Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
--------------------------------------------------------------------------------
Can I have multiple main methods in the same class?
No the program fails to compile. The compiler says that the main method is already defined in the class.
--------------------------------------------------------------------------------
Do I need to import java.lang package any time? Why ?
No. It is by default loaded internally by the JVM.
--------------------------------------------------------------------------------
Can I import same package/class twice?
Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.
--------------------------------------------------------------------------------
What are Checked and UnChecked Exception?
A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method
----------------------------------------------------------------------------------
checked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
--------------------------------------------------------------------------------
What is Overriding?
When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.
-------------------------------------------------------------------------------
What are different types of inner classes?
They are
Nested -level classes, Member classes, Local classes, Anonymous classes

Nested -level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other -level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. -level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested -level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested -level class. The primary difference between member classes and nested -level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

-----------------------------------------------------------------------------------
Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol symbol : class ABCD location: package io import java.io.ABCD;
--------------------------------------------------------------------------------
Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.
-------------------------------------------------------------------------------
What is the difference between declaring a variable and defining a variable?
In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization. e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.
--------------------------------------------------------------------------------
What is the default value of an object reference declared as an instance variable?
null unless we define it explicitly.
--------------------------------------------------------------------------------
Can a level class be private or protected?
No. A level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a level class can not be private. Same is the case with protected.
--------------------------------------------------------------------------------
What type of parameter passing does Java support?
In Java the arguments are always passed by value .
--------------------------------------------------------------------------------
Primitive data types are passed by reference or pass by value?
Primitive data types are passed by value.
--------------------------------------------------------------------------------
Objects are passed by value or by reference?
Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .
--------------------------------------------------------------------------------
What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
--------------------------------------------------------------------------------
How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
--------------------------------------------------------------------------------
Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.
--------------------------------------------------------------------------------
How can I customize the seralization process?
i.e. how can one have a control over the serialization process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.
--------------------------------------------------------------------------------
What is the common usage of serialization?
Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.
--------------------------------------------------------------------------------
What is Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.
--------------------------------------------------------------------------------
What happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.
--------------------------------------------------------------------------------
What one should take care of while serializing the object?
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.
--------------------------------------------------------------------------------
What happens to the static fields of a class during serialization?
Are these fields serialized as a part of each serialized object?
Yes the static fields do get serialized. If the static field is an object then it must have implemented Serializable interface. The static fields are serialized as a part of every object. But the commonness of the static fields across all the instances is maintained even after serialization.
--------------------------------------------------------------------------------
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. [Received from Venkateswara Manam]
--------------------------------------------------------------------------------
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.
--------------------------------------------------------------------------------
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.
--------------------------------------------------------------------------------
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 .
--------------------------------------------------------------------------------
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.
--------------------------------------------------------------------------------
When a thread is created and started, what is its initial state?
A thread is in the ready state after it has been created and started.
--------------------------------------------------------------------------------
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.
--------------------------------------------------------------------------------
What is the Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
--------------------------------------------------------------------------------
What is the difference between a while statement and a do statement?
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
--------------------------------------------------------------------------------
What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
--------------------------------------------------------------------------------
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.
-------------------------------------------------------------------------------
Servlets:


Explain the life cycle methods of a Servlet.
The javax.servlet.Servlet interface defines the three methods known as life-cycle method. public void init(ServletConfig config) throws ServletException public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException public void destroy() First the servlet is constructed, then initialized wih the init() method. Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet. The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.
--------------------------------------------------------------------------------
What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.
The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.
--------------------------------------------------------------------------------
Explain the directory structure of a web application.
The directory structure of a web application consists of two parts. A private directory called WEB-INF A public resource directory which contains public resource folder. WEB-INF folder consists of 1. web.xml
2. classes directory
3. lib directory
--------------------------------------------------------------------------------
What are the common mechanisms used for session tracking?
Cookies SSL sessions URL- rewriting
--------------------------------------------------------------------------------
Explain ServletContext.
ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.
--------------------------------------------------------------------------------
What is preinitialization of a servlet?
A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.
--------------------------------------------------------------------------------
What is the difference between Difference between doGet() and doPost()?
A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following: http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN


doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.
--------------------------------------------------------------------------------
What is the difference between HttpServlet and GenericServlet?
A GenericServlet has a service() method aimed to handle requests.
HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.
---------------------------------------------------------------------------------
JSP:
What is a output comment?
A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser. JSP Syntax Example 1 Displays in the page source:
--------------------------------------------------------------------------------
What is a Hidden Comment?
A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page. You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>. JSP Syntax Examples
--------------------------------------------------------------------------------
What is a _Expression?
An _expression tag contains a scripting language _expression that is evaluated, converted to a String, and inserted where the _expression appears in the JSP file. Because the value of an _expression is converted to a String, you can use an _expression within text in a JSP file. Like You cannot use a semicolon to end an _expression
--------------------------------------------------------------------------------
What is a Declaration?
A declaration declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.
--------------------------------------------------------------------------------
What is a Scriptlet?
A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can

1.Declare variables or methods to use later in the file (see also Declaration).

2.Write expressions valid in the page scripting language (see also _Expression).

3.Use any of the JSP implicit objects or any object declared with a tag.

You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet. Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.
--------------------------------------------------------------------------------
What are implicit objects? List them?
Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below request response pageContext session application out config page exception
--------------------------------------------------------------------------------
Difference between forward and sendRedirect?
When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
--------------------------------------------------------------------------------
What are the different scope valiues for the ?
The different scope values for are
1. page
2. request
3.session
4.application
--------------------------------------------------------------------------------
Explain the life-cycle mehtods in JSP?
THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces.

The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol.

However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests.
This interface declares one method _jspService(). The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.

posted by Arpan The Progress at 12:17 AM 0 comments
C++

C++ Interview Questions

Is it possible to have Virtual Constructor? If yes, how?If not, Why not possible ?
There is nothing like Virtual Constructor.
The Constructor cant be virtual as the constructor is a code which is responsible for creating a instance of a class and it cant be delegated to any other object by virtual keyword means.
--------------------------------------------------------------------------------
What about Virtual Destructor?
Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime depending on the type of object baller is balling to , proper destructor will be called.
--------------------------------------------------------------------------------
What is Pure Virtual Function? Why and when it is used ?
The abstract class whose pure virtual method has to be implemented by all the classes which derive on these. Otherwise it would result in a compilation error.
This construct should be used when one wants to ensure that all the derived classes implement the method defined as pure virtual in base class.
--------------------------------------------------------------------------------
What is problem with Runtime type identification?
The run time type identification comes at a cost of performance penalty. Compiler maintains the class.
--------------------------------------------------------------------------------
How Virtual functions call up is maintained?
Through Look up tables added by the compile to every class image. This also leads to performance penalty.
--------------------------------------------------------------------------------
Can inline functions have a recursion?
No.
Syntax wise It is allowed. But then the function is no longer Inline. As the compiler will never know how deep the recursion is at compilation time.
--------------------------------------------------------------------------------
How do you link a C++ program to C functions?
By using the extern "C" linkage specification around the C function declarations.
Programmers should know about mangled function names and type-safe linkages. Then they should explain how the extern "C" linkage specification statement turns that feature off during compilation so that the linker properly links function calls to C functions.
--------------------------------------------------------------------------------
Explain the scope resolution operator?
It permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.
--------------------------------------------------------------------------------
How many ways are there to initialize an int with a constant?
1. int foo = 123;
2. int bar(123);
-------------------------------------------------------------------------------
What is your reaction to this line of code? delete this;
It is not a good programming Practice.
A good programmer will insist that you should absolutely never use the statement if the class is to be used by other programmers and instantiated as static, extern, or automatic objects. That much should be obvious.
The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in. Subsequent dereferencing of the baller can and usually does lead to disaster. I think that the language rules should disallow the idiom, but that's another matter.
--------------------------------------------------------------------------------
What is the difference between a copy constructor and an overloaded assignment operator?
A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.
--------------------------------------------------------------------------------
When should you use multiple inheritance?
There are three acceptable answers:- "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way."
Consider an Asset class, Building class, Vehicle class, and CompanyCar class. All company cars are vehicles. Some company cars are assets because the organizations own them. Others might be leased. Not all assets are vehicles. Money accounts are assets. Real estate holdings are assets. Some real estate holdings are buildings. Not all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes apparent that multiple inheritance is a likely and intuitive way to model this common problem domain. The applicant should understand, however, that multiple inheritance, like a chainsaw, is a useful tool that has its perils, needs respect, and is best avoided except when nothing else will do.
--------------------------------------------------------------------------------
What is a virtual destructor?
The simple answer is that a virtual destructor is one that is declared with the virtual attribute.
The behavior of a virtual destructor is what is important. If you destroy an object through a baller or reference to a base class, and the base-class destructor is not virtual, the derived-class destructors are not executed, and the destruction might not be comple
--------------------------------------------------------------------------------
Can a constructor throw a exception? How to handle the error when the constructor fails?
The constructor never throws a error.
--------------------------------------------------------------------------------
What are the debugging methods you use when came across a problem?
Debugging with tools like :
GDB, DBG, Forte, Visual Studio.

Analyzing the Core dump.

Using tusc to trace the last system call before crash.

Putting Debug statements in the program source code.
--------------------------------------------------------------------------------
How the compilers arranges the various sections in the executable image?
The executable had following sections:-
Data Section (uninitialized data variable section, initialized data variable section )
Code Section
Remember that all static variables are allocated in the initialized variable section.
--------------------------------------------------------------------------------
Explain the ISA and HASA class relationships. How would you implement each in a class design?
A specialized class "is" a specialization of another class and, therefore, has the ISA relationship with the other class.
This relationship is best implemented by embedding an object of the Salary class in the Employee class.
-------------------------------------------------------------------------------
When is a template a better solution than a base class?
When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the generality) to the designer of the container or manager class.
--------------------------------------------------------------------------------
What are the differences between a C++ struct and C++ class?
The default member and base-class access specifies are different.
This is one of the commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++ struct is just like a C struct, while a C++ class has inheritance, access specifies, member functions, overloaded operators, and so on. Actually, the C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base-class inheritance, and a class defaults to the private access specified and private base-class inheritance.
--------------------------------------------------------------------------------
How do you know that your class needs a virtual destructor?
If your class has at least one virtual function, you should make a destructor for this class virtual. This will allow you to delete a dynamic object through a baller to a base class object. If the destructor is non-virtual, then wrong destructor will be invoked during deletion of the dynamic object.
--------------------------------------------------------------------------------
What is the difference between new/delete and malloc/free?
Malloc/free do not know about constructors and destructors. New and delete create and destroy objects, while malloc and free allocate and deallocate memory.
--------------------------------------------------------------------------------
What happens when a function throws an exception that was not specified by an exception specification for this function?
Unexpected() is called, which, by default, will eventually trigger abort().
--------------------------------------------------------------------------------
Can you think of a situation where your program would crash without reaching the breakball, which you set at the beginning of main()?
C++ allows for dynamic initialization of global variables before main() is invoked. It is possible that initialization of global will invoke some function. If this function crashes the crash will occur before main() is entered.
--------------------------------------------------------------------------------
What issue do auto_ptr objects address?
If you use auto_ptr objects you would not have to be concerned with heap objects not being deleted even if the exception is thrown.
--------------------------------------------------------------------------------
Is there any problem with the following:
char *a=NULL; char& p = *a;?
The result is undefined. You should never do this. A reference must always refer to some object.
--------------------------------------------------------------------------------
Why do C++ compilers need name mangling?
Name mangling is the rule according to which C++ changes function's name into function signature before passing that function to a linker. This is how the linker differentiates between different functions with the same name.
--------------------------------------------------------------------------------
What is Polymorphism?
'Polymorphism' is an object oriented term. Polymorphism may be defined as the ability of related objects to respond to the same message with different, but appropriate actions. In other words, polymorphism means taking more than one form. Polymorphism leads to two important aspects in Object Oriented terminology - Function Overloading and Function Overriding. Overloading is the practice of supplying more than one definition for a given function name in the same scope. The compiler is left to pick the appropriate version of the function or operator based on the arguments with which it is called. Overriding refers to the modifications made in the sub class to the inherited methods from the base class to change their behaviour.
--------------------------------------------------------------------------------
What is Operator overloading?
When an operator is overloaded, it takes on an additional meaning relative to a certain class. But it can still retain all of its old meanings.
Examples:
1) The operators >> and << may be used for I/O operations because in the header, they are overloaded.
2) In a stack class it is possible to overload the + operattor so that it appends the contents of one stack to the contents of another. But the + operator still retains its original meaning relative to other types of data.
--------------------------------------------------------------------------------
What is the difference between run time binding and compile time binding?
Dynamic Binding :
The address of the functions are determined at runtime rather than @ compile time. This is also known as "Late Binding".

Static Binding :
The address of the functions are determined at compile time rather than @ run time. This is also known as "Early Binding"
--------------------------------------------------------------------------------
When constructing an XML DTD, how do you create an external entity reference in an attribute value?

Every interview session should have at least one trick question. Although possible when using SGML, XML DTDs don't support defining external entity references in attribute values. It's more important for the candidate to respond to this question in a logical way than than the candidate know the somewhat obscure answer.
--------------------------------------------------------------------------------
How would you build a search engine for large volumes of XML data?
The way candidates answer this question may provide insight into their view of XML data. For those who view XML primarily as a way to denote structure for text files, a common answer is to build a full-text search and handle the data similarly to the way Internet portals handle HTML pages. Others consider XML as a standard way of transferring structured data between disparate systems. These candidates often describe some scheme of importing XML into a relational or object database and relying on the database's engine for searching. Lastly, candidates that have worked with vendors specializing in this area often say that the best way the handle this situation is to use a third party software package optimized for XML data.