Friday, September 26, 2014

MFC interview questions



What is MFC?

MFC is the C++ class library Microsoft provides to place an object-oriented wrapper around the Windows API.The Microsoft Foundation Class (MFC) Library is a collection of classes written in the C++ that can be used in building application programs. It  allows developers to more easily work with Windows operating systems and in developing Windows applications.

What is the difference between the ASSERT and VERIFY macros?

Both ASSERT and VERIFY macros behave in the same Manner in debug Version.But in Release version the Expression in the ASSERT is ignored. And in Release version the Expression in the VERIFY is evaluated. But not verified. Means the expression is evaluated. And like dubug it is NOT stop the execution if the expression evaluated to FALSE

Can you explain the relashionship between document,frame and view ?

The frame window is the application's top-level window. It's normally a WS_OVERLAPPEDWINDOW-style window with a resizing border, a title bar, a system menu, and minimize, maximize, and close buttons. 
The view is a child window sized to fit the frame window so that it becomes the frame window's client area. 
The application's data is stored in the document object, a visible representation of which appears in the view. 
For an SDI application, the frame window class is derived from CFrameWnd, the document class is derived from CDocument, and the view class is derived from CView or a related class such as CScrollView.



What is the difference between hinsrtance and hprevinstance in WinMain function?

hInstance : will be having the handle of the current instance 
hPrevInctance : will be having the handle of last instance. hPrevInstance is NULL if only one instance is running
if you are using 32-bit os then the entry to the hPrevInstance is always NULL.
It was used in the 16 bit os where the instance of previosly running application was saved . so that it can be refered again ! due the memory restriction.

What is the difference between hinsrtance and hprevinstance in WinMain function?

hInstance : will be having the handle of the current instance 
hPrevInctance : will be having the handle of last instance. hPrevInstance is NULL if only one instance is running
if you are using 32-bit os then the entry to the hPrevInstance is always NULL.
It was used in the 16 bit os where the instance of previosly running application was saved . so that it can be refered again ! due the memory restriction.

Explain about MDI and CMultiDocTemplate ?

To Established the relationship between CView and CDocument with CDoctemplate and Multidoctemplate.Cdoctemplate for SDI and CMultidoctemplate for MDI

What function is used to disable a control at runtime?

// Get a pointer to the control's window.
CWnd *p = GetDlgItem(IDC_NEWCONTROL);

// Disable the control.
p->EnableWindow(FALSE);



Which CPrintInfo member variable must be set for multiple page printouts?

RTTI (Run Time Type Identification) in MFC can be handled by using the class CRunTimeClass. 
But CRunTimeClass can be use to identify the type of the class which are derived from CObject.
 
For eg -
 
    void MyFunction()
    {
       CObject *mObject = new MyClass;
       if(mObject->IsKindOf(RUNTIME_CLASS( MyClass) ) )
       {
          printf("Class is of type MyClass\n");
       }
       else
       {
          printf("Class is of type someotherclass\n");
       }
    } 
 
We can use "type_info" for other type of classes which are 
not derived from CObject.

What is the use of CObject::Dump function ?

Dumps the contents of your object.When you write your own class, you should override the Dump function to provide diagnostic services for yourself and other users of your class. The overridden Dump usually calls the Dump function of its base class before printing data members unique to the derived class.Dump function should not print a newline character at the end of its output.Dump is a const function, you are not permitted to change the object state during the dump.

// example for CObject::Dump
void CAge::Dump( CDumpContext &dc ) const
 {
        CObject::Dump( dc );
        dc << "Age = " << m_years;
 }

What is the use of UpdateData funciton ?

UpdateData function is used to get or set the values in your appropriate control variables.  UpdateData ( FALSE ) would update the data from control variables to control, while UpdateData ( TRUE ) would assing the data from controls to control variable.

This function need not be called if you are using DDX ( Dynamic Data Exchange ).

BOOL UpdateData( BOOL bSaveAndValidate = TRUE );

UpdateData(TRUE) indicate dialog box is being initialized
UpdateData(FALSE) indicates data is being retrieved from the
dialog box.

Call this member function to initialize data in a dialog box, or to retrieve and validate dialog data.

What is the difference between GetMessage and PeekMessage ?

The major difference between the two is that GetMessage() doesn't return until it finds a message to retrieve from the Application Queue, this allows us to free up precious CPU
usage for other programs to use. PeekMessage() returns immediately weather there are any messages or not, this allows us to utilize the time between messages, for example
to render a 3D scene.

How to update all the views whenver document got updated ?

Calling UpdateAllViews() function

What are the types of button controls?

  • Command Button 
  • Radio Button

What is the base class for most MFC classes?

CObject

How to handle command line arguements from simple MFC application?

m_lpCmdLine Corresponds to the lpCmdLine parameter passed by Windows to WinMain. Points to a null-terminated string that specifies the command line for the application. Use m_lpCmdLine to access any command-line arguments the user entered when the application was started. m_lpCmdLine is a public variable of type LPTSTR.

If I derive a new class from CObject what are the basic features my derived will get?

Searialization, Debugging support, Runtime time class information, compatibility with collection classes.

What is the use of CCmdTarget ?

It is the base class for the MFC library message map architecture.Which maps commands/messages to the member functions to handle them. Classes derived from this are CWnd,CWinApp,CFrameWnd,CView, CDocument

How to access document object from view ?

Using GetDocument() function within a CView class.

What is the entry point for window based applications ?

WinMain() is the entry point for window based applications.

What is the use of message map ?

Message map is a macro used to handle messgaes by calling appropriate functions. i.e
      
               BEGIN_MESSAGE_MAP(CMywnd,CFrameWnd)
                              ON_WM_PAINT()
               END_MESSAGE_MAP

Here OnPaint method will be called whn WM_PAINT message comes. MessageMap is a logical table that maps the windows messages to the member functions of the class. MFC handles Windows message in a different way. Because MFC applications are built upon classes, it is more convenient to handle messages within class member functions instead of one big callbackfunction.In MFC, this is achieved through message mapping: we can implement the functions that will be used to execute commands, and use macros defined in MFC to direct the messages into these member functions.

How to convert a CString variable to char* or LPTSTR?

Use CString::GetBuffer(). It can be used in a manner similar to this:
// prototype of a function that takes a LPTSTR parameter
// presented for argument's sake.
void test_func ( LPTSTR lpszString, int length );

CString string;
test_func ( string.GetBuffer ( 50 ), 50 );
string.ReleaseBuffer ( );
Forgetting to call CString::ReleaseBuffer() can cause problems very difficult to debug as it releases the lock on CString's inner buffer. One thing to keep in mind about CString::GetBuffer() is that it returns a TCHAR* value (or LPTSTR, it's the same), so it is subject to the same ANSI/MBCS Vs. UNICODE convertions as most other Win32 APIs. It also means that if you're compiling a unicode version of your application, and 
specifically need a char* from your CString instance, you'll have to use a separate buffer of the appropriate type, and then make the convertion to unicode using one of the vailable API's before asigning it's value to the CString instance. The same goes if you're doing the exact opposite: getting a WCHAR* out of a CString, while compiling in MBCS mode.
ii)  Use a temporary variable. For example: 

  char       temp[256];
  CString string;
  
  test_func ( temp, 256 );
  string = temp;

How to handle dynamic menus in MFC?

Dynamic menus can be handled using Cmenu's Createmenu,Insrtmenu and Appendmenu functions.

What is serialization ?which function is responsible for serializing data ?

Serialization is the process of writing or reading an object to or from a persistent storage medium, such as a disk file. Serializing an object requires 3 ingredients:
•    A CFile object representing the datafile
•    A CArchive object that provides the serialization context
•    The object being serialized
Serialization represents a relationship between objects derived from the CObject class, the CArchive class representing an archive, and the CFile class that represents physical storage.

What function is used to retrieve the currently selected index in a list box?

GetCurSel() will be used to retrieve the index number and GetText() is used to retrieve the text.
//Example
int index;
CString strText;
index = m_ctlListBox.GetCurSel();
m_ListBox.GetText(index,strText);

What is CArchive class dowes?

The MFC Library uses CArchive objects for serialization. A CArchive object represents persistent storage of some kind. When an object is about to be serialized, CArchive calls the object's Serialize member function, one of the overridable functions in CObject. Thus, the underlying philosophy is that it is the object that knows best how to prepare itself for persistent storage, while it is the CArchive object that knows how to transfer the resulting data stream to persistent media.The CArchive class allows you to save a complex network of objects in a permanent binary form (usually disk storage) that persists after those objects are deleted. Later you can load the objects from persistent storage, reconstituting them in memory. This process of making data persistent is called “serialization.”

What is the use of OninitDialog ?

All your initialization for your dialog can be inside "OnInitDialog". Basically to set default / preset values to your dialog controls.

What is the use of Mutex and critical section?

An object of class CMutex represents a “mutex” — a synchronization object that allows one thread mutually exclusive access to a resource. Mutexes are useful when only one thread at a time can be allowed to modify data or some other controlled resource. For example, adding nodes to a linked list is a process that should only be allowed by one thread at a time. By using a CMutex object to control the linked list, only one thread at a time can gain access to the list.

To use a CMutex object, construct the CMutex object when it is needed. Specify the name of the mutex you wish to wait on, and that your application should initially own it. You can then access the mutex when the constructor returns. Call CSyncObject::Unlock when you are done accessing the controlled resource.

What is model and modeless dialog box ? Give some examples?

When we create Modal Dialog Box we can't move to other windows until this dialog is closed. For eg: MessageBox, where we can't move to the other window until we press ok or cancel. When we create Modeless Dilaog Box we can swap to the other windows. For eg: like a conventional window.

How to create open & save dialogs ?

In CommonDialogs class we have to use CFileDialog class where the first parameter TRUE for open dialog and FALSE for Save dialog.

For file open:
CFileDialog SampleDlg(TRUE,NULL,NULL,OFN_OVERWRITEPROMPT,"Text Files (*.txt)|*.txt|Comma Separated Values(*.csv)|*.csv||");

int iRet = SampleDlg.DoModal();

What is CSingleDocTemplate?

It’s a document template class used to create single document interface SDI applications. Only one document can be opened at a time. It identifies the document class used to manage the application's data, the frame window class that encloses views of that data, and the view class used to draw visual representations of the data. The document template also stores a resource ID that the framework uses to load menus, accelerators, and other resources that shape the application's user interface.

Explain about MDI and CMultiDocTemplate ?

MDI applications are designed using the doc-view architectures in which there could be many views associated with a single document object and an application can open multiple docuements at the same time for eg:WORD.
In MDI terms, your main window is called the Frame, this is probably the only window you would have in a SDI (Single Document Interface) program. In MDI there is an additional window, called the MDI Client Window which is a child of your Frame window. CMultiDocTemplate is the document template class used to create MDI applications..The document template also stores a resource ID that the framework uses to load menus, accelerators, and other resources that shape the application's user interface.

Tell me the different controls in MFC ?

CAnimateCtrl,CButton,CEdit,CListBox,CComboBox,CRic hEditCtrl,CStatic, CTreeCtrl,CToolTipCtrl,CIPAddressCtrl,CTabCtrl,CDa teTimeCtrl,CHeaderCtrl,CListCtrl,CMonthCalCtrl,COl eCtrl,CProgressCtrl,CScrollBar,CSliderCtrl,CStatus BarCtrl,CTollBarCtrl etc.,

What is the use of OnInitDialog ?

This message is sent to the dialog box during the Create, CreateIndirect, or DoModal calls, which occur immediately before the dialog box is displayed. This can be used to intialize the dialog controls or show/hide the controls etc.,

What is the functioning of UpdateData() funciton ?

This is to initialize data in a dialog box, or to retrieve and validate dialog data.
The framework automatically calls UpdateData with bSaveAndValidate set to FALSE when a modal dialog box is created in the default implementation of CDialog::OnInitDialog. The call occurs before the dialog box is visible. The default implementation of CDialog::OnOK calls this member function with bSaveAndValidate set to TRUE to retrieve the data, and if successful, will close the dialog box. If the Cancel button is clicked in the dialog box, the dialog box is closed without the data being retrieved.


How to handle RTTI in MFC ?

Run-Time Type Information is a mechanism that allows the type of an object to be determined during the program execution.

Three main elements to RTTI in MFC are
:

1.Dynamic_cast operator - Used for conversion of polymorphic types.
2.typeid - used for identifying the exact type of an object 
3. type_info class used to hold the type information returned by typeid.

What is serialization ?which function is responsible for serializing data ?

Searialization is the process of streaming the object data to or from a persistent storage medium. It's useful in Doc-View Architecture. CObject :: Serialize() function is used to do serialization.

Explain about different kinds of threads in MFC?

Two types of thread in MFc are UserInterface thread and worker thread. UserInterface threads maintain the message loops and used to handles user input,creates windows and process messges sent to those windows.Worker thread don't use message loops and mainly used to perform background operations such as printing etc.,Created using AfxBeginThread bypassing ThreadFunction to create worker thread and Runtime class object to create a user interface thread.

what is the use of Mutex and critical section ?

Mutex as the name suggest allows a mutullay exclusive access to a shared resource among the threads. Critical section is a piece of code that can be executed safely to be accessed by two or more threads. Criticalsection provides synchronization means for one process only, while mutexes allow data synchronization across processes. Means two or more threads can share the common resources among more than one application or process boundaries in mutex.

What is socket?

A "socket" is an endpoint of communication: an object through which your application communicates with other Windows Sockets applications across a network.The two MFC Windows Sockets programming models are supported by the following classes: CAsyncSocket and CSocket.

What is the difference between Synchronous sockets and asynchronous sockets?

Consider a server application that is listening on a specific port to get data from clients. In synchronous receiving, while the server is waiting to receive data from a client, if the stream is empty the main thread will block until the request for data is satisfied. Hence, the server cannot do anything else until it receives data from the client. If another client attempts to connect to the server at that time, the server cannot process that request because it is blocked on the first client. This behavior is not acceptable for a real-world application where we need to support multiple clients at the same time. 

In asynchronous communication, while the server is listening or receiving data from a client, it can still process connection requests from other clients as well as receive data from those clients. When a server is receiving asynchronously, a separate thread (at the OS level) listens on the socket and will invoke a callback function when a socket event occurs. This callback function in turn will respond and process that socket event.

Have you ever used win32 APIs ?

MFC is a wrapper around win32 API, It provides classes which uses the win32 API, Some of the API's we usually work with are : GetDlgItemInt,GetDlgItemText,GetWindowTextA,Messag eBoxA,CreateFile,CreateMutex,CreateEvent,WaitForSi ngleObject,CreateWindow,ShowWindow etc.,

What is the difference between ANSI Code and UNICODE ?

ANSI code represents 8bytes data where UNICODE represents 16bytes data for supporting universal languages. One major draw back to ASCII was you could only have 256 different characters. However, languages such as Japanese and Arabic have thousands of characters. Thus ASCII would not work in these situations. The result was Unicode which allowed for up to 65,536 different characters.

What is a message map, and what is the advantage of a message map over virtual function?

MessageMap is a logical table that maps the windows messages to the member functions of the class. We use message maps over virtual function because of lots of overhead. If every windows message had a virtual function associated with it , there would be several hundred bytes per window class of vtable. Message maps means we only pay for the messages we use.

Given two processes, how can they share memory?

Processes and thread are very similar but they differ in the way they share their resources. Processes are independent and have its own address space. If two independent processes want to communicate they do this by using the following techniques 1.Message Passing 2.Sockets 3. named pipes

How to Initialize contents of a dialog?

In MFC, the contents of a dialog are initialized if they are associated with their corresponding data members. This is done through "UpdateData(FALSE)" function. The control data is transferred to the data members through "UpdateData(TRUE)".

In WIN32, the dialog data in controls can be initialized during WM_INITDIALOG call. The control data can be updated to the dialog members using apppropriate "SendMessage" functions.

About GDI object?

GDI object (is a graphical device object) used to write on a device context for graphical output. GDI objects are: Pen, Brush, Font,Line, Rectangle etc. These objects are created using their corresponding win32 function. For eg, CreatePen, CreatePenIndirect are used to create a pen object. After these objects are created they would need to be selected to the device context before processing using "SelectObject" function. 
GDI objects are not associated with any device context during its creation. SelectObject function does that assocaition. Once an object is selected into the device context it would be available until the object is destroyed through DeleteObject or the program exits.

What is device context?

A data structure in Windows programming that is used to define the attributes of text and images that are output to the screen or printer. The device context (DC) is maintained by GDI. A DC, which is a handle to the structure, is obtained before output is written and released after the elements have been written.

Message to limit the size of window?

WM_SIZE message is received by the window procedure when a user resizes a window. In order to limite the size of a window, you could handle the WM_SIZE message appropriately. 

Core Java interview questions


Core Java Interview Questions

What do you understand by Synchronization?
Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}

What is transient variable?
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.

Name the containers which use Border Layout as their default layout?

Containers which uses Border Layout as their default are: window, Frame and Dialog classes.
What is Collection API?

The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.


Is Iterator a Class or Interface? What is its use?
Iterator is an interface which is used to step through the elements of a Collection.
What is a native method?A native method is a method that is implemented in a language other than Java.

What are order of precedence and associativity, and how are they used? Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left

What is the catch or declare rule for method declarations?


If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

What is the range of the char type?

The range of the char type is 0 to 2^16 - 1.
What is similarities/difference between an Abstract class and Interface?
Differences are as follows:
Interfaces provide a form of multiple inheritance. A class can extend only one other class.
Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.
Similarities:
Neither Abstract classes or Interface can be instantiated.
How to define an Abstract class?
A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.
Example of Abstract class:
abstract class testAbstractClass {
protected String myString;
public String getMyString() {
return myString;
}
public abstract string anyAbstractFunction();
}

How to define an Interface?

In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Emaple of Interface:

public interface sampleInterface {
public void functionOne();

public long CONSTANT_ONE = 1000;
}

Explain the user defined Exceptions?
User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
// The class simply has to exist to be an exception
}
Explain the new Features of JDBC 2.0 Core API?

The JDBC 2.0 API includes the complete JDBC API, which includes both core and Optional Package API, and provides inductrial-strength database computing capabilities.
New Features in JDBC 2.0 Core API:
Scrollable result sets- using new methods in the ResultSet interface allows programmatically move the to particular row or to a position relative to its current position
JDBC 2.0 Core API provides the Batch Updates functionality to the java applications.
Java applications can now use the ResultSet.updateXXX methods.
New data types - interfaces mapping the SQL3 data types
Custom mapping of user-defined types (UTDs)
Miscellaneous features, including performance hints, the use of character streams, full precision for java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestamp values.
Explain garbage collection?
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.
How you can force the garbage collection?Garbage collection automatic process and can't be forced.
What is OOPS?
OOP is the common abbreviation for Object-Oriented Programming.
Describe the principles of OOPS.

There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.
Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.
Explain the Inheritance principle.
Inheritance is the process by which one object acquires the properties of another object.
Explain the Polymorphism principle.The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".
Explain the different forms of Polymorphism.
From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:
Method overloading
Method overriding through inheritance
Method overriding through the Java interface

What are Access Specifiers available in Java?
Access specifiers are keywords that determines the type of access to the member of a class. These are:
Public
Protected
Private
Defaults
Describe the wrapper classes in Java.
Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.
Following table lists the primitive types and the corresponding wrapper classes:
Primitive
Wrapper
boolean
java.lang.Boolean
byte
java.lang.Byte
char
java.lang.Character
double
java.lang.Double
float
java.lang.Float
int
java.lang.Integer
long
java.lang.Long
short
java.lang.Short
void
java.lang.Void

Read the following program:
public class test {
public static void main(String [] args) {
int x = 3;
int y = 1;
if (x = y)
System.out.println("Not equal");
else
System.out.println("Equal");
}
}
What is the result?
A. The output is “Equal”
B. The output in “Not Equal”
C. An error at " if (x = y)" causes compilation to fall.
D. The program executes but no output is show on console.
Answer: Cwhat is the class variables ?
When we create a number of objects of the same class, then each object will share a common copy of variables. That means that there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class, but mind it that it should be declared outside outside a class. These variables are stored in static memory. Class variables are mostly used for constants, variable that never change its initial value. Static variables are always called by the class name. This variable is created when the program starts i.e. it is created before the instance is created of class by using new operator and gets destroyed when the programs stops. The scope of the class variable is same a instance variable. The class variable can be defined anywhere at class level with the keyword static. It initial value is same as instance variable. When the class variable is defined as int then it's initial value is by default zero, when declared boolean its default value is false and null for object references. Class variables are associated with the class, rather than with any object.

What is the difference between the instanceof and getclass, these two are same or not ?

Instanceof is a operator, not a function while getClass is a method of java.lang.Object class. Consider a condition where we use
if(o.getClass().getName().equals("java.lang.Math")){ }This method only checks if the classname we have passed is equal to java.lang.Math. The class java.lang.Math is loaded by the bootstrap ClassLoader. This class is an abstract class.This class loader is responsible for loading classes. Every Class object contains a reference to the ClassLoader that defines. getClass() method returns the runtime class of an object. It fetches the java instance of the given fully qualified type name. The code we have written is not necessary, because we should not compare getClass.getName(). The reason behind it is that if the two different class loaders load the same class but for the JVM, it will consider both classes as different classes so, we can't compare their names. It can only gives the implementing class but can't compare a interface, but instanceof operator can.
The instanceof operator compares an object to a specified type. We can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. We should try to use instanceof operator in place of getClass() method. Remember instanceof opeator and getClass are not same. Try this example, it will help you to better understand the difference between the two.
Interface one{
}

Class Two implements one {
}
Class Three implements one {
}

public class Test {
public static void main(String args[]) {
one test1 = new Two();
one test2 = new Three();
System.out.println(test1 instanceof one); //true
System.out.println(test2 instanceof one); //true
System.out.println(Test.getClass().equals(test2.getClass())); //false
}
}

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

Yes

Can an Interface be final?

No

Can an Interface have an inner class?

Yes.
public interface abc
{
static int i=0; void dd();
class a1
{
a1()
{
int j;
System.out.println("inside");
};
public static void main(String a1[])
{
System.out.println("in interfia");
}
}
}

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

No

What is Externalizable? Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in).

What modifiers are allowed for methods in an Interface?

Only public and abstract modifiers are allowed for methods in interfaces.
What is a local, member and a class variable?Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables). Variables declared within the class i.e not within any methods and are defined as “static” are class variables

What are the different identifier states of a Thread
?

The different identifiers of a Thread are: R - Running or runnable thread, S - Suspended thread, CW - Thread waiting on a condition variable, MW - Thread waiting on a monitor lock, MS - Thread suspended waiting on a monitor lock

What are some alternatives to inheritance
?Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

Why isn’t there operator overloading?Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().

What does it mean that a method or field is “static”? Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the java.lang.System class.

How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?


String hostname = InetAddress.getByName("192.18.97.39").getHostName();

Difference between JRE/JVM/JDK?

Why do threads block on I/O?

Threads block on i/o (that is enters the waiting state) so that other threads may execute while the I/O operation is performed.

What is synchronization and why is it important?With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.
Is null a keyword? The null value is not a keyword.
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.
Which characters may be used as the second character of an identifier, but not as the first character of an identifier?The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.
What modifiers may be used with an inner class that is a member of an outer class? A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
What are wrapped classes? Wrapped classes are classes that allow primitive types to be accessed as objects.
What restrictions are placed on the location of a package statement within a source code file?A package statement must appear as the first line in a source code file (excluding blank lines and comments).

What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.