Tampilkan postingan dengan label interview. Tampilkan semua postingan
Tampilkan postingan dengan label interview. Tampilkan semua postingan

HTML and CSS Interview Questions and Answers

Jumat, 07 Maret 2014

Q. Can you have a DIV element nested inside a SPAN element?
A. It is a bad practice to have a DIV element nested inside a SPAN element. You can have a SPAN inside a DIV. The reason being the DIV is a block element and SPAN is an inline element. So, why would you want to have a block element inside an inline element? SPAN is a like sub tag, which applies styles for the specified content in-between the SPAN tag.

Q. How will you decide between using nested HTML table tags and a DIV tag with CSS?
A. Use DIV tags with CSS for laying out the web pages and use TABLE for representing data.

Tabular data represented using html table tag.




To layout web page elements

The traditional way of laying out web pages was to place them inside invisible tables as demonstrated below. This way of laying out is more complicated to do, harder to maintain and makes the web pages to load very slowly.



Bad: Laying out with nested TABLE tags and CSS

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Table Layout</title>

<style type="text/css">
table {
width: 100%;
height: 1000px;
}

td.header {
width: 100%;
text-align: center;
background-color: yellow;
}

td.contents {
width: 80%;
text-align: center;
background-color: orange;
}

td.rhsmenu {
width: 20%;
text-align: center;
background-color: green;
}

td.footer {
width: 100%;
text-align: center;
background-color: blue;
}
</style>


</head>
<body>
<table>
<tbody>
<tr height="15%">
<td class="header" colspan="2">Header Information</td>
</tr>
<tr height="65%">
<td class="contents">Contents go
here</td>
<td class="rhsmenu">RHS Panel</td>
</tr>
<tr height="20%">
<td class="footer" colspan="2">Footer Information</td>
</tr>
</tbody>
</table>

</body>
</html>

 The newer way to lay out your page elements is using DIVs and CSS. It can do everything tables can do and much more, and as an added bonus it loads a lot faster than tables ever did. It is easier to maintain, if you dont go overboard with nested DIVs. Use DIV for the conatainer and then use other elements SPAN, P, etc with CSS.

 Good: Laying out with DIVs and CSS tag


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Div Layout</title>

<!-- This can be defined outside in its own file and included into an html file -->
<style type="text/css">
body {
display: block;
width: 400px;
height:400px;
text-align: center;
}

/* main content container floated to the left*/
#content {
position: relative;
width: 80%;
height: 65%;
float: left;
background-color: orange;
width: 320px;
}

/* rhs menu container floated to the left*/
#rhs-menu {
position: relative;
width: 20%;
height: 65%;
float: left;
background-color: green;
}

/* header container floated to the left*/
#header {
position: relative;
width: 100%;
height: 15%;
float: left;
background-color: yellow;
}

/* footer with "clear"" to ensure that the footer is always below content and rhs-menu */
#footer {
position: relative;
width: 100%;
height: 20%;
clear: both;
background-color: blue;
}

/* align text vertically*/
#content p,#rhs-menu p,#header p,#footer p {
position: absolute;
top: 50%;
left: 50%;
height: 50%;
width: 50%;
margin: -15% 0 0 -25%;
}

/* position the logo using absolute (from top left corner) or relative*/
.logo-text {
position: absolute;
top: 5px;
left: 10px;
}

</style>

</head>
<body>

<div id="header"><span class="logo-text">logo goes here </span>
<p>Header Information</p>
</div>
<div id="content">
<p>Contents go here</p>
</div>
<div id="rhs-menu">
<p>RHS Panel</p>
</div>
<div id="footer">
<p>Footer Information</p>
</div>

</body>
</html>

Note: It is a best practice to define HTML, CSS, and JavaScript in separate files. The CSS is combined with HTML in these examples for illustration purpose only.

The typical usecase for the "clear" css tag is when you want to put a footer at the bottom of your page, beneath the RHS menu and the content sections. So, by using the CSS tags like float, clear, absolute, relative, and display you can create attractive, maintainable, and faster layouts.
Read More..

The pre Java Interview online written test questions that I hate

Minggu, 23 Februari 2014

Some online assessment sites basically try to test your memorizing capabilities with API based questions listed below. Also, about 30% - 50% of the questions are on API that you rarely use or obsolete. When you have the API documentation, why remember the API. Here are a few such questions I came across recently. If you want to ask such questions, then allow people to refer to the online API documentation. These tests are only going to filter out quality candidates.


Q. Which of the following are valid JavaMail message types?

a) Message.RecipientType.CC
b) MessageRecipientType.CC
c) Message.RecipientType.CCList
d) Message.RecipientType.BCC
e) MessageRecipientType.BCC

A. a and d


Q. Which of the following are JNDI event listeners?

a) NamespaceChangeListener
b) ObjectListener
c) ObjectChangeListener
d) UnsolicitedNotificationListener
e) ObjectNotFoundListenr

A. a, c, and d.


Q. Which of the following statements are correct, based on the following code snippet for uploading a file?

<form action="upload"  enctype="multipart/form-data">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>


a) The enctype must be "text/form-data"
b) The method attribute is missing in the "form" element and it should be of type "GET"
c) The method attribute is missing in the "form" element and it should be of type "POST"
d) The "input" element must have the attribute "value"
e) The above syntax is correct

A. c. 

The correct format is:

<form action="upload"  method="post" enctype="multipart/form-data">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>


Q. Which of the following objects are NOT part of the JavaBean Activation Framework (JAF)?

a) DataSource
b) DataFileHandler
c) DataHandler
d) DataContentHandler
e) FileDateHandler
f) FileTypeMap

A. b and e. All the others are part of JAF.


Q. Which of the following statements are INCORRECT?

a) HttpServletRequest.getRemoteUser( ) return null;
b) HttpServletRequest.isUserInRole(java.lang.String role) throws SecurityException ;
c) HttpServletRequest.getRemoteUser( ) return false;
d) HttpServletRequest.isUserInRole(java.lang.String role) return false;
e) HttpServletRequest.getUserPrincipal( ) throws SecurityException
f) HttpServletRequest.getUserPrincipal( ) return null;


A. b, c, and e are INCORRECT.

Q. Which of the following elements would you see in a SOAP payload with attachments?

a) <soap:header>
b) <soap:footer>
c) <soap:body>
d) <soap:content>
e) <soap:attachment>

A. a and c.


Q. Which of the following can be used in place of "****" in the code snippet shown below?


if(request.getParameter("location").equals("nextPage") {

      *****

}


a) request.sendRedirect("url");
b) response.sendRedirect("url");
c) request.redirect("url");
d) response.redirect("url");
e) response.send("url")


A.b

Q. Which of the following are valid JDBC  result set types?


a) TYPE_FORWARD_ONLY
b) TYPE_BACKWARD_ONLY
c) TYPE_SCROLL_INSENSITIVE
d) TYPE_SCROLL_SENSITIVE
e) TYPE_SCROLL_REVERSE

A. a, c, and d.


Q. Which of the following are valid JSP life cycle methods?

a) jspService( )
b)_jspService( )
c) jspInit( )
d) jspDestroy( )
e) _jspInit()

A. a, c, and d.


Q. Which of the following are CORRECT about JCA?

a)  JCA is a standard architecture for integrating heterogeneous EIS systems not written in Java
b)  JCA is a standard architecture for integrating other JEE systems
c)  JCA can be used to integrate with mainframe systems
d)  JCA can be used to integrate with ERP systems
e)  JCA can be used to integrate with Database systems
f)  The underlying EIS systems are integrated using pluggable resource adapters

A. a, c, d, e and f.

Q. Which of the following are INCORRECT about JAAS?

a) JAAS bring in location based authentication and authorization to JEE.
b) JAAS is designed to bring subject based authentication and authorization to JEE
c) JAAS is modeled after the Pluggable Authentication Module (PAM)-a popular API for defining authentication modules in a portable and extensible manner
d) JAAS can be used across managed resources such as servlet/JSP, EJB, or MBeans and over a variety of connection protocols such as HTTP, RMI/IIOP, or JMX/RMI.
e) JAAS was fully integrated into the core Java security architecture

A. a.

The last 2 questions are not bad, but for most of the other questions, the answers can be found by jumping on a search engine for 5 to 15 minutes. It is not really testing your understanding of the core concepts or hands-on experience.

Is it just me, or do you agree with me? Please post the Java Interview Questions that you hate.

Read More..

SQL Interview Questions and Answers on deleting records

Senin, 10 Februari 2014



The following is a very popular SQL job interview question.

Q. What is the difference between "Truncate" and "Delete" commands?
A. 
  • TRUNCATE TABLE_NAME always locks the table and page but not each row, whereas  DELETE statement is executed using a row lock, each row in the table is locked for deletion.
  • Truncate removes all the records in the table whereas delete can be used with WHERE clause to remove records conditionally. That is remove only a handful number of records.
  • Truncate performance is much faster than Delete, as its logging is minimal wheres the Delete command logs every record.
  • Truncate does not retain the identity, whereas DELETE command retains the identity. When you use Truncate, If the table contains an identity column, the counter for that column is reset to the seed value that is defined for the column.
  • Truncate cleans up the object statistics and clears the allocated space whereas Delete retains the object statistics and allocated space.
  • TRUNCATE is a DDL (Data Definition Language) and DELETE is a DML (Data Manipulation Language). 
  • Data removed by TRUNCATE command cannot be generally rolled back unless the database server specifically supports it. The DELETE command can rollback a transaction.
  • The TRUNCATE command does not fire any triggers, whereas the DELETE command fires any triggers defined on the table. For example, to keep an audit trail of records that have been deleted by inserting the deleted records into an audit table via the DELETE triggers.

Q. When will you use a truncate command?
A.TRUNCATE is useful for purging a table with huge amount of data. Alternatively, you can drop the table and recreate it that makes sense. Firing a delete command instead of a truncate command to empty a table with millions of records can result in locking the whole table and also can take longer time to complete, and at times cause the machine to hang.

The truncate command is executed as shown below.

TRUNCATE TABLE table_name



Q. Which command will you use to periodically purge data from your tables as part of a house keeping job?
A.  Use a DELETE command within a transaction with a WHERE clause to remove data that are older than 7 years. Remove  large amount of data in batches as opposed to in a single transaction.

Q. How will you delete a few records from single table
A.

DELETE FROM parent p WHERE p.parent_name = Peter


Q
. How will you delete a few records from parent and child tables where the parent table with parent_name = Peter?
A.

Firstly, you need to delete the child records because the integrity constraint wont let you delete the parent record when there are child records.

DELETE child

FROM  parent p, child c

WHERE p.parent_id = c.parent_id

  AND p.parent_name = Peter


Now, the parent table can be deleted as shown below

DELETE FROM  parent p WHERE p.parent_name = Peter


Note: Please note the difference in syntax when you make a join with the child. When there is only a single table involved, it is "DELETE FROM table_name", but when there is a join, it is "DELETE table_name" and then the "FROM" with the join clauses.


Q.  What do you do with the PURGE command?
A. The purge command is used to clear the recycle bin. It is generally used with the DROP command. For example,

drop table tablename purge;


the above  command will clear away the table from database as well as from the recycle bin. After executing  the purge command, you cannot retrieve the table using a flashback query. 



    You may also like:
    Read More..

    Java new I O Interview Questions and Answers

    Jumat, 07 Februari 2014



    The Java New IO is very powerful and it is all about performance!, performance!!, and performance!!!. But, you need to get your head around how the buffers work. Here are some questions and answers that will help you do that. Q. How does the Java NIO (i.e New IO) introduced in Java version 1.4 differ from the old IO?
    A. The NIO is all about better performance.

    IONIO (New IO)
    Stream oriented. This means that you read one or more bytes at a time, from a stream. What you do with the read bytes is up to you. They are not cached anywhere. Furthermore, you cannot move forward and back in the data in a stream. If you need to move forward and back in the data read from a stream, you will need to buffer yourself first.

    Buffer oriented. This means better performance. Data is read into a buffer from which it be processed later. You can move forward and back in the buffer. This gives you a bit more flexibility during processing. However, you also need to check if the buffer contains all the data you need in order to fully process it.
    Blocking IO. This means when a thread invokes a read() or write(), that thread is blocked until there is some data to read, or the data is fully written. The thread can do nothing else in the meantime.

    Non blocking IO. This means better performance. NIOs non-blocking mode enables a thread to request reading data from a channel, and only get what is currently available, or do nothing at all, if no data is currently available. Rather than remain blocked until data becomes available for reading, the thread can proceed with doing something else.
    You need to create additional threads to read and write data in parallel. More threads means more CPU context switching and consuming more thread stacks.Selectors.  This also means better performance. NIOs selectors allow a single thread to monitor multiple channels of input. You can register multiple channels with a selector, then use a single thread to "select" the channels that have input available for processing, or select the channels that are ready for writing. This selector mechanism makes it easy for a single thread to manage multiple channels. This is also known as multiplexing. The Apache MINA package is based on Java NIO to write high performance networking applications. For example, a TCP server.

    Here is the diagrammatic overview:



    Q. How do you manipulate the buffer in NIO?
    A. The NIO buffer  has following 3 state variables -- position, limit, and capacity

    • position: The position value keeps track of how much you have gotten from the buffer. It specifies from which array element the next byte will come. Thus, if youve written 1 bytes as shown below with shaded area to a channel from a buffer, that buffers position will be set to 1 (starting from 0), referring to the second element of the array as shown in the diagram.
    • limit: The limit variable specifies how much room there is left to put data into -- in the case of reading from a channel into a buffer or how much data there is left to get -- in the case of writing from a buffer into a channel. The position is always less than, or equal to, the limit. The limit is 3 (counting from 0) in the diagram below.
    • capacity:  The capacity of a buffer specifies the maximum amount of data that can be stored in the underlying array. The limit can never be larger than the capacity. The capacity is 6 (counting from 0) in the diagram below.

    In the above diagram, the position starts with 0, and after reading 1 byte, it becomes 1 byte, and the limit value of 3 states that there are 2 more bytes to be read. 



    Q. What do you understand by terms flip( ) and clear( ) in NIO?
    A.

    Flip

    When you are ready to write your data to an output channel. You must call the flip() method. This method does two key things:

    1. It sets the limit to the current position.
    2. It sets the position to 0.

    You are now ready to begin writing data to a channel from the buffer starting from 0 to the limit.


    Clear

    After you have done your writes, the final step is to call the buffers clear() method. This method resets the buffer in preparation for receiving more bytes. Clear does two key things:

    1. It sets the limit to match the capacity.
    2. It sets the position to 0.


    Also, the get and put methods are used to get and put data to and from the buffer respectively. some coding examples are discussed in Java I/O interview Questions and Answers.


    Q. What is in the NIO.2 package introduced in Java 7?
    A. The more New I/O APIs for the Java Platform (NIO.2) in Java 7 enhance the New I/O APIs (NIO) introduced in Java 1.4 by adding

    • The four asynchronous channels to the java.nio.channels package. 
    •  The java.io.File class is upgraded to the java.nio.file.Path that allows logical manipulating of paths in memory without accessing the file system.
    • The NIO.2 associates the notion of metadata like is hidden, is it a directory, size, access control, etc with attributes and provides access to them through the java.nio.file.attribute package. Since different file systems have different notions about which attributes should be tracked, NIO.2 groups the attributes into views, each of which maps to a particular file system implementation.
    • The NIO.2 provides support for both hard links and symbolic links and the Path class knows how to detect a link and will behave in the default manner if no configuration of behavior is specified.
    • The NIO.2 comes with a set of brand new methods for managing files and directories, such as create, read, write, move, delete, and so on. The most of these tasks are found in the java.nio.file.Files class.
    • The FileVisitor interface introduced in Java 7 makes recursing through directories and files a breeze.
    • The Watch Service API was introduced in Java 7 (NIO.2) as a thread-safe service that is capable of watching  a directory for changes to its content through actions such as create, delete, and modify. This means, with NIO.2, you no longer need to poll the file system for changes or use other in-house solutions to monitor the file system changes.
    • Java 7 (NIO.2) introduces a new interface for working with Random Access Files with its SeekableByteChannel and an interface named NetworkChannel that provides network channel classes for tetworking.
    Read More..

    C Interview Question

    1. What is C++
      C++ is created by Bjarne Stroustrup of AT&T Bell Labs as an extension of C, C++ is an object-oriented computer language used in the development of enterprise and commercial applications. Microsoft’s Visual C++ became the premier language of choice among developers and programmers.

    2. What are the basic concepts of object oriented programming?
      It is necessary to understand some of the concepts used extensively in object oriented programming.These include

    • Objects
    • Classes
    • Data abstraction and encapsulation
    • Inheritance
    • Polymorphism
    • Dynamic Binding
    • Message passing

    3. Define inheritance?
      The mechanism of deriving a new class (derived) from an old class (base class) is called inheritance. It allows the extension and reuse of existing code without having to rewrite the code from scratch. Inheritance is the process by which objects of one class acquire properties of objects of another class.

    4. Define polymorphism?
      Polymorphism means one name, multiple forms. It allows us to have more than one function with the same name in a program.It allows us to have overloading of operators so that an operation can exhibit different behaviors in different instances.

    5. What is encapsulation?
      The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Encapsulation containing and hiding information about an object, such as internal data structures and code.


    6. What is message passing?
      An object oriented program consists of a set of objects that communicate with each other. Message passing involves specifying the name of the object, the name of the function and the information to be sent.

    7. What are tokens in C++?
      The smallest individual units of a program is known as tokens. c++ has the following tokens :

    • Keywords
    • Identifiers
    • Constants
    • Strings
    • Operators

    8. What is the use of enumerated data type?
      An enumerated data type is another user defined type which provides a way for attaching names to numbers thereby increasing comprehensibility of the code. The enum keyword automatically enumerates a list of words by assigning them values 0,1,2, and so on.

    9. What is the use of default constructor?
      A constructors that accepts no parameters is called the default constructor.If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A(). This constructor is an inline public member of its class. The compiler will implicitly define A::A() when the compiler uses this constructor to create an object of type A. The constructor will have no constructor initializer and a null body.

    10. Define Constructors?
      A constructor is a member function with the same name as its class. The constructor is invoked whenever an object of its associated class is created.It is called constructor because it constructs the values of data members of the class.


    11. How variable declaration in c++ differs that in c?
      C requires all the variables to be declared at the beginning of a scope but in c++ we can declare variables anywhere in the scope. This makes the programmer easier to understand because the variables are declared in the context of their use.

    12. Define destuctors?
      A destructor is called for a class object when that object passes out of scope or is explicitly deleted.A destructors as the name implies is used to destroy the objects that have been created by a constructors.Like a constructor , the destructor is a member function whose name is the same as the class name but is precided by a tilde.

    13. What is a class?
      A class is a collection of objects.

    14. What is the difference between c &c++?
      c++ ia an object oriented programing but c is a procedure oriented programing.c is super set of c++. c cant suport inheritance,function overloading, method overloading etc. but c++ can do this.In c-programe the main function could not return a value but in the c++ the main function shuld return a value.

    15. What is copy constructor?
      Copy constructor is a constructor function with the same name as the class and used to make deep copy of objects.


    16. What is default constructor?
      A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.

    17. What is a scope resolution operator?
      The scope resolution operator 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.

    18. What is the difference between Object and Instance?
      An instance of a user-defined type is called an object. We can instantiate many objects from one class. An object is an instance of a class.

    19. What is the difference between macro and inline?
      Inline follows strict parameter type checking, macros do not.
            Macros are always expanded by pre-processor, whereas compiler may or may not replace the inline definitions.

    20. How variable declaration in c++ differs that in c?
      C requires all the variables to be declared at the beginning of a scope but in c++ we can declare variables anywhere in the scope. This makes the programmer easier to understand because the variables are declared in the context of their use.


    21. What is multiple inheritance?
      A class can inherit properties from more than one class which is known as multiple inheritance.

    22. what is the use of virtual destructor in c++?
      A destructor is automatically called when the object is destroyed. A virtual destructor in C++ is used primarily to prevent resource leaks by performing a clean-up of the object.

    23. What do you mean by reference variable in c++?
      A reference variable provides an alias to a previously defined variable.
            Data -type & reference-name = variable name

    24. What do you mean by implicit conversion?

    • Whenever data types are mixed in an expression then c++ performs the conversion automatically.
    • Here smaller type is converted to wider type.
    • Example : in case of integer and float integer is converted into float type.


    25. What are virtual functions?

    • The virtual functions must be members of some class.
    • They cannot be static members.
    • They are accessed by using object pointers.
    •  A virtual function can be a friend of another class. 
    26. What is the difference between class and structure?
    • By default, the members ot structures are public while that tor class is private.
    • structures doesn’t provide something like data hiding which is provided by the classes.
    • structures contains only data while class bind both data and member functions.
    27. What are storage qualifiers in C++ ?
      Const-Keyword indicates that memory once initialized, should not be altered by a program.
    Volatile keyword indicates that the value in the memory location can be altered even though nothing in the program.
             Mutable keyword indicates that particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.

    28. What is virtual class and friend class?
      Friend classes are used when two or more classes and virtual base class aids in multiple inheritance.
    Virtual class is used for run time polymorphism when object is linked to procedure call at run time.

    29. what is an abstract base class?
      An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function.

    30. What is dynamic binding?
      Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run time.It is associated with polymorphism and inheritance.

    31. What is difference between function overloading and operator overloading?
             A function is overloaded when same name is given to different function.
             While overloading a function, the return type of the functions need to be the same. 

    32. What are the advantages of inheritance?
    • Code re-usability
    • Saves time in program development.
    33. What is a dynamic constructor?
      The constructor can also be used to allocate memory while creating objects. Allocation of memory to objects at the time of their construction is known as dynamic construction of objects.The memory is allocated with the help of the new operator.

    34. What is the difference between an Array and a List?
      The main difference between an array and a list is how they internally store the data. whereas Array is collection of homogeneous elements. List is collection of heterogeneous elements.

    35. What is the use of ‘using’ declaration?
      A using declaration makes it possible to use a name from a namespace.

    36. What is the difference between a template class and class template?
    • Template class- A generic definition or a parameterized class not instantiated until the client provides the needed information. It’s jargon for plain templates.
    • Class template- A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It’s jargon for plain classes.
    37. What is friend function?
      The function declaration should be preceded by the keyword friend.The function definitions does not use either the keyword or the scope operator ::. The functions that are declared with the keyword friend as friend function.Thus, a friend function is an ordinary function or a member of another class.

    38. What is a scope resolution operator?
      A scope resolution operator (::), can be used to define the member functions of a class outside the class.

    39. What do you mean by pure virtual functions?
      A pure virtual member function is a member function that the base class forces derived classes to provide. Any class containing any pure virtual function cannot be used to create object of its own type.

    40. What is a conversion constructor?
      A converting constructor is a single-parameter constructor that is declared without the function specifier explicit. The compiler uses converting constructors to convert objects from the type of the first parameter to the type of the converting constructor’s class.

    41. What is a container class? What are the types of container classes?
      A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a wellknown interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.

    42. What is Associative container?
      Associative containers are designed to support direct access to elements using keys. They are not sequential. There are four types of associative containers :
    • Set
    • Multiset
    • Map
    • Multimap
    43. What is an iterator?
      Iterators are like pointers. They are used to access the elements of containers thus providing a link between algorithms and containers. Iterators are defined for specific containers and used as arguments to algorithms.

    44. What are the defining traits of an object-oriented language?
      The defining traits of an object-oriented language are: (POI) 
    • Encapsulation
    • Inheritance
    • Polymorphism
    45. Name some pure object oriented languages?
    •  Smalltalk
    • Java
    • Eiffel
    • Sather 
    46. What is this pointer?
      It is a pointer that points to the current object. This can be used to access the members of the current object with the help of the arrow operator.

    47. What is encapsulation?
      Encapsulation (or information hiding) is the process of combining data and functions into a single unit called class.

    48. What is problem with Runtime type identification?
      The run time type identification comes at a cost of performance penalty. Compiler maintains the class.

    49. What are the differences between new and malloc?
      New initializes the allocated memory by calling the constructor. Memory allocated with new should be released with delete.
    • Malloc allocates uninitialized memory. 
    • The allocated memory has to be released with free.new automatically calls the constructor while malloc(dosen’t)
    50. What is conversion operator?
      You can define a member function of a class, called a conversion function, that converts from the type of its class to another specified type.

    51. What is difference between template and macro?
      A template can be used to create a family of classes or function.A template describes a set of related classes or set of related functions in which a list of parameters in the declaration describe how the members of the set vary.
            Identifiers that represent statements or expressions are called macros.

    52. What is reference?
      Reference is a name that acts as an alias, or alternative name, for a previously defined variable or an object.

    53. What are the access specifier in c++?
      There are three types of access specifier in c++ . They are 
    • Public
    • Protected
    • Private
    54. What is difference between C++ and Java?
    •  C++ has pointers Java does not.
    • Java is the platform independent as it works on any type of operating systems.
    • java has no pointers where c ++ has pointers.
    • Java has garbage collection C++ does not.
    55. What is namespace?
      The C++ language provides a single global namespace.Namespaces allow to group entities like classes, objects and functions under a name.

    56. What is an explicit constructor?
      A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. It’s purpose is reserved explicitly for construction.Explicit constructors are simply constructors that cannot take part in an implicit conversion.

    57. What is the use of storage class specifiers?
      A storage class specifier is used to refine the declaration of a variable, a function, and parameters. The following are storage class specifiers :
    • auto
    • register
    • static
    • extern
    58. What is assignment operator in c++?
      Default assignment operator handles assigning one object to another of the same class. Member to member copy (shallow copy).

    59. Can destructor be private?
      Yes destructors can be private. But according it is not advisable to have destructors to be private.

    60. What is strstream?
      stringstream provides an interface to manipulate strings as if they were input/output streams.
    ‹strstream› to define several classes that support iostreams operations on sequences stored in an allocated array of char object.

    61. What are the types of STL containers?
    •  deque
    • hash map
    • hashmultimap
    • hash_multiset
    • hashset
    • list
    • map
    • multimap
    • multiset
    • set
    • vector
    62. What is the difference between method overloading and method overriding?
      Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters).
    Method overriding is the ability of the inherited class rewriting the virtual method of the base class.

    63. What do you mean by inline function?
      An inline function is a function that is expanded inline when invoked.ie. the compiler replaces the function call with the corresponding function code. An inline function is a function that is expanded in line when it is invoked. That is the compiler replaces the function call with the corresponding function code (similar to macro).

    64. What is a template?
      A template can be used to create a family of classes or function.A template describes a set of related classes or set of related functions in which a list of parameters in the declaration describe how the members of the set vary.

    65. What is a copy constructor and when is it called?
      A copy constructor is a method that accepts an object of the same class and copies it members to the object on the left part of assignment.

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

    67. What is a virtual destructor?
      The simple answer is that a virtual destructor is one that is declared with the virtual attribute.

    68. What do you mean by Stack unwinding?
      It is a process during exception handling when the destructor is called for all local objects between the place where the exception was thrown and where it is caught.

    69. What is STL? and what are the components of stl?
      A collection of generic classes and functions is called as Standard Template Library (STL).The stl components are 
    • Containers
    • Algorithm
    • Iterators
    70. What is a modifier?
      A modifier, also called a modifying function is a member function that changes the value of at least one data member. In other words, an operation that modifies the state of an object. Modifiers are also known as mutators.

    71. What is an adaptor class or Wrapper class?
      A class that has no functionality of its own. Its member functions hide the use of a third party software component or an object with the non-compatible interface or a non-objectoriented implementation.

    72. What is a Null object?
      It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object.

    73. What is class invariant?
      A class invariant is a condition that defines all valid states for an object. It is a logical condition to ensure the correct working of a class. Class invariants must hold when an object is created, and they must be preserved under all operations of the class. In particular all class invariants are both preconditions and post-conditions for all operations or member functions of the class.

    74. What is the difference between the message and method?
      Message : Objects communicate by sending messages to each other.A message is sent to invoke a method.
            Method : Provides response to a message and it is an implementation of an operation.

    75. How can we access protected and private members of a class?
      In the case of members protected and private, these could not be accessed from outside the same class at which they are declared. This rule can be transgressed with the use of the friend keyword in a class, so we can allow an external function to gain access to the protected and private members of a class.

    76. What do you mean by late binding?
      Late binding refers to function calls that are not resolved until run time. Virtual functions are used to achieve late binding. When access is via a base pointer or reference, the virtual function actually called is determined by the type of object pointed to by the pointer.

    77. What is virtual function?
      A virtual function is a member function that is declared within a base class and redefined by a derived class .To create a virtual function, the function declaration in the base class is preceded by the keyword virtual.

    78. What do you mean by early binding?
      Early binding refers to the events that occur at compile time. Early binding occurs when all information needed to call a function is known at compile time. Examples of early binding include normal function calls, overloaded function calls, and overloaded operators. The advantage of early binding is efficiency.





    Read More..

    Top 20 Java technical interview questions and answers for experienced Java developers

    Rabu, 05 Februari 2014

    If you are an interviewer -- it really pays to ask well rounded questions to judge the real experience of the candidate as opposed to just relying on the number of years.

    If you are an interviewee -- You have no control over what questions will be asked in Java job interviews, but there are a few Java interview questions that are very frequently asked in job interviews, and it really pays to prepare for those questions. Here are a few such questions. This is based on some of my recent interviews. Brushing up on these answers will boost your success rate in Java job interviews.

    The focus is on judging your experience. So, go through your resume and reflect back on your hands-on experience. Many of these answers will also serve you well in selling your technical strengths to open ended questions like -- tell me about yourself? , why do you like software development?, when reviewing others work, what do you look for?, what was your most significant accomplishment?, etc

    Q1. Can you describe the high level architecture of the application that you had worked on recently? or Can you give a 100 feet birds eye view of the application you were involved in as a developer or designer?

    A1. The purpose is to judge your overall experience. Here are a few links that will prepare for this most sought-after question, especially for the experienced professionals.



    Q2. How would you go about deciding between SOAP based web service and RESTful web service?
    A2. Web services are very popular and widely used to integrate disparate systems. It is imperative to understand the differences, pros, and cons between each approach. Recently, I have been asked these questions very frequently, here is the answer that discusses the pros and cons of SOAP vs. RESTful web services in detail.  

    Q3.How will you go about ensuring that you build a more robust application? or How do you improve quality of your application?
    A3. This question is very popular with the interviewers because they want to hire candidates who write good quality application. Here are some useful links to prepare for this question.


    Q4. What are some of the best practices regarding SDLC? Have you worked in an agile development environment? Did you use test driven development and continuous integration?
    A4. 
    Q5: Can you write code? How would you go about implementing .....?
    A5:  You will be asked to write a small function or a program. The interviewer will be looking for things like
    • How well you analyze the requirements and the solution? Ask relevant questions if the requirements are not clear. Think out loud so that the interviewer knows that how you are approaching the problem.The approach is more important that arriving at the correct solution.
    • List all possible alternatives.
    • Write pseudo code.
    • Write unit tests.
    • Where required, brainstorm with the interviewer.
    • Find ways to improve your initial solution. Talk through thread safety and best practices where applicable.
    Here are some links to popular coding questions and answers.
    • Java coding interview questions and answers:. Covers a number of coding questions with answers. These are some of the popular coding interview questions like reversing a string, calculating the Fibonacci number, recursion vs iteration, equals versus ==, etc.

    Q6. How would you go about designing a car parking station?
    A6.
    Map out the requirements:
    • The car park needs to cater for different types of car parks like regular, handicapped, and compact.
    • It should keep track of empty and filled spaces.
    • It should also cater for valet parking.
    Map out the classes that would be required. Use a UML class diagram. Here are some points to get started.
    • A CarPark class to represent a parking station.
    • A ParkingSpace can be an abstract class or an interface to represent a parking space, and RegularParkingSpace, HandicappedParkingSpace, CompactParkingSpace, etc are subtypes of a ParkingSpace. This means a RegularParkingSpace is a ParkingSpace.
    • A CarPark has a (i.e. composition) finite number of ParkingSpaces. A CarPark also keeps track of all the parking spaces and a separate list of all the vacant parking spaces.
    • A Vehicle class uses a (i.e. delegation) ParkingSpace.  The Vehicle class will hold attributes using enum classes like  VehicleType and ParkingType. The vehicle types could be Compact, Regular, and Handicapped. The parking types could be Self or Valet. Depending on the requirements, the self or valet types could be designed as subtypes of the Vehicle class.


    Q7: Can you design the classes that represent a restaurant?
    A7: Very popular. Good understanding of OO design is vital to job interview success. Learn the SOLID design principles, know why you favor composition over inheritance, and dont under estimate the power of coding to interface.
    • Java OO Interview Questions and Answers. A step-by-step tutorial explaining how you would go about designing your classes. The "Core Java Career Essentials" PDF covers more examples on SOLID design principles with working code.

    How would you go about identifying thread safety issues in an application? How would you go about identifying memory leaks issues? How would you go about identifying performance issues?, etc to judge your experience. I am yet to work on a project that didnt face problems relating to thread safety, memory leaks, and performance issues. Hence, it really pays to market your skills and experience in fixing issues relating to these common challenges.


    Q8. How will you go about fixing memory leaks in Java?
    A8. Again, a very common problem, and a thorough answer will go a long way in securing your next Java job.

    Q9: How will you go about fixing performance issues in Java?
    A9:
    • Detecting performance issues in Java. A basic tutorial covering -- how to detect performance issues.
    • Also, refer to the JMeter tutorials in this blog as to learn how you can put load on your application to simulate concurrent users.

    Q10: How will you go about detecting and fixing thread-safety issues in Java?
    A10: Debugging concurrency issues and fixing any thread starvation, dead lock, and contention requires skills and experience to identify and reproduce these hard to resolve issues. Here are some techniques to detect concurrency issues.
    • Manually reviewing the code for any obvious thread-safety issues. There are static analysis tools like Sonar, ThreadCheck, etc for catching concurrency bugs at compile-time by analyzing their byte code.
    • List all possible causes and add extensive log statements and write test cases to prove or disprove your theories.
    • Thread dumps are very useful for diagnosing synchronization problems such as deadlocks. The trick is to take 5 or 6 sets of thread dumps at an interval of 5 seconds between each to have a log file that has 25 to 30 seconds worth of runtime action. For thread dumps, use kill -3 in Unix and CTRL+BREAK in Windows. There are tools like Thread Dump Analyzer (TDA), Samurai, etc. to derive useful information from the thread dumps to find where the problem is. For example, Samurai colors idle threads in grey, blocked threads in red, and running threads in green. You must pay more attention to those red threads.
    • There are tools like JDB (i.e. Java DeBugger) where a “watch” can be set up on the suspected variable. When ever the application is modifying that variable, a thread dump will be printed.
    • There are dynamic analysis tools like jstack and JConsole, which is a JMX compliant GUI tool to get a thread dump on the fly. The JConsole GUI tool does have handy features like “detect deadlock” button to perform deadlock detection operations and ability to inspect the threads and objects in error states. Similar tools are available for other languages as well.

    Java Interview Questions 11- 13 for experienced developers

    Read More..

    Servlets interview questions and answers

    Senin, 03 Februari 2014

    Q. How do you get your servlet to stop timing out on a really long database query?
    A. There are situations despite how much database tuning effort you put into a project, there might be complex queries or a batch process initiated via a Servlet, which might take several minutes to execute. The issue is that if you call a long query from a Servlet or JSP, the browser may time out before the call completes. When this happens, the user will not see the results of their request. There are proprietary solutions to this problem like asynchronous servlets in WebLogic, Async Beans in WebSphere etc but you need a solution that is portable. Let us look at portable solutions to this issue.



    Solution 1: Client-pull or client-refresh (aka server polling): You can use the tag for polling the server. This tag tells the client it must refresh the page after a number of seconds.

    <META http-equiv=”Refresh” content=”10; url=”newPage.html” />


    Once you can have the browser poll your Servlet on a regular basis to re-fetch a page, then your servlet can check for a value of a variable say in a HttpSession to determine if the page returned will have the results expected by the user or resend the tag with a “Please wait …” message and retry fetching the page again later.

    Solution 2: JEE Solution: Instead of spawning your own threads within your Servlet, you could use JMS (Java Messaging Service). This involves following steps:

    1. You need to have two servlets, a RequestingServlet and a DisplayingServlet. The initial client request is sent to the RequestingServlet. Both the RequestingServlet and DisplayingServlet polled by the browser via tag discussed above or JavaScript. Both these Servlets should send the tag with their responses until final display of the query results.
    2. RequestingServlet places the query on the “request” queue using JMS.
    3. You need to have a MessageDrivenBean (aka MDB) say QueryProcessorMDB, which dequeues the query from the “request” queue and performs the long-running database operation. On completion of processing long-running database operation, the QueryProcessorMDB returns the query results to the “reply” queue (use javax.jms.QueueSender & javax.jms.ObjectMessage). Note: MDBs are invoked asynchronously on arrival of messages in the queue.
    4. DisplayingServlet checks the “reply” queue for the query results using JMS (use javax.jms.QueueReceiver & javax.jms.ObjectMessage) every few seconds via tag described above or a JavaScript.

    Advantages: Firstly, implementing your long-running database operation to be invoked from onMessage( ) method of your QueryProcessorMDB decouples your application whereby if a database failure occurs, the request query message will be placed back in the “request” queue and retried again later. Secondly MDBs can be clustered (with or without additional JVMs) to listen on the same “request” queue. This means cluster of MDBs will be balancing the load of processing long running database operations. This can improve the throughput due to increased processing power.


    Q. What is the difference between forwarding a request and redirecting a request?
    A. Both methods send you to a new resource like Servlet, JSP, etc



    Forward:
    • Forward action takes place within the server without the knowledge of the browser. Accepts relative path to the servlet or context root.
    • No extra network trip.

    Redirect:
    • Sends a header back to the browser, which contains the name of the resource to be redirected to. The browser will make a fresh request from this header information. Need to provide absolute URL path.
    • This has an overhead of extra remote trip but has the advantage of being able to refer to any resource on the same or different domain and also allows book marking of the page.
    Q. What are the considerations for servlet clustering?
    A.

    • Objects stored in a session should be serializable to support in-memory replication of sessions. Also consider the overhead of serializing very large objects. Test the performance to make sure it is acceptable.
    • Design for idempotence. Failure of a request or impatient users clicking again can result in duplicate requests being submitted. So the Servlets should be able to tolerate duplicate requests.
    • Avoid using instance and static variables in read and write mode because different instances may exist on different JVMs. Any state should be held in an external resource such as a database. 
    • Avoid storing values in a ServletContext. A ServletContext is not serializable and also the different instances may exist in different JVMs.
    • Avoid using java.io.* because the files may not exist on all backend machines. Instead use getResourceAsStream().


    Q. How do you perform I/O operations in a Servlet/JSP?
    A.

    Problem: Since web applications are deployed as WAR files on the application server’s web container, the full path and relative paths to these files vary for each server.

    Solution -1: You can configure the file paths in web.xml using tags and retrieve file paths in your Servlets/JSPs. But this technique requires changes to the web.xml deployment descriptor file, to point to the correct path.


    Solution -2: You can overcome these configuration issues by using the features of java.lang.ClassLoader and javax.servlet.ServletContext classes. There are various ways of reading a file using the ServletContext API methods such as getResource(String resource),getResourceAsStream(String resource), getResourcePaths(String path) and getRealPath(String path). The getRealPath(String path) method translates virtual URL into real path.


    //Get the file “products.xml” under the WEB-INF folder of  your application as inputstream
    InputStream is = config.getServletContext().getResourceAsStream(“/products.xml”);

    Alternatively you can use the APIs from ClassLoader as follows. The file “products.xml” should be placed under WEB-INF/classes directory where all web application classes reside.

    //Get the URL for the file and create a stream explicitly 
    URL url = config.getServletContext().getResource(“/products.xml”);
    BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream));
    OR
    //use the context class loader
    URL url = Thread.currentThread().getContextClassLoader().getResource(“products-out.xml”);
    BufferedWriter bw = new BufferedWriter(new FileWriter(url.getFile());


    Q. How do you send a file to a browser from your web application? I.e. how do you download a file from your web application?
    A. Files can be downloaded from a web application by using the right combination of headers.

    //set the header to a non-standard value for attachments to be saved by the browser with the //Save-As dialog so that it is unrecognized by the browsers because often browsers try to do //something special when they recognize the content-type. 
    response.setContentType(“application/x-download”);
    //use Content-Disposition “attachment” to invoke “Save As” dialog and “inline” for displaying //the file content on the browser without invoking the “Save As” dialog.
    response.setHeader(“Content-disposition”, “attachment;filename=” + fileName);


    Q. How do you send a file from a browser to your web application? i.e. How do you upload a file to your web application?
    A. There are better and more secured ways to upload your files instead of using using web. For example FTP, secure FTP etc. But if you need to do it via your web application then your default encoding and GET methods are not suitable for file upload and a form containing file input fields must specify the encoding type “multipart/form-data” and the POST method in the
    tag as shown below:

    <form enctype=”multipart/form-data” method=”POST”  action=”/MyServlet”>
    <input type=”file” name=”products” />
    <input type=”submit” name=”Upload” value=”upload” />
    </form>

    When the user clicks the “Upload” button, the client browser locates the local file and sends it to the server using HTTP POST. When it reaches your server, your implementing servlet should process the POST data in order to extract the encoded file. Unfortunately, application servers implementing the Servlet and JSP specifications are not required to handle the multipart/form-data encoding. Fortunately there are number of libraries available such as Apache Commons File Upload, which is a small Java package that lets you obtain the content of the uploaded file from the encoded form data. The API of this package is flexible enough to keep small files in memory while large files are stored on disk in a “temp” directory. You can specify a size threshold to determine when to keep in memory and when to write to disk.

    Note: The above questions and answers are extracted from the book Java/J2EE Job Interview Companion. Only a few questions and answers are extracted.
    Read More..

    Top 10 Servlet Interview Question Answers J2EE

    Minggu, 02 Februari 2014

    This time its servlet interview questions, I was thinking what to pick for my interview series and than I thought about J2EE and Servlet is my favorite on that space. Servlet is an important part of any J2EE development and serves as Controller on many web MVC frameworks and that’s why it’s quite popular on J2EE interviews. These Servlet questions are based on my experience as well as collected by friends and colleague and they are not only good for interview practice but also shows a new direction of learning for any one who is not very familiar with servlet technology.

    Servlet interview question and answerAs said earlier this interview question article is part of my earlier series java interview questions , UNIX command interview questions and Java threading interview questions.

    You can find answers of all these questions on google but I have also listed my answers fo r quick reference.
    Read more »
    Read More..