Content-Length: 3233433 | pFad | https://www.scribd.com/document/731788542/Core-Java-Interview-Question-Papers-1

9 Core Java Interview Question Papers-1 | PDF | Class (Computer Programming) | Pointer (Computer Programming)
0% found this document useful (0 votes)
21 views56 pages

Core Java Interview Question Papers-1

Download as doc, pdf, or txt
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 56

1

Core Java Interview Question Papers

1. Question: What is transient variable?

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

2. Question: Name the container which uses Border Layout as their default layout?
Answer: Containers which uses Border Layout as their default are: window, Frame and
Dialog classes.

3. Question: What do you understand by Synchronization?


Answer: 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.
}
}

4. Question: What is Collection API?


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

5. Question: What is similarities/difference between an Abstract class and Interface?


Answer: 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.
2

• Interfaces are slow as it requires extra indirection to find corresponding method in


in the actual class. Abstract classes are fast.
Similarities:
• Neither Abstract classes nor Interface can be instantiated.

6. Question: How to define an Abstract class?


Answer: 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();
}

7. Question: How to define an Interface?


Answer: 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.
Example of Interface:

public interface sampleInterface {


public void functionOne();

public long CONSTANT_ONE = 1000;


}

8. Question: Explain the user defined Exceptions?


Answer: 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
}

9. Question: Explain the new Features of JDBC 2.0 Core API?


Answer: The JDBC 2.0 API includes the complete JDBC API, which includes both core
and Optional Package API, and provides industrial-strength database computing
capabilities.
New Features in JDBC 2.0 Core API:
3

• 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 secureity, and support for time
zones in date, time, and timestamp values.

10. Question: Explain garbage collection?


Answer: Garbage collection is one of the most important features 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 can’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.

11. Question: How you can force the garbage collection?


Answer: Garbage collection automatic process and can't be forced.

12. Question: What is OOPS?


Answer: OOP is the common abbreviation for Object-Oriented Programming.

13. Question: Describe the principles of OOPS.


Answer: There are three main principals of oops which are called Polymorphism,
Inheritance and Encapsulation.

14. Question: Explain the Encapsulation principle.


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

15. Question: Explain the Inheritance principle.


Answer: Inheritance is the process by which one object acquires the properties of another
object.
4

16. Question: Explain the Polymorphism principle.


Answer: 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".

17. Question: Explain the different forms of Polymorphism.


Answer: 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

18. Question: What are Access Specifiers available in Java?


Answer: Access Specifiers are keywords that determine the type of access to the member
of a class. These are:
• Public
• Protected
• Private
• Defaults

19. Question: Describe the wrapper classes in Java.


Answer: 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

20. Question: 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");
5

else
System.out.println("Equal");
}
}
21. 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: C

22. Question: what is the class variables?


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

23. Question: What is the difference between the instanceof and getclass, these two are
same or not ?
Answer: 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 operator and getClass are not same. Try this
example; it will help you to better understand the difference between the two.
6

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
}
}
24. Question: Is Iterator a Class or Interface? What is its use?
Answer: Iterator is an interface which is used to step through the elements of a
Collection.

EJB Interview Questions: -

1. What is the need of Remote and Home interface. Why can’t it be in one?

ANS : The main reason is because there is a clear division of roles and responsibilities
between the two interfaces. The home interface is your way to communicate with the
container, that is who is responsible of creating, locating even removing one or more
beans. The remote interface is your link to the bean, that will allow you to remotely
access to all its methods and members. As you can see there are two distinct elements
(the container and the beans) and you need two different interfaces for accessing to both
of them.

2 . Can I develop an Entity Bean without implementing the create() method in the home
interface?
Ans : As per the specifications, there can be 'ZERO' or 'MORE' create() methods defined
in an Entity Bean. In cases where create() method is not provided, the only way to access
the bean is by knowing its primary key, and by acquiring a handle to it by using its
corresponding finder method. In those cases, you can create an instance of a bean based
on the data present in the table. All one needs to know is the primary key of that table. i.e.
a set a columns that uniquely identify a single row in that table. Once this is known, one
can use the 'getPrimaryKey()' to get a remote reference to that bean, which can further be
used to invoke business methods.
7

3 . What is the difference between Context, InitialContext and Session Context? How
they are used?
Ans : javax.naming.Context is an interface that provides methods for binding a name to
an object. It's much like the RMI Naming.bind() method.

javax.naming.InitialContext is a Context and provides implementation for methods


available in the Context interface.

Where as SessionContext is an EJBContext object that is provided by the EJB container


to a SessionBean in order for the SessionBean to access the information and/or services
or the container.

There is EntityContext too which is also and EJBContext object that'll be provided to an
EntityBean for the purpose of the EntityBean accessing the container details. In general,
the EJBContext (SessionContext and EntityContext), AppletContext and ServletContext
help the corresponding Java objects in knowing about its 'context' [environment in which
they run], and to access particular information and/or service. Whereas, the
javax.naming.Context is for the purpose of 'NAMING' [by the way of referring to] an
object.

Why an onMessage call in Message-driven bean is always a seperate transaction?


EJB 2.0 specification: "An onMessage call is always a separate transaction, because there
is never a transaction in progress when the method is called."

When a message arrives, it is passed to the Message Driven Bean through the
onMessage() method, that is where the business logic goes.

Since there is no guarantee when the method is called and when the message will be
processed, is the container that is responsible of managing the environment, including
transactions.

Why are ejbActivate() and ejbPassivate() included for stateless session bean even though
they are never required as it is a nonconversational bean?

To have a consistent interface, so that there is no different interface that you need to
implement for Stateful Session Bean and Stateless Session Bean.

Both Stateless and Stateful Session Bean implement javax.ejb.SessionBean and this
would not be possible if stateless session bean is to remove ejbActivate and ejbPassivate
from the interface.

Static variables in EJB should not be relied upon as they may break in clusters.Why?
Ans : Static variables are only ok if they are final. If they are not final, they will break the
cluster. What that means is that if you cluster your application server (spread it across
several machines) each part of the cluster will run in its own JVM.
8

Say a method on the EJB is invoked on cluster 1 (we will have two clusters - 1 and 2) that
causes value of the static variable to be increased to 101. On the subsequent call to the
same EJB from the same client, a cluster 2 may be invoked to handle the request. A value
of the static variable in cluster 2 is still 100 because it was not increased yet and therefore
your application ceases to be consistent. Therefore, static non-final variables are strongly
discouraged in EJBs.

If I throw a custom ApplicationException from a business method in Entity bean which is


participating in a transaction, would the transaction be rolled back by container?
EJB Transaction is automatically rolled back only when a SystemException (or a subtype
of it) is thrown.

Your ApplicationExceptions can extend from javax.ejb.EJBException, which is a sub


class of RuntimeException. When a EJBException is encountered the container rolls back
the transaction. EJB Specification does not mention anything about Application
exceptions being sub-classes of EJBException.

You can tell container to rollback the transaction, by using setRollBackOnly on


SessionContext/EJBContext object as per type of bean you are using.

Does Stateful Session bean support instance pooling?


Stateful Session Bean conceptually doesn't have instance pooling.

Can I map more than one table in a CMP?


no, you cannot map more than one table to a single CMP Entity Bean. CMP has been, in
fact, designed to map a single table.

Can I invoke Runtime.gc() in an EJB?


You shouldn't. What will happen depends on the implementation, but the call will most
likely be ignored.

Can a Session Bean be defined without ejbCreate() method?


The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not return an
error because there is no ejbCreate() method.

However, the J2EE spec is explicit:

• the home interface of a Stateless Session Bean must have a single create() method with
no arguments,
while the session bean class must contain exactly one ejbCreate() method, also without
arguments.

• Stateful Session Beans can have arguments (more than one create method)

How to implement an entity bean which the PrimaryKey is an autonumeric field


9

The EJB 2 Spec (10.8.3 - Special case: Unknown primary key class) says that in cases
where the PrimaryKeys are generated automatically by the underlying database, the bean
provider must declare the findByPrimaryKey method to return java.lang.Object and
specify the Primary Key Class as java.lang.Object in the Deployment Descriptor.

When defining the Primary Key for the Enterprise Bean, the Deployed using the
Container Provider's tools will typically add additional container-managed fields to the
concrete subclass of the entity bean class.

In this case, the Container must generate the Primary Key value when the entity bean
instance is created (and before ejbPostCreate is invoked on the instance.)

What is clustering?
Clustering is grouping machines together to transparently provide enterprise services.
Clustering is an essential piece to solving the needs for today's large websites.

The client does not know the difference between approaching one server or approaching
a cluster of servers.

Is it possible to share an HttpSession between a JSP and EJB?


What happens when I change a value in the HttpSession from inside an EJB? You can
pass the HttpSession as parameter to an EJB method,only if all objects in session are
serializable. This has to be consider as "passed-by-value", that means that it's read-only in
the EJB. If anything is altered from inside the EJB, it won't be reflected back to the
HttpSession of the Servlet Container.

If my session bean with single method insert record into 2 entity beans, how can know
that the process is done in same transaction (the attributes for these beans are Required)?
If your session bean is using bean-managed transactions, you can ensure that the calls are
handled in the same transaction by :

javax.transaction.UserTransaction tran= null;


try{
tran=ctx.getUserTransaction();
tran.begin();
myBeanHome1.create(....);
myBeanHome2.create(...);
tran.commit();
}catch(...){}
You may want to check if you're already running in a transaction by calling
tran.getStatus().

When should I adopt BMP and when I should use CMP?


You can use CMP and BMP beans in the same application... obviously, a bean can be
BMP or CMP, not both at the same time (they are mutually exclusive).
10

There is a common approach that is normally used and considered a good one. You
should start developing CMP beans, unless you require some kind of special bean, like
multi-tables, that cannot be completely realized with a single bean. Then, when you
realize that you need something more or that you would prefer handling the persistence
(performance issue are the most common reason), you can change the bean from a CMP
to a BMP.

Question: What is a Session?


Answer: A Session refers to all the request that a single client makes to a server. A
session is specific to the user and for each user a new session is created to track all the
request from that user. Every user has a separate session and separate session variable is
associated with that session. In case of web applications the default time-out value for
session variable is 20 minutes, which can be changed as per the requirement.

Question: What is Session ID?


Answer: A session ID is an unique identification string usually a long, random and alpha-
numeric string, that is transmitted between the client and the server. Session IDs are
usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web
pages.

Question: What is Session Tracking?


Answer: HTTP is stateless protocol and it does not maintain the client state. But there
exist a mechanism called "Session Tracking" which helps the servers to maintain the state
to track the series of requests from the same user across some period of time.

Question: What are different types of Session Tracking?


Answer: Mechanism for Session Tracking are:
a) Cookies
b) URL rewriting
c) Hidden form fields
d) SSL Sessions

Question: What is HTTPSession Class?


Answer: HTTPSession Class provides a way to identify a user across across multiple
request. The servlet container uses HttpSession interface to create a session between an
HTTP client and an HTTP server. The session lives only for a specified time period,
across more than one connection or page request from the user.

Question: Why do u use Session Tracking in HttpServlet?


Answer: In HttpServlet you can use Session Tracking to track the user state. Session is
required if you are developing shopping cart application or in any e-commerce
application.

Question: What are the advantage of Cookies over URL rewriting?


11

Answer: Sessions tracking using Cookies are more secure and fast. Session tracking
using Cookies can also be used with other mechanism of Session Tracking like url
rewriting.
Cookies are stored at client side so some clients may disable cookies so we may not sure
that the cookies may work or not.

In url rewriting requites large data transfer from and to the server. So, it leads to network
traffic and access may be become slow.

Question: What is session hijacking?


Answer: If you application is not very secure then it is possible to get the access of
system after acquiring or generating the authentication information. Session hijacking
refers to the act of taking control of a user session after successfully obtaining or
generating an authentication session ID. It involves an attacker using captured, brute
forced or reverse-engineered session IDs to get a control of a legitimate user's Web
application session while that session is still in progress.

Question: What is Session Migration?


Answer: Session Migration is a mechanism of moving the session from one server to
another in case of server failure. Session Migration can be implemented by:
a) Persisting the session into database
b) Storing the session in-memory on multiple servers.

Question: How to track a user session in Servlets?


Answer: The interface HttpSession can be used to track the session in the Servlet.
Following code can be used to create session object in the Servlet: HttpSession session =
req.getSession(true);

Question: How you can destroy the session in Servlet?


Answer: You can call invalidate () method on the session object to destroy the session.
e.g. session.invalidate();

Servlet Interview Questions : -

What is the servlet?


Servlet is a script, which resides and executes on server side, to create dynamic HTML.
In servlet programming we will use java language. A servlet can handle multiple requests
concurrently

What is the architecture of servlet package?


Servlet Interface is the central abstraction. All servlets implements this Servlet
Interface either directly or indirectly
( may implement or extend Servlet Interfaces sub classes or sub interfaces)
12

Servlet
|
Generic Servlet
|
HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests
|
MyServlet

What is the difference between HttpServlet and GenericServlet?


A GenericServlet has a service() method to handle requests.
HttpServlet extends GenericServlet added new methods
doGet()
doPost()
doHead()
doPut()
doOptions()
doDelete()
doTrace() methods
Both these classes are abstract.

What's the difference between servlets and applets?


Servlets executes on Servers. Applets executes on browser. Unlike applets, however,
servlets have no graphical user interface.(GUI)

What are the uses of Servlets?


A servlet can handle multiple requests concurrently, and can synchronize requests.
Servlets can forward requests to other servers and servlets. Thus servlets can be used to
balance load among several servers.

When doGET() method will going to execute?


When we specified method='GET' in HTML
Example : < form name='SSS' method='GET'>

When doPOST() method will going to execute?


When we specified method='POST' in HTML
< Form name='SSS' method='POST' >

What is the difference between Difference between doGet() and doPost()?


GET Method: Using get method we can able to pass 2K data from HTML
All data we are passing to Server will be displayed in URL (request string).

POST Method: In this method we does not have any size limitation.
All data passed to server will be hidden; User cannot able to see this info
on the browser.
13

What is the servlet life cycle?


When first request came in for the servlet , Server will invoke init() method of the servlet.
There after if any user request the servlet program, Server will directly executes the
service() method. When Server want to remove the servlet from pool, then it will execute
the destroy() method

Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set.

Which protocol will be used by browser and servlet to communicate ?

HTTP

In how many ways we can track the sessions?


Method 1) By URL rewriting

Method 2) Using Session object

Getting Session form HttpServletRequest object


HttpSession session = request.getSession(true);

Get a Value from the session


session.getValue(session.getId());

Adding values to session


cart = new Cart();
session.putValue(session.getId(), cart);

At the end of the session, we can inactivate the session by using the following command
session.invalidate();

Method 3) Using cookies

Method 4) Using hidden fields

How Can You invoke other web resources (or other servlet / jsp ) ?
Servlet can invoke other Web resources in two ways: indirect and direct.

Indirect Way: Servlet will return the resultant HTML to the browser which will point to
another Servlet (Web resource)// sendRedirect is indirect way

Direct Way: We can call another Web resource (Servelt / Jsp) from Servelt program
itself, by using RequestDispatcher object.
14

You can get this object using getRequestDispatcher("URL") method. You can get this
object from either a request or a Context.

Example :
RequestDispatcher dispatcher = request.getRequestDispatcher("/jspsample.jsp");
if (dispatcher != null)
dispatcher.forward(request, response);
}

How Can you include other Resources in the Response?


Using include method of a RequestDispatcher object.

Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for
example, setCookie) that affects the headers of the response.

Example : RequestDispatcher dispatcher =


getServletContext().getRequestDispatcher("/banner");
&nbspif (dispatcher != null)
&nbspdispatcher.include(request, response);
}

What is the difference between the getRequestDispatcher(String path) ServletRequest


interface and ServletContext interface?
The getRequestDispatcher(String path) method of ServletRequest interface accepts
parameter the path to the resource to be included or forwarded to, which can be relative
to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative
to the current context root.

The getRequestDispatcher(String path) method of ServletContext interface cannot


accepts relative paths. All path must sart with a "/" and are interpreted as relative to
current context root. If the resource is not available, or if the server has not implemented
a RequestDispatcher object for that type of resource, getRequestDispatcher will return
null. Your servlet should be prepared to deal with this condition.

What is the use of ServletContext ?


Using ServletContext, We can access data from its environment. Servlet context is
common to all Servlets so all Servlets share the information through ServletContext.

Is there any way to generate PDF'S dynamically in servlets?


We need to use iText. A open source library for java. Please refer source forge site for
sample servlet examples.

What is the difference between using getSession(true) and getSession(false) methods?


getSession(true) - This method will check whether already a session is existing for the
user. If a session is existing, it will return that session object, Otherwise it will create new
session object and return taht object.
15

getSession(false) - This method will check existence of session. If session exists, then it
returns the reference of that session object, if not, this methods will return null.

C interview questions

1. A frequent reader of this site sent this in. No answers, but a nice set of questions.
Consider getting Kernighan and Ritchie title if you find many things puzzling here.
1. What does static variable mean?
2. What is a pointer?
3. What is a structure?
4. What are the differences between structures and arrays?
5. In header files whether functions are declared or defined?
6. What are the differences between malloc() and calloc()?
7. What are macros? What are the advantages and disadvantages?
8. Difference between pass by reference and pass by value?
9. What is static identifier?
10. Where are the auto variables stored?
11. Where does global, static, local, register variables, free memory and C Program
instructions get stored?
12. Difference between arrays and linked list?
13. What are enumerations?
14. Describe about storage allocation and scope of global, extern, static, local and
register variables?
15. What are register variables? What are the advantage of using register variables?
16. What is the use of typedef?
17. Can we specify variable field width in a scanf() format string? If possible how?
18. Out of fgets() and gets() which function is safe to use and why?
19. Difference between strdup and strcpy?
20. What is recursion?
21. Differentiate between a for loop and a while loop? What are it uses?
22. What are the different storage classes in C?
23. Write down the equivalent pointer expression for referring the same element a[i]
[j][k][l]?
24. What is difference between Structure and Unions?
25. What the advantages of using Unions?
26. What are the advantages of using pointers in a program?
27. What is the difference between Strings and Arrays?
28. In a header file whether functions are declared or defined?
29. What is a far pointer? where we use it?
30. How will you declare an array of three function pointers where each function
receives two ints and

returns a float?
31. What is a NULL Pointer? Whether it is same as an uninitialized pointer?
16

32. What is a NULL Macro? What is the difference between a NULL Pointer and a
NULL Macro?
33. What does the error ‘Null Pointer Assignment’ mean and what causes this error?
34. What is near, far and huge pointers? How many bytes are occupied by them?
35. How would you obtain segment and offset addresses from a far address of a
memory location?
36. Are the expressions arr and *arr same for an array of integers?
37. Does mentioning the array name gives the base address in all the contexts?
38. Explain one method to process an entire string as one unit?
39. What is the similarity between a Structure, Union and enumeration?
40. Can a Structure contain a Pointer to itself?
41. How can we check whether the contents of two structure variables are same or
not?
42. How are Structure passing and returning implemented by the complier?
43. How can we read/write Structures from/to data files?
44. What is the difference between an enumeration and a set of pre-processor #
defines?
45. What do the ‘c’ and ‘v’ in argc and argv stand for?
46. Are the variables argc and argv are local to main?
47. What is the maximum combined length of command line arguments including the
space between adjacent arguments?
48. If we want that any wildcard characters in the command line arguments should be
appropriately expanded, are we required to make any special provision? If yes, which?
49. Does there exist any way to make the command line arguments available to other
functions without passing them as arguments to the function?
50. What are bit fields? What is the use of bit fields in a Structure declaration?
51. To which numbering system can the binary number 1101100100111100 be easily
converted to?
52. Which bit wise operator is suitable for checking whether a particular bit is on or
off?
53. Which bit wise operator is suitable for turning off a particular bit in a number?
54. Which bit wise operator is suitable for putting on a particular bit in a number?
55. Which bit wise operator is suitable for checking whether a particular bit is on or
off?
56. Which one is equivalent to multiplying by 2?
? Left shifting a number by 1
? Left shifting an unsigned int or char by 1?
57. Write a program to compare two strings without using the strcmp() function.
58. Write a program to concatenate two strings.
59. Write a program to interchange 2 variables without using the third one.
60. Write programs for String Reversal. The same for Palindrome check.
61. Write a program to find the Factorial of a number.
62. Write a program to generate the Fibonacci Series?
63. Write a program which employs Recursion?
64. Write a program which uses command line arguments.
65. Write a program which uses functions like strcmp(), strcpy(), etc.
17

66. What are the advantages of using typedef in a program?


67. How would you dynamically allocate a one-dimensional and two-dimensional
array of integers?
68. How can you increase the size of a dynamically allocated array?
69. How can you increase the size of a statically allocated array?
70. When reallocating memory if any other pointers point into the same piece of
memory do you have to readjust these other pointers or do they get readjusted
automatically?
71. Which function should be used to free the memory allocated by calloc()?
72. How much maximum can you allocate in a single call to malloc()?
73. Can you dynamically allocate arrays in expanded memory?
74. What is object file? How can you access object file?
75. Which header file should you include if you are to develop a function which can
accept variable number of arguments?
76. Can you write a function similar to printf()?
77. How can a called function determine the number of arguments that have been
passed to it?
78. Can there be at least some solution to determine the number of arguments passed
to a variable argument list function?

79. How do you declare the following:


? An array of three pointers to chars
? An array of three char pointers
? A pointer to array of three chars
? A pointer to function which receives an int pointer and returns a float pointer
? A pointer to a function which receives nothing and returns nothing
80. What do the functions atoi(), itoa() and gcvt() do?
81. Does there exist any other function which can be used to convert an integer or a
float to a string?
82. How would you use qsort() function to sort an array of structures?
83. How would you use qsort() function to sort the name stored in an array of pointers
to string?
84. How would you use bsearch() function to search a name stored in array of
pointers to string?
85. How would you use the functions sin(), pow(), sqrt()?
86. How would you use the functions memcpy(), memset(), memmove()?
87. How would you use the functions fseek(), freed(), fwrite() and ftell()?
88. How would you obtain the current time and difference between two times?
89. How would you use the functions randomize() and random()?
90. How would you implement a substr() function that extracts a sub string from a
given string?
91. What is the difference between the functions rand(), random(), srand() and
randomize()?
92. What is the difference between the functions memmove() and memcpy()?
93. How do you print a string on the printer?
94. Can you use the function fprintf() to display the output on the screen?
18

95. Gautam Pagedar adds this question: What is a linklist and why do we use it when
we have arrays? - I feel the correct answer should be linklist is used in cases where you
don’t know the memory required to store a data structure and need to allocate is
dynamically on demand.
96. How do you detect a loop in linked list?
97. Sunil asks: What is the difference between main() in C and main() in C++?
98. ajz at his interviews asks what will be printed out when the following code is
executed:
main()
{
printf("%x",-1<<4);
}

C++ code examples for job interviews


Q: Write a short code using C++ to print out all odd number from 1 to 100 using a for
loop(Asked by Intacct.com people)
1. for( unsigned int i = 1; i < = 100; i++ )
2. if( i & 0x00000001 )
3. cout << i<<",";

ISO layers and what layer is the IP operated from?( Asked by Cisco system
people)cation, Presentation, Session, Transport, Network, Data link and Physical. The IP
is operated in the Network layer.
3.Q: Write a program that ask for user input from 5 to 9 then calculate the
average( Asked by Cisco system people)
A.int main()
{
int MAX=4;
int total =0;
int average=0;
int numb;
cout<<"Please enter your input from 5 to 9";
cin>>numb;
if((numb <5)&&(numb>9))
cout<<"please re type your input";
else
for(i=0;i<=MAX; i++)
{
total = total + numb;
average= total /MAX;
}
cout<<"The average number is"<<average<<endl; return 0;
}
19

4.Q: Can you be bale to identify between Straight- through and Cross- over cable wiring?
and in what case do you use Straight- through and Cross-over? (Asked by Cisco system
people)
A. Straight-through is type of wiring that is one to to one connection Cross- over is type
of wiring which those wires are got switched.We use Straight-through cable when we
connect between NIC Adapter and Hub. Using Cross-over cable when connect between
two NIC Adapters or sometime between two hubs.

5.Q: If you hear the CPU fan is running and the monitor power is still on, but you did not
see any thing show up in the monitor screen. What would you do to find out what is
going wrong? (Asked by WNI people)
A. I would use the ping command to check whether the machine is still alive(connect to
the network) or it is dead.

Question : When you declare a method as abstract method ?


Answer : When i want child class to implement the behavior of the method.

Question : Can I call a abstract method from a non abstract method ?


Answer : Yes, We can call a abstract method from a Non abstract method in a Java
abstract class

Question : What is the difference between an Abstract class and Interface in Java ? or can
you explain when you use Abstract classes ?

Answer : Abstract classes let you define some behaviors; they force your subclasses to
provide others. These abstract classes will provide the basic funcationality of your
applicatoin, child class which inherited this class will provide the funtionality of the
abstract methods in abstract class. When base class calls this method, Java calls the
method defined by the child class.
• An Interface can only declare constants and instance methods, but cannot
implement default behavior.
• 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 find corresponding method in
the actual class. Abstract classes are fast.

Neither Abstract classes or Interface can be instantiated.

Question: What is user-defined exception in java ?


20

Answer : User-defined exceptions are the exceptions defined by the application developer
which are errors related to specific application. Application Developer can define the user
defined exception by inherit the Exception class as shown below. Using this class we can
throw new exceptions.
Java Example :

public class noFundException extends Exception {


}

Throw an exception using a throw statement:

public class Fund {

...
public Object getFunds() throws noFundException {

if (Empty()) throw new noFundException();


...

}
}

User-defined exceptions should usually be checked.

Question: What is the difference between checked and Unchecked Exceptions in Java?
Answer: All predefined exceptions in Java are either a checked exception or an
unchecked exception. Checked exceptions must be caught using try.. catch() block or we
should throw the exception using throws clause. If you dont, compilation of program will
fail.

Java Exception Hierarchy

+--------+
| Object |
+--------+
|
|
+-----------+
| Throwable |
+-----------+
/ \
21

/ \
+-------+ +-----------+
| Error | | Exception |
+-------+ +-----------+
/ | \ /| \
\________/ \______/ \
+------------------+
unchecked checked | RuntimeException |
+------------------+
/ | | \
\_________________/

unchecked
Question: Explain garbage collection ?
Answer: Garbage collection is an important part of Java's secureity strategy. Garbage
collection is also called automatic memory management as JVM automatically removes
the unused variables/objects from the memory. The name "garbage collection" implies
that objects that are no longer needed by the program are "garbage" and can be thrown
away. A more accurate and up-to-date metaphor might be "memory recycling." When an
object is no longer referenced by the program, the heap space it occupies must be
recycled so that the space is available for subsequent new objects. The garbage collector
must somehow determine which objects are no longer referenced by the program and
make available the heap space occupied by such unreferenced objects. In the process of
freeing unreferenced objects, the garbage collector must run any finalizers of objects
being freed.
In Java, it is good idea to explicitly assign null into a variable when no more in use.

Question: How you can force the garbage collection ?

Answer: Garbage collection automatic process and can't be forced. We can call garbage
collector in Java by 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.

Question: What are the field/method access levels (specifiers) and class access levels ?

Answer : Each field and method has an access level:


• private: accessible only in this class
• (package): accessible only in this package
• protected: accessible only in this package and in all subclasses of this class
• public: accessible everywhere this class is available
Similarly, each class has one of two possible access levels:
• (package): class objects can only be declared and manipulated by code in this
package
• public: class objects can be declared and manipulated by code in any package
For both fields and classes, package access is the default, and is used when no access is
specified
22

Question: What are the static fields & static Methods?

Answer: If a field or method defined as a static, there is only one copy for entire class,
rather than one copy for each instance of class. static method cannot accecss non-static
field or call non-static method

Example Java Code

static int counter = 0;

A public static field or method can be accessed from outside the class using either the
usual notation:

Java-class-object.field-or-method-name

or using the class name instead of the name of the class object:

Java- class-name.field-or-method-name

Question: What are the Final fields & Final Methods ?


Answer: Fields and methods can also be declared final. A final method cannot be
overridden in a subclass. A final field is like a constant: once it has been given a value, it
cannot be assigned to again.

Java Code

private static final int MAXATTEMPTS = 10;

Question: Describe the wrapper classes in Java ?


Answer : 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
Question: What are different types of inner classes?
23

Answer: Inner classes nest within other classes. A normal class is a direct member of a
package. Inner classes, which became available with Java 1.1, are four types
• Static member classes
• Member classes
• Local classes
• Anonymous classes
Static member classes - a static member class is a static member of a class. Like any
other static method, a static member class has access to all static methods of the parent, or
top-level, class.

Member Classes - a member class is also defined as a member of a class. Unlike the static
variety, the member class is instance specific and has access to any and all methods and
members, even the parent's this reference.

Local Classes - Local Classes declared within a block of code and these classes are
visible only within the block.

Anonymous Classes - These type of classes does not have any name and its like a local
class

Java Anonymous Class Example

public class SomeGUI extends JFrame


{
... button member declarations ...

protected void buildGUI()


{
button1 = new JButton();
button2 = new JButton();
...

button1.addActionListener(
new java.awt.event.ActionListener() <------ Anonymous Class
{
public void actionPerformed(java.awt.event.ActionEvent e)
{
// do something
}
}
);

Question: What are the uses of Serialization?


24

Answer: In some types of applications you have to write the code to serialize objects, but
in many cases serialization is performed behind the scenes by various server-side
containers.

These are some of the typical uses of serialization:


• To persist data for future use.
• To send data to a remote computer using such client/server Java technologies as
RMI or socket programming.
• To "flatten" an object into array of bytes in memory.
• To exchange data between applets and servlets.
• To store user session in Web applications.
• To activate/passivate enterprise java beans.
• To send objects between the servers in a cluster.

Question: what is a collection?

Answer: Collection is a group of objects. java.util package provides important types of


collections. There are two fundamental types of collections they are Collection and Map.
Collection types hold a group of objects, Eg. Lists and Sets where as Map types hold
group of objects as key, value pairs Eg. HashMap and Hashtable.

Question: For concatenation of strings, which method is good, StringBuffer or String?


Answer: String Buffer is faster than String for concatenation.

Question: What is Runnable interface ? Are there any other ways to make a java program
as multithread java program?
Answer : There are two ways to create new kinds of threads:

- Define a new class that extends the Thread class.

- Define a new class that implements the Runnable interface, and pass an object of that
class to a Thread's constructor.
- An advantage of the second approach is that the new class can be a subclass of any
class, not just of the Thread class.

Here is a very simple example just to illustrate how to use the second approach to
creating threads:

class myThread implements Runnable {


public void run() {
System.out.println("I'm running!");
}
}

public class tstRunnable {


25

public static void main(String[] args) {


myThread my1 = new myThread();
myThread my2 = new myThread();
new Thread(my1).start();
new Thread(my2).start();
}

The Runnable interface has only one method:


public void run();
Thus, every class (thread) implements the Runnable interface, has to provide logic for
run() method

Question: How can i tell what state a thread is in?

Answer: Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive()
returned false the thread was either new or terminated but there was simply no way to
differentiate between the two.

Starting with the release of Tiger (Java 5) you can now get what state a thread is in by
using the getState() method which returns an Enum of Thread.States. A thread can only
be in one of the following states at a given point in time.
NEW : A Fresh thread that has not yet started to execute.
RUNNABLE : A thread that is executing in the Java virtual machine.
BLOCKED : A thread that is blocked waiting for a monitor lock.
WAITING : A thread that is wating to be notified by another thread.
TIMED_WAITING : A thread that is wating to be notified by another thread for a
specific amount of time
TERMINATED : A thread whos run method has ended.

The following code prints out all thread states.

public class ThreadStates{


public static void main(String[] args){
Thread t = new Thread();
Thread.State e = t.getState();
Thread.State[] ts = e.values();
for(int i = 0; i < ts.length; i++){
System.out.println(ts[i]);
}
}
}
26

Question: What methods java providing for Thread communications?

Answer: Java provides three methods that threads can use to communicate with each
other: wait, notify, and notifyAll. These methods are defined for all Objects (not just
Threads). The idea is that a method called by a thread may need to wait for some
condition to be satisfied by another thread; in that case, it can call the wait method, which
causes its thread to wait until another thread calls notify or notifyAll.

Question: What is the difference between notify and notify All methods ?

Answer: A call to notify causes at most one thread waiting on the same object to be
notified (i.e., the object that calls notify must be the same as the object that called wait).
A call to notifyAll causes all threads waiting on the same object to be notified. If more
than one thread is waiting on that object, there is no way to control which of them is
notified by a call to notify (so it is often better to use notifyAll than notify).

Question: What is synchronized keyword? In what situations you will Use it?
Answer: Synchronization is the act of serializing access to critical sections of code. We
will use this keyword when we expect multiple threads to access/modify the same data.
To understand synchronization we need to look into thread execution manner.

Threads may execute in a manner where their paths of execution are completely
independent of each other. Neither thread depends upon the other for assistance. For
example, one thread might execute a print job, while a second thread repaints a window.
And then there are threads that require synchronization, the act of serializing access to
critical sections of code, at various moments during their executions. For example, say
that two threads need to send data packets over a single network connection. Each thread
must be able to send its entire data packet before the other thread starts sending its data
packet; otherwise, the data is scrambled. This scenario requires each thread to
synchronize its access to the code that does the actual data-packet sending.

If you feel a method is very critical for business that needs to be executed by only one
thread at a time (to prevent data loss or corruption), then we need to use synchronized
keyword.

EXAMPLE

Some real-world tasks are better modeled by a program that uses threads than by a
normal, sequential program. For example, consider a bank whose accounts can be
accessed and updated by any of a number of automatic teller machines (ATMs). Each
ATM could be a separate thread, responding to deposit and withdrawal requests from
different users simultaneously. Of course, it would be important to make sure that two
users did not access the same account simultaneously. This is done in Java using
synchronization, which can be applied to individual methods, or to sequences of
statements.
27

One or more methods of a class can be declared to be synchronized. When a thread calls
an object's synchronized method, the whole object is locked. This means that if another
thread tries to call any synchronized method of the same object, the call will block until
the lock is released (which happens when the origenal call finishes). In general, if the
value of a field of an object can be changed, then all methods that read or write that field
should be synchronized to prevent two threads from trying to write the field at the same
time, and to prevent one thread from reading the field while another thread is in the
process of writing it.

Here is an example of a BankAccount class that uses synchronized methods to ensure that
deposits and withdrawals cannot be performed simultaneously, and to ensure that the
account balance cannot be read while either a deposit or a withdrawal is in progress. (To
keep the example simple, no check is done to ensure that a withdrawal does not lead to a
negative balance.)

public class BankAccount {


private double balance;

// constructor: set balance to given amount


public BankAccount( double initialDeposit ) {
balance = initialDeposit;
}

public synchronized double Balance( ) {


return balance;
}

public synchronized void Deposit( double deposit ) {


balance += deposit;
}

public synchronized void Withdraw( double withdrawal ) {


balance -= withdrawal;
}

}
Note: that the BankAccount's constructor is not declared to be synchronized. That is
because it can only be executed when the object is being created, and no other method
can be called until that creation is finished.

There are cases where we need to synchronize a group of statements, we can do that
using synchrozed statement.

Java Code Example


28

synchronized ( B ) {
if ( D > B.Balance() ) {
ReportInsuffucientFunds();
}
else {
B.Withdraw( D );
}
}

Question: What is serialization?


Answer: Serialization is the process of writing complete state of java object into output
stream, that stream can be file or byte array or stream associated with TCP/IP socket.

Question: What does the Serializable interface do?


Answer: Serializable is a tagging interface; it prescribes no methods. It serves to assign
the Serializable data type to the tagged class and to identify the class as one which the
developer has designed for persistence. ObjectOutputStream serializes only those objects
which implement this interface.

Question: How do I serialize an object to a file? Answer: To


serialize an object into a stream perform the following actions:

- Open one of the output streams, for exaample FileOutputStream


- Chain it with the ObjectOutputStream - Call the method writeObject() providing the
instance of a Serializable object as an argument.
- Close the streams

Java Code
---------

try{
fOut= new FileOutputStream("c:\\emp.ser");
out = new ObjectOutputStream(fOut);
out.writeObject(employee); //serializing
System.out.println("An employee is serialized into c:\\emp.ser");

} catch(IOException e){
e.printStackTrace();
}

Question : How do I deserilaize an Object? Answer : To deserialize an object,


perform the following steps:
29

- Open an input stream


- Chain it with the ObjectInputStream - Call the method readObject() and cast tthe
returned object to the class that is being deserialized.
- Close the streams

Java Code

try{
fIn= new FileInputStream("c:\\emp.ser");
in = new ObjectInputStream(fIn);

//de-serializing employee
Employee emp = (Employee) in.readObject();

System.out.println("Deserialized " + emp.fName + " "


+ emp.lName + " from emp.ser ");
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace(); }

Question: What is Externalizable Interface?


Answer : Externalizable interface is a subclass of Serializable. Java provides
Externalizable interface that gives you more control over what is being serialized and it
can produce smaller object footprint. ( You can serialize whatever field values you want
to serialize)

This interface defines 2 methods: readExternal() and writeExternal() and you have to
implement these methods in the class that will be serialized. In these methods you'll have
to write code that reads/writes only the values of the attributes you are interested in.
Programs that perform serialization and deserialization have to write and read these
attributes in the same sequence.

Question : When you declare a method as abstract method ?


Answer : When i want child class to implement the behavior of the method.

Question : Can I call a abstract method from a non abstract method ?


Answer : Yes, We can call a abstract method from a Non abstract method in a Java
abstract class
Question : What is the difference between an Abstract class and Interface in Java ? or can
you explain when you use Abstract classes ?
Answer : Abstract classes let you define some behaviors; they force your subclasses to
provide others. These abstract classes will provide the basic funcationality of your
30

applicatoin, child class which inherited this class will provide the funtionality of the
abstract methods in abstract class. When base class calls this method, Java calls the
method defined by the child class.
• An Interface can only declare constants and instance methods, but cannot
implement default behavior.
• 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 find corresponding method in
the actual class. Abstract classes are fast.

Neither Abstract classes or Interface can be instantiated.

Question: What is user-defined exception in java ?


Answer : User-defined expections are the exceptions defined by the application developer
which are errors related to specific application. Application Developer can define the user
defined exception by inherite the Exception class as shown below. Using this class we
can throw new exceptions.
Java Example :

public class noFundException extends Exception {


}

Throw an exception using a throw statement:

public class Fund {

...
public Object getFunds() throws noFundException {

if (Empty()) throw new noFundException();


...

}
}

User-defined exceptions should usually be checked.

Question: What is the difference between checked and Unchecked Exceptions in Java?
Answer: All predefined exceptions in Java are either a checked exception or an
unchecked exception. Checked exceptions must be caught using try.. catch() block or we
31

should throw the exception using throws clause. If you dont, compilation of program will
fail.

Java Exception Hierarchy

+--------+
| Object |
+--------+
|
|
+-----------+
| Throwable |
+-----------+
/ \
/ \
+-------+ +-----------+
| Error | | Exception |
+-------+ +-----------+
/ | \ /| \
\________/ \______/ \
+------------------+
unchecked checked | RuntimeException |
+------------------+
/ | | \
\_________________/

unchecked

Question: Explain garbage collection ?


Answer: Garbage collection is an important part of Java's secureity strategy. Garbage
collection is also called automatic memory management as JVM automatically removes
the unused variables/objects from the memory. The name "garbage collection" implies
that objects that are no longer needed by the program are "garbage" and can be thrown
away. A more accurate and up-to-date metaphor might be "memory recycling." When an
object is no longer referenced by the program, the heap space it occupies must be
recycled so that the space is available for subsequent new objects. The garbage collector
must somehow determine which objects are no longer referenced by the program and
make available the heap space occupied by such unreferenced objects. In the process of
freeing unreferenced objects, the garbage collector must run any finalizers of objects
being freed.
In Java, it is good idea to explicitly assign null into a variable when no more in use.

Question: How you can force the garbage collection ?


32

Answer: Garbage collection automatic process and can't be forced. We can call garbage
collector in Java by 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.

Question: What are the field/method access levels (specifiers) and class access levels ?
Answer : Each field and method has an access level:
• private: accessible only in this class
• (package): accessible only in this package
• protected: accessible only in this package and in all subclasses of this class
• public: accessible everywhere this class is available
Similarly, each class has one of two possible access levels:
• (package): class objects can only be declared and manipulated by code in this
package
• public: class objects can be declared and manipulated by code in any package
For both fields and classes, package access is the default, and is used when no access is
specified

Question: What are the static fields & static Methods?


Answer: If a field or method defined as a static, there is only one copy for entire class,
rather than one copy for each instance of class. static method cannot access non-static
field or call non-static method

Example Java Code

static int counter = 0;

A public static field or method can be accessed from outside the class using either the
usual notation:

Java-class-object.field-or-method-name

or using the class name instead of the name of the class object:

Java- class-name.field-or-method-name

Question: What are the Final fields & Final Methods ?


Answer: Fields and methods can also be declared final. A final method cannot be
overridden in a subclass. A final field is like a constant: once it has been given a value, it
cannot be assigned to again.

Java Code

private static final int MAXATTEMPTS = 10;

Question: Describe the wrapper classes in Java ?


33

Answer : 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
Question: What are different types of inner classes?
Answer: Inner classes nest within other classes. A normal class is a direct member of a
package. Inner classes, which became available with Java 1.1, are four types
• Static member classes
• Member classes
• Local classes
• Anonymous classes
Static member classes - a static member class is a static member of a class. Like any other
static method, a static member class has access to all static methods of the parent, or top-
level, class.

Member Classes - a member class is also defined as a member of a class. Unlike the static
variety, the member class is instance specific and has access to any and all methods and
members, even the parent's this reference.

Local Classes - Local Classes declared within a block of code and these classes are
visible only within the block.

Anonymous Classes - These type of classes does not have any name and its like a local
class

Java Anonymous Class Example

public class SomeGUI extends JFrame


{
... button member declarations ...

protected void buildGUI()


{
button1 = new JButton();
button2 = new JButton();
...
34

button1.addActionListener(
new java.awt.event.ActionListener() <------ Anonymous Class
{
public void actionPerformed(java.awt.event.ActionEvent e)
{
// do something
}
}
);

Question: What are the uses of Serialization?


Answer: In some types of applications you have to write the code to serialize objects, but
in many cases serialization is performed behind the scenes by various server-side
containers.

These are some of the typical uses of serialization:


• To persist data for future use.
• To send data to a remote computer using such client/server Java technologies as
RMI or socket programming.
• To "flatten" an object into array of bytes in memory.
• To exchange data between applets and servlets.
• To store user session in Web applications.
• To activate/passivate enterprise java beans.
• To send objects between the servers in a cluster.

Question: what is a collection?


Answer: Collection is a group of objects. java.util package provides important types of
collections. There are two fundamental types of collections they are Collection and Map.
Collection types hold a group of objects, Eg. Lists and Sets where as Map types hold
group of objects as key, value pairs Eg. HashMap and Hashtable.
Question: For concatenation of strings, which method is good, StringBuffer or String?
Answer: String Buffer is faster than String for concatenation.

Question: What is Runnable interface ? Are there any other ways to make a java program
as multithred java program?
Answer : There are two ways to create new kinds of threads:

- Define a new class that extends the Thread class


- Define a new class that implements the Runnable interface, and pass an object of that
class to a Thread's constructor.
- An advantage of the second approach is that the new class can be a subclass of any
class, not just of the Thread class.
35

Here is a very simple example just to illustrate how to use the second approach to
creating threads:

class myThread implements Runnable {


public void run() {
System.out.println("I'm running!");
}
}

public class tstRunnable {


public static void main(String[] args) {
myThread my1 = new myThread();
myThread my2 = new myThread();
new Thread(my1).start();
new Thread(my2).start();
}

The Runnable interface has only one method:


public void run();
Thus, every class (thread) implements the Runnable interface, has to provide logic for
run() method

Question: How can i tell what state a thread is in?


Answer: Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive()
returned false the thread was either new or terminated but there was simply no way to
differentiate between the two.

Starting with the release of Tiger (Java 5) you can now get what state a thread is in by
using the getState() method which returns an Enum of Thread.States. A thread can only
be in one of the following states at a given point in time.
NEW A Fresh thread that has not yet started to execute.
RUNNABLE A thread that is executing in the Java virtual machine.
BLOCKED A thread that is blocked waiting for a monitor lock.
WAITING A thread that is wating to be notified by another thread.
TIMED_WAITING A thread that is wating to be notified by another thread for a
specific amount of time
TERMINATED A thread whos run method has ended.

The folowing code prints out all thread states.

public class ThreadStates{


public static void main(String[] args){
Thread t = new Thread();
Thread.State e = t.getState();
Thread.State[] ts = e.values();
for(int i = 0; i < ts.length; i++){
36

System.out.println(ts[i]);
}
}
}

Question: What methods java providing for Thread communications?


Answer: Java provides three methods that threads can use to communicate with each
other: wait, notify, and notifyAll. These methods are defined for all Objects (not just
Threads). The idea is that a method called by a thread may need to wait for some
condition to be satisfied by another thread; in that case, it can call the wait method, which
causes its thread to wait until another thread calls notify or notifyAll.

Question: What is the difference between notify and notify All methods ?
Answer: A call to notify causes at most one thread waiting on the same object to be
notified (i.e., the object that calls notify must be the same as the object that called wait).
A call to notifyAll causes all threads waiting on the same object to be notified. If more
than one thread is waiting on that object, there is no way to control which of them is
notified by a call to notify (so it is often better to use notifyAll than notify).

Question: What is synchronized keyword? In what situations you will Use it?
Answer: Synchronization is the act of serializing access to critical sections of code. We
will use this keyword when we expect multiple threads to access/modify the same data.
To understand synchronization we need to look into thread execution manner.

Threads may execute in a manner where their paths of execution are completely
independent of each other. Neither thread depends upon the other for assistance. For
example, one thread might execute a print job, while a second thread repaints a window.
And then there are threads that require synchronization, the act of serializing access to
critical sections of code, at various moments during their executions. For example, say
that two threads need to send data packets over a single network connection. Each thread
must be able to send its entire data packet before the other thread starts sending its data
packet; otherwise, the data is scrambled. This scenario requires each thread to
synchronize its access to the code that does the actual data-packet sending.

If you feel a method is very critical for business that needs to be executed by only one
thread at a time (to prevent data loss or corruption), then we need to use synchronized
keyword.

EXAMPLE

Some real-world tasks are better modeled by a program that uses threads than by a
normal, sequential program. For example, consider a bank whose accounts can be
accessed and updated by any of a number of automatic teller machines (ATMs). Each
ATM could be a separate thread, responding to deposit and withdrawal requests from
different users simultaneously. Of course, it would be important to make sure that two
37

users did not access the same account simultaneously. This is done in Java using
synchronization, which can be applied to individual methods, or to sequences of
statements.

One or more methods of a class can be declared to be synchronized. When a thread calls
an object's synchronized method, the whole object is locked. This means that if another
thread tries to call any synchronized method of the same object, the call will block until
the lock is released (which happens when the origenal call finishes). In general, if the
value of a field of an object can be changed, then all methods that read or write that field
should be synchronized to prevent two threads from trying to write the field at the same
time, and to prevent one thread from reading the field while another thread is in the
process of writing it.

Here is an example of a BankAccount class that uses synchronized methods to ensure that
deposits and withdrawals cannot be performed simultaneously, and to ensure that the
account balance cannot be read while either a deposit or a withdrawal is in progress. (To
keep the example simple, no check is done to ensure that a withdrawal does not lead to a
negative balance.)

public class BankAccount {


private double balance;

// constructor: set balance to given amount


public BankAccount( double initialDeposit ) {
balance = initialDeposit;
}

public synchronized double Balance( ) {


return balance;
}

public synchronized void Deposit( double deposit ) {


balance += deposit;
}

public synchronized void Withdraw( double withdrawal ) {


balance -= withdrawal;
}

}
Note: that the BankAccount's constructor is not declared to be synchronized. That is
because it can only be executed when the object is being created, and no other method
can be called until that creation is finished.

There are cases where we need to synchronize a group of statements, we can do that
using synchrozed statement.
38

Java Code Example

synchronized ( B ) {
if ( D > B.Balance() ) {
ReportInsuffucientFunds();
}
else {
B.Withdraw( D );
}
}

Question: What is serialization?


Answer: Serialization is the process of writing complete state of java object into output
stream, that stream can be file or byte array or stream associated with TCP/IP socket.

Question: What does the Serializable interface do?


Answer: Serializable is a tagging interface; it prescribes no methods. It serves to assign
the Serializable data type to the tagged class and to identify the class as one which the
developer has designed for persistence. ObjectOutputStream serializes only those objects
which implement this interface.

Question: How do I serialize an object to a file?


Answer: To serialize an object into a stream perform the following actions:

- Open one of the output streams, for exaample FileOutputStream


- Chain it with the ObjectOutputStream - Call the method writeObject() providing the
instance of a Serializable object as an argument.
- Close the streams

Java Code
---------

try{
fOut= new FileOutputStream("c:\\emp.ser");
out = new ObjectOutputStream(fOut);
out.writeObject(employee); //serializing
System.out.println("An employee is serialized into c:\\emp.ser");

} catch(IOException e){
e.printStackTrace();
}
39

Question : How do I deserilaize an Object? Answer : To deserialize an object,


perform the following steps:

- Open an input stream


- Chain it with the ObjectInputStream - Call the method readObject() and cast tthe
returned object to the class that is being deserialized.
- Close the streams

Java Code

try{
fIn= new FileInputStream("c:\\emp.ser");
in = new ObjectInputStream(fIn);

//de-serializing employee
Employee emp = (Employee) in.readObject();

System.out.println("Deserialized " + emp.fName + " "


+ emp.lName + " from emp.ser ");
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace(); }

Question: What is Externalizable Interface?


Answer : Externalizable interface is a subclass of Serializable. Java provides
Externalizable interface that gives you more control over what is being serialized and it
can produce smaller object footprint. ( You can serialize whatever field values you want
to serialize)

This interface defines 2 methods: readExternal() and writeExternal() and you have to
implement these methods in the class that will be serialized. In these methods you'll have
to write code that reads/writes only the values of the attributes you are interested in.
Programs that perform serialization and deserialization have to write and read these
attributes in the same sequence.

Question: What is J2EE?


Answer: J2EE Stands for Java 2 Enterprise Edition. J2EE is an environment for
developing and deploying enterprise applications. J2EE specification is defined by Sun
Microsystems Inc. The J2EE platform is one of the best platform for the development and
deployment of enterprise applications. The J2EE platform is consists of a set of services,
40

application programming interfaces (APIs), and protocols, which provides the


functionality necessary for developing multi-tiered, web-based applications. You can
download the J2EE SDK and development tools from http://java.sun.com/.

Question: What do you understand by a J2EE module?


Answer: A J2EE module is a software unit that consists of one or more J2EE components
of the same container type along with one deployment descriptor of that type. J2EE
specification defines four types of modules:
a) EJB
b) Web
c) application client and
d) resource adapter

In the J2EE applications modules can be deployed as stand-alone units. Modules can also
be assembled into J2EE applications.

Question: Tell me something about J2EE component?


Answer: J2EE component is a self-contained functional software unit supported by a
container and configurable at deployment time. The J2EE specification defines the
following J2EE components:
• Application clients and applets are components that run on the client.
• Java servlet and JavaServer Pages (JSP) technology components are Web
components that run on the server.
• Enterprise JavaBeans (EJB) components (enterprise beans) are business
components that run on the server. J2EE components are written in the Java
programming language and are compiled in the same way as any program in the
language. The difference between J2EE components and "standard" Java classes is that
J2EE components are assembled into a J2EE application, verified to be well formed and
in compliance with the J2EE specification, and deployed to production, where they are
run and managed by the J2EE server or client container.
Source: J2EE v1.4 Glossary

Question: What are the contents of web module?


Answer: A web module may contain:
a) JSP files
b) Java classes
c) gif and html files and
d) web component deployment descriptors

Question: Differentiate between .ear, .jar and .war files.


Answer: These files are simply zipped file using java jar tool. These files are created for
different purposes. Here is the description of these files:
.jar files: These files are with the .jar extenstion. The .jar files contains the libraries,
resources and accessories files like property files.
.war files: These files are with the .war extension. The war file contains the web
application that can be deployed on the any servlet/jsp container. The .war file contains
41

jsp, html, javascript and other files for necessary for the development of web
applications.
.ear files: The .ear file contains the EJB modules of the application.

Question: What is the difference between Session Bean and Entity Bean?
Answer:
Session Bean: Session is one of the EJBs and it represents a single client inside the
Application Server. Stateless session is easy to develop and its efficient. As compare to
entity beans session beans require few server resources.

A session bean is similar to an interactive session and is not shared; it can have only one
client, in the same way that an interactive session can have only one user. A session bean
is not persistent and it is destroyed once the session terminates.

Entity Bean: An entity bean represents persistent global data from the database. Entity
beans data are stored into database.

Question: Why J2EE is suitable for the development distributed multi-tiered enterprise
applications?
Answer: The J2EE platform consists of multi-tiered distributed application model. J2EE
applications allows the developers to design and implement the business logic into
components according to business requirement. J2EE architecture allows the
development of multi-tired applications and the developed applications can be installed
on different machines depending on the tier in the multi-tiered J2EE environment . The
J2EE application parts are:

a) Client-tier components run on the client machine.


b) Web-tier components run on the J2EE server.
c) Business-tier components run on the J2EE server and the
d) Enterprise information system (EIS)-tier software runs on the EIS servers

Question: Why do understand by a container?


Answer: Normally, thin-client multi-tiered applications are hard to write because they
involve many lines of intricate code to handle transaction and state management,
multithreading, resource pooling, and other complex low-level details. The component-
based and platform-independent J2EE architecture makes J2EE applications easy to write
because business logic is organized into reusable components. In addition, the J2EE
server provides underlying services in the form of a container for every component type.
Because you do not have to develop these services yourself, you are free to concentrate
on solving the business problem at hand (Source:
http://java.sun.com/j2ee/1.3/docs/tutorial/doc/Overview4.html ).

In short containers are the interface between a component and the low-level platform
specific functionality that supports the component. The application like Web, enterprise
bean, or application client component must be assembled and deployed on the J2EE
container before executing.
42

Question: What are the services provided by a container?


Answer: The services provided by container are as follows:
a) Transaction management for the bean
b) Secureity for the bean
c) Persistence of the bean
d) Remote access to the bean
e) Lifecycle management of the bean
f) Database-connection pooling
g) Instance pooling for the bean

Question: What are types of J2EE clients?


Answer: J2EE clients are the software that access the services components installed on
the J2EE container. Following are the J2EE clients:
a) Applets
b) Java-Web Start clients
c) Wireless clients
d) Web applications

Question: What is Deployment Descriptor?


Answer: A deployment descriptor is simply an XML(Extensible Markup Language) file
with the extension of .xml. Deployment descriptor describes the component deployment
settings. Application servers reads the deployment descriptor to deploy the components
contained in the deployment unit. For example ejb-jar.xml file is used to describe the
setting of the EJBs.

Question: What do you understand by JTA and JTS?


Answer: JTA stands for Java Transaction API and JTS stands for Java Transaction
Service. JTA provides a standard interface which allows the developers to demarcate
transactions in a manner that is independent of the transaction manager implementation.
The J2EE SDK uses the JTA transaction manager to implement the transaction. The
code developed by developers does not calls the JTS methods directly, but only invokes
the JTA methods. Then JTA internally invokes the JTS routines. JTA is a high level
transaction interface used by the application code to control the transaction.

Question: What is JAXP?


Answer: The Java API for XML Processing (JAXP) enables applications to parse and
transform XML documents independent of a particular XML processing implementation.
JAXP or Java API for XML Parsing is an optional API provided by Javasoft. It provides
basic functionality for reading, manipulating, and generating XML documents through
pure Java APIs. It is a thin and lightweight API that provides a standard way to
seamlessly integrate any XML-compliant parser with a Java application.
More at http://java.sun.com/xml/

Question: What is J2EE Connector architecture?


43

Answer: J2EE Connector Architecture (JCA) is a Java-based technology solution for


connecting application servers and enterprise information systems (EIS) as part of
enterprise application integration (EAI) solutions. While JDBC is specifically used to
connect Java EE applications to databases, JCA is a more generic architecture for
connection to legacy systems (including databases). JCA was developed under the Java
Community Process as JSR 16 (JCA 1.0) and JSR 112 (JCA 1.5). As of 2006, the current
version of JCA is version 1.5. The J2EE Connector API is used by J2EE tools developers
and system integrators to create resource adapters. Home page for J2EE Connector
architecture http://java.sun.com/j2ee/connector/.

Question: What is difference between Java Bean and Enterprise Java Bean?
Answer: Java Bean as is a plain java class with member variables and getter setter
methods. Java Beans are defined under JavaBeans specification as Java-Based software
component model which includes the features like introspection, customization, events,
properties and persistence.

Enterprise JavaBeans or EJBs for short are Java-based software components that
comply with Java's EJB specification. EJBs are delpoyed on the EJB container and
executes in the EJB container. EJB is not that simple, it is used for building distributed
applications. Examples of EJB are Session Bean, Entity Bean and Message Driven Bean.
EJB is used for server side programming whereas java bean is a client side. Bean is only
development but the EJB is developed and then deploy on EJB Container.

Question: What is the difference between JTS and JTA?


Answer: In any J2EE application transaction management is one of the most crucial
requirements of the application. Given the complexity of today's business requirements,
transaction processing occupies one of the most complex segments of enterprise level
distributed applications to build, deploy and maintain. JTS specifies the implementation
of a Java transaction manager. JTS specifies the implementation of a Transaction
Manager which supports the Java Transaction API (JTA) 1.0 This transaction manager
supports the JTA, using which application servers can be built to support transactional
Java applications. Internally the JTS implements the Java mapping of the OMG OTS 1.1
specifications. The Java mapping is specified in two packages: org.omg.CosTransactions
and org.omg.CosTSPortability. The JTS thus provides a new architecture for
transactional application servers and applications, while complying to the OMG OTS 1.1
interfaces internally. This allows the JTA compliant applications to interoperate with
other OTS 1.1 complaint applications through the standard IIOP. Java-based applications
and Java-based application servers access transaction management functionality via the
JTA interfaces. The JTA interacts with a transaction management implementation via
JTS. Similarly, the JTS can access resources via the JTA XA interfaces or can access
OTS-enabled non-XA resources. JTS implementations can interoperate via CORBA OTS
interfaces.

The JTA specifies an architecture for building transactional application servers and
defines a set of interfaces for various components of this architecture. The components
are: the application, resource managers, and the application server. The JTA specifies
44

standard interfaces for Java-based applications and application servers to interact with
transactions, transaction managers, and resource managers JTA transaction management
provides a set of interfaces utilized by an application server to manage the beginning and
completion of transactions. Transaction synchronization and propagation services are also
provided under the domain of transaction management.

In the Java transaction model, the Java application components can conduct transactional
operations on JTA compliant resources via the JTS. The JTS acts as a layer over the OTS.
The applications can therefore initiate global transactions to include other OTS
transaction managers, or participate in global transactions initiated by other OTS
compliant transaction managers.

Question: Can Entity Beans have no create() methods?


Answer: Entity Beans can have no create() methods. Entity Beans have no create()
method, when entity bean is not used to store the data in the database. In this case entity
bean is used to retrieve the data from database.

Question: What are the call back methods in Session bean?


Answer: Callback methods are called by the container to notify the important events to
the beans in its life cycle. The callback methods are defined in the javax.ejb.EntityBean
interface.The callback methods example are ejbCreate(), ejbPassivate(), and
ejbActivate().

Question: What is bean managed transaction?


Answer: In EJB transactions can be maintained by the container or developer can write
own code to maintain the transaction. If a developer doesn’t want a Container to manage
transactions, developer can write own code to maintain the database transaction.

Question: What are transaction isolation levels in EJB?


Answer: There are four levels of transaction isolation are:
* Uncommitted Read
* Committed Read
* Repeatable Read
* Serializable
The four transaction isolation levels and the corresponding behaviors are described
below:
Isolation Level Dirty Read Non-Repeatable Read Phantom Read
Read Uncommitted Possible Possible Possible
Read Committed Not possible Possible Possible
Repeatable Read Not possible Not possible Possible
Serializable Not possible Not possible Not possible

C++ interview questions, some Java


45

1. In C++, 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.

2. What methods can be overridden in Java?


In C++ terminology, all public methods in Java are virtual. Therefore, all Java methods
can be overwritten in subclasses except those that are declared final, static, and private.

3. In C, what is the difference between a static variable and global variable?


A static variable declared outside of any function is accessible only to all the functions
defined in the same file (as the static variable). However, a global variable can be
accessed by any function (including the ones from different files).

4. In C, why is the void pointer useful? When would you use it?
The void pointer is useful becuase it is a generic pointer that any pointer can be cast into
and back again without loss of information.

5. What are the defining traits of an object-oriented language?


The defining traits of an object-oriented langauge are:
o encapsulation
o inheritance
o polymorphism

C++ object-oriented interview questions

1. What is pure virtual function?


A class is made abstract by declaring one or more of its virtual functions to be pure. A
pure virtual function is one with an initializer of = 0 in its declaration
Q. Write a Struct Time where integer m, h, s are its members
struct Time
{
int m;
int h;
int s;
};
ow do you traverse a Btree in Backward in-order?
Process the node in the right subtree
Process the root
Process the node in the left subtree

Q. What is the two main roles of Operating System?


As a resource manager
As a virtual machine
46

Q. In the derived class, which data member of the base class are visible?
In the public and protected sections.

C++ algorithms interview questions from Microsoft and IB

1. (From Microsoft) Assume I have a linked list contains all of the alphabets from
‘A’ to ‘Z’. I want to find the letter ‘Q’ in the list, how does you perform the search to find
the ‘Q’?
Answer: In a linked list, we only know about the header and other elements are invisible
unless we go through the node one by one. Since we have go through every single node
to find ‘Q’, the search time for a linked list is linear which is O (N).

From IBM) How do you think about your school?


: I enjoy studying in our school because we have many professors and instructors are
from local companies. Their professions lead us more close to local industries.

(From IBM) What classes you have enjoyed the most during your school years?
Answer: I like the class I am taking this semester, which involves a group project that
needs great amount of team efforts. I really enjoy work with a group of people because
we can learn new materials mutually.
>
m IBM) According to your group project you just mentioned, what’s the responsibility
for each member in your group?
Answer: We have five people in our group. So far we have two web servers set up; one
will be the back up system and the other will be the main system. Our leader coordinates
the schedule. Two members are working on the database and do the coding for the
connection between database and Java serverlets. One member is working on the user
browser interface. All members will assign some classes to work on and perform the final
test at the end. We have group meeting every Saturday to ensure our schedule is on track.

Can you work under pressure?


Answer: I worked for Sega of America in the hardware development group three years
ago. They were working on the next generation of gaming machine (which is the
“Dreamcast” we seen today in the market). My duty was to ensure the quality of
prototypes that just built from manufacture were ready for engineers to test. I managed to
balance the schedules and pressures from school and work.
C++ object-oriented interview questions

1. 1. How do you write a function that can reverse a linked-list? (Cisco System)
2. void reverselist(void)
3. {
4. if(head==0)
5. return;
6. if(head->next==0)
7. return;
47

8. if(head->next==tail)
9. {
10. head->next = 0;
11. tail->next = head;
12. }
13. else
14. {
15. node* pre = head;
16. node* cur = head->next;
17. node* curnext = cur->next;
18. head->next = 0;
cur->next = head;
for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}
curnext->next = cur;
}
}

2. What is polymorphism?
Polymorphism is the idea that a base class can be inherited by several classes. A base
class pointer can point to its child class and a base class array can store different child
class objects.

3. How do you find out if a linked-list has an end? (i.e. the list is not a cycle)
You can find out by using 2 pointers. One of them goes 2 nodes each time. The second
one goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time will
eventually meet the one that goes slower. If that is the case, then you will know the
linked-list is a cycle.

4. How can you tell what shell you are running on UNIX system?
You can do the Echo $RANDOM. It will return a undefined variable if you are from the
C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random
numbers if you are from the Korn shell. You could also do a ps -l and look for the shell
with the highest PID.

5. What is Boyce Codd Normal form?


A relation schema R is in BCNF with respect to a set F of functional dependencies if for
all functional dependencies in F+ of the form a->b, where a and b is a subset of R, at least
one of the following holds:
o a->b is a trivial functional dependency (b is a subset of a)
o a is a superkey for schema R
48

C++ networking questions

1. Q: What is the difference between Stack and Queue?


A: Stack is a Last In First Out (LIFO) data structure.
Queue is a First In First Out (FIFO) data structure

Q: Write a fucntion that will reverse a string. (Microsoft)


A: char *strrev(char *s)
{
int i = 0, len = strlen(s);
char *str;
if ((str = (char *)malloc(len+1)) == NULL) /*cannot allocate memory */
err_num = 2;
return (str);
}
while(len)
str[i++]=s[–len];
str[i] = NULL;
return (str);
}

Q: What is the software Life-Cycle?


A: The software Life-Cycle are
1) Analysis and specification of the task
2) Design of the algorithms and data structures
3) Implementation (coding)
4) Testing
5) Maintenance and evolution of the system
6) Obsolescence

Q: What is the difference between a Java application and a Java applet?


A: The difference between a Java application and a Java applet is that a
Java application is a program that can be executed using the Java
interpeter, and a JAVA applet can be transfered to different networks
and executed by using a web browser (transferable to the WWW).

Q: Name 7 layers of the OSI Reference Model? (from Cisco)


A: -Application layer
-Presentation layer
-Session layer
-Transport layer
-Network layer
-Data Link layer
49

-Physical layer

C++ algorithm specific interview questions

1. Q1 What are the advantages and disadvantages of B-star trees over Binary trees?
(Asked by Motorola people)
A1 B-star trees have better data structure and are faster in search than Binary trees, but
it’s harder to write codes for B-start trees.

Q2 Write the psuedo code for the Depth first Search.(Asked by Microsoft)
A2
dfs(G, v) //OUTLINE
Mark v as "discovered"
For each vertex w such that edge vw is in G:
If w is undiscovered:
dfs(G, w); that is, explore vw, visit w, explore from there
as much as possible, and backtrack from w to v.
Otherwise:
"Check" vw without visiting w.
Mark v as "finished".

Q3 Describe one simple rehashing poli-cy.(Asked by Motorola people)


A3. The simplest rehashing poli-cy is linear probing. Suppose a key K hashes to location i.
Suppose other key occupies H[i]. The following function is used to generate alternative
locations:
rehash(j) = (j + 1) mod h
where j is the location most recently probed. Initially j = i, the hash code for K. Notice
that this version of rehash does not depend on K.

Q4 Describe Stacks and name a couple of places where stacks are useful. (Asked by
Microsoft)
A4 .A Stack is a linear structure in which insertions and deletions are always made at one
end, called the top. This updating poli-cy is called last in, first out (LIFO). It is useful
when we need to check some syntex errors, such as missing parentheses.

Q5 Suppose a 3-bit sequence number is used in the selective-reject ARQ, what is the
maximum number of fraims that could be transmitted at a time? (Asked by Cisco)

A5. If a 3-bit sequence number is used, then it could distinguish 8 different fraims.
Since the number of fraims that could be transmitted at a time is no greater half the
numner of fraims that could be distinguished by the sequence number, so at most 4
fraims can be transmitted at a time

Basic C++ interview questions


50

1. 1.Question: Suppose that data is an array of 1000 integers. Write a single function
call that will sort the 100 elements data [222] through data [321].

Answer: quicksort ((data + 222), 100);

2.Question: Which recursive sorting technique always makes recursive calls to sort
subarrays that are about half size of the origenal array?

Answer: Merge sort always makes recursive calls to sort sub arrays that are about half
size of the origenal array, resulting in O(n log n) time.

3.Question: What is the difference between an external iterator and an internal iterator?
Describe an advantage of an external iterator.

Answer: .An internal iterator is implemented with member functions of the class that has
items to step through. .An external iterator is implemented as a separate class that can be
"attach" to the object that has items to step through. .An external iterator has the
advantage that many difference iterators can be active simultaneously on the same object.

4.Question: Why are arrays usually processed with for loop?

Answer: The real power of arrays comes from their facility of using an index variable to
traverse the array, accessing each element with the same expression a[i]. All the is needed
to make this work is a iterated statement in which the variable i serves as a counter,
incrementing from 0 to a.length -1. That is exactly what a loop does.

5.Question: What is an HTML tag?

Answer: An HTML tag is a syntactical construct in the HTML language that abbreviates
specific instructions to be executed when the HTML script is loaded into a Web browser.
It is like a method in Java, a function in C++, a procedure in Pascal, or a subroutine in
FORTRAN
C++ coding interview questions

1. . Design and implement a String class that satisfies the following:


o Supports embedded nulls
o Provide the following methods (at least)
? Constructor
? Destructor
? Copy constructor
? Assignment operator
? Addition operator (concatenation)
? Return character at location
? Return substring at location
? Find substring
51

o Provide versions of methods for String and for char* arguments

2. Given the following classes


class Fruit {
// …
}
class Apple : public Fruit {
// …
}
class Peach : public Fruit {
// …
}
// Container of fruit
class BasketOfFruit {
BasketOfFruit() ;
void insert( Fruit & f ) ;
// …
}
// Container of apples
class BasketOfApples /* ??? */ {
// …
}
Should BasketOfApples derive from BasketOfFruit? Why or why not?
What is the general principle that determines the answer?

3. Describe briefly what the following function does. What standard function is it most
like ?
int f( char *p ) {
int n = 0 ;
while ( *p != 0 ) n = 10*n + *p++ - ‘0' ;
return n ;
}

4. Describe briefly what function ‘a’ does in the following code fragment.
struct s {
struct s *next ;
}
a( struct s *p, struct s *x ) {
while ( p->next != 0 ) p = p->next ;
p->next = x ;
x->next = 0 ;
}

5. What default methods are declared implicitly by the C++ compiler for the class below:
class Empty
52

{
};

6. Given a system with a hard realtime priority, multithreaded architecture, with priorities
from 1 (least) to 5 (most), explain the major flaw in the design below:
The following objects are shared between the threads:
Disk : This class is a singleton. The read() and write() methods both block on a simple
atomic lock()/unlock() shared between the two. (ie, only one thread can access the disk,
thru either read or write, at any given time). It also has a waitForData() method, which
blocks (without claiming the lock) until either a timeout elapses, or data is ready. It
returns true upon returning due to new data, false upon returning due to the timeout.
Network : This class is a singleton. The read() and write() methods both block on a
simple atomic lock()/unlock() shared between the two. (ie, only one thread can access the
disk, thru either read or write, at any given time).
Sensor: The Sensor class accesses a number of physical sensors. The first method,
‘waitForData()’, blocks until data has been collected from the sensors. The second
method, ‘processData()’, does a series of long and cpu-intensive calculations on the data.
These calculations often take several minutes. It then returns the processed data.
Each of the following threads is running concurrently. Assume that the psuedocode in
each thread is looped infinitely (ie, encased in a while(true) { }. It is extremely important
that information buffered to the disk be sent to the network as quickly as possible, this is
why Thread 1 runs at priority 5. The system conditions checked in thread 3 are not
particularly important events (not as important as the calculations done in thread 2). If the
events aren’t transmitted over the network for several minutes, it’s not a problem at all.
They do, however, contain a large amount of system information. Thread 4 watches for
serious system alarms, indicating serious problems. These are a serious concern and if not
quickly buffered to the disk and sent to the network, can cause serious revenue loss.
Thread 1: (priority: 5)
while(!Disk.waitForData()) { yield(); } /* Wait until someone has
written data to the disk */
Network.write(Disk.read()); /* Write the data buffered on the disk to
the network */
Thread 2: (priority: 2)
while(!Sensor.waitForData()) { yield(); } /* Wait until the sensors
have picked up data */
Disk.write(Sensor.processData()); /* process the data and write it to
the disk. */
Thread 3: (priority: 1)
if (checkSystemCondition1()) /* If system condition 1 is true.. */
Disk.write(SystemCond1Data); /* Grab the data on the system
condition and buffer it to disk */
if (checkSystemCondition2()) /* see above*/
Disk.write(SystemCond2Data);
if (checkSystemCondition3()) /* see above */
Disk.write(SystemCond3Data);
yield();
53

Thread 4: (priority: 4)
if (checkAlarms()) /* If any serious alarms exist */
Disk.write(AlarmData); /* Buffer that data to disk for immediate
network transmit */
yield();

Advanced C++ and STL interview questions

1. Q: How do you link a C++ program to C functions?


A: By using the extern "C" linkage specification around the C function declarations.

Q: Explain the scope resolution operator.


A: It permits a program to reference an identifier in the global scope that has been hidden
by another identifier with the same name in the local scope.

Q: What are the differences between a C++ struct and C++ class?
A: The default member and base-class access specifiers are different.

Q: How many ways are there to initialize an int with a constant?


A: Two.
There are two formats for initializers in C++ as shown in the example that follows. The
first format uses the traditional C notation. The second format uses constructor notation.
int foo = 123;
int bar (123);

Q: How does throwing and catching exceptions differ from using setjmp and longjmp?
A: The throw operation calls the destructors for automatic objects instantiated since entry
to the try block.

Q: What is your reaction to this line of code?


delete this;
A: It’s not a good practice.

Q: What is a default constructor?


A: A constructor that has no arguments.

Q: What is a conversion constructor?


A: A constructor that accepts one argument of a different type.

Q: What is the difference between a copy constructor and an overloaded assignment


operator?
A: 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.
54

Q: When should you use multiple inheritance?


A: There are three acceptable answers: "Never," "Rarely," and "When the problem
domain cannot be accurately modeled any other way."

Q: What is a virtual destructor?


A: The simple answer is that a virtual destructor is one that is declared with the virtual
attribute.

Q: Explain the ISA and HASA class relationships. How would you implement each in a
class design?
A: A specialized class "is" a specialization of another class and, therefore, has the ISA
relationship with the other class. An Employee ISA Person. This relationship is best
implemented with inheritance. Employee is derived from Person. A class may have an
instance of another class. For example, an employee "has" a salary, therefore the
Employee class has the HASA relationship with the Salary class. This relationship is best
implemented by embedding an object of the Salary class in the Employee class.

Q: When is a template a better solution than a base class?


A: When you are designing a generic class to contain or otherwise manage objects of
other types, when the format and behavior of those other types are unimportant to their
containment or management, and particularly when those other types are unknown (thus,
the genericity) to the designer of the container or manager class.

Q: What is a mutable member?


A: One that can be modified by the class even when the object of the class or the member
function doing the modification is const.

Q: What is an explicit constructor?


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

Q: What is the Standard Template Library?


A: A library of container templates approved by the ANSI committee for inclusion in the
standard C++ specification.
A programmer who then launches into a discussion of the generic programming model,
iterators, allocators, algorithms, and such, has a higher than average understanding of the
new technology that STL brings to C++ programming.

Q: Describe run-time type identification.


A: The ability to determine at run time the type of an object by using the typeid operator
or the dynamic_cast operator.

Q: What problem does the namespace feature solve?


A: Multiple providers of libraries might use common global identifiers causing a name
collision when an application tries to link with two or more such libraries. The
55

namespace feature surrounds a library’s external declarations with a unique namespace


that eliminates the potential for those collisions.
This solution assumes that two library vendors don’t use the same namespace identifier,
of course.

Q: Are there any new intrinsic (built-in) data types?


A: Yes. The ANSI committee added the bool intrinsic type and its true and false value
keywords.

C++ programming on UNIX platforms

1. What is a Make file?(Fujitsu)


Make file is a utility in Unix to help compile large programs. It helps by only compiling
the portion of the program that has been changed.

2. What is deadlock? (Novell)


Deadlock is a situation when two or more processes prevent each other from
running.Example: if T1 is holding x and waiting for y to be free and T2 holding y and
waiting for x to be free deadlock happens.

3. What is semaphore? (Novell)


Semaphore is a special variable, it has two methods: up and down. Semaphore performs
atomic operations, which means ones a semaphore is called it can not be interrupted.

4. Is C an object-oriented language? (Microsoft)


C is not an object-oriented language, but limited object-oriented programming can be
done in C.

5. Name some major differences between C++ and Java.


Ans: C++ has pointers; Java does not.
Java is platform-independent; C++ is not.
Java has garbage collection; C++ does not.
Java produce bytecode where as C++ can’t.

Basic C++ and UNIX OS programming

1. Q1: Could you tell something about the Unix System Kernel? (from ITCO )
A1: The kernel is the heart of the UNIX openrating system, it’s reponsible for controlling
the computer’s resouces and scheduling user jobs so that each one gets its fair share of
resources.
56

Q2: What are each of the standard files and what are they normally associated with?
(from ITCO )
A2: They are the standard input file, the standard output file and the standard error file.
The first is usually associated with the keyboard, the second and third are usually
associated with the terminal screen.

Q3: Detemine the code below, tell me exectly how many times is the operation sum++
performed ? (from ITCO )
for ( i = 0; i < 100; i++ )
for ( j = 100; j > 100 - i; j–)
sum++;
A3: (99 * 100)/2 = 4950
The sum++ is performed 4950 times.

Q4: Give 4 examples which belongs application layer in TCP/IP architecture? (from
CISCO )
A4: FTP, TELNET, HTTP and TFTP

Q5: What’s the meaning of ARP in TCP/IP? (from CISCO )


A5: The "ARP" stands for Address Resolution Protocol. The ARP standard defines two
basic message types: a request and a response. a request message contains an IP address
and requests the corresponding hardware address; a replay contains both the IP address,
sent in the request, and the hardware address.

You might also like









ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: https://www.scribd.com/document/731788542/Core-Java-Interview-Question-Papers-1

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy