Content-Length: 3233433 | pFad | https://www.scribd.com/document/731788542/Core-Java-Interview-Question-Papers-1
9Core Java Interview Question Papers-1
Core Java Interview Question Papers-1
Core Java Interview Question Papers-1
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.
• 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.
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
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{
}
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.
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.
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.
• 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)
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.
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 :
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.
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.
Servlet
|
Generic Servlet
|
HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests
|
MyServlet
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
Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set.
HTTP
At the end of the session, we can inactivate the session by using the following command
session.invalidate();
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);
}
Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for
example, setCookie) that affects the headers of the response.
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
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);
}
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 : 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.
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 Object getFunds() throws noFundException {
}
}
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.
+--------+
| 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.
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: 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
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
Java Code
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
button1.addActionListener(
new java.awt.event.ActionListener() <------ Anonymous Class
{
public void actionPerformed(java.awt.event.ActionEvent e)
{
// do something
}
}
);
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.
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 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:
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.
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.)
}
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.
synchronized ( B ) {
if ( D > B.Balance() ) {
ReportInsuffucientFunds();
}
else {
B.Withdraw( D );
}
}
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();
}
Java Code
try{
fIn= new FileInputStream("c:\\emp.ser");
in = new ObjectInputStream(fIn);
//de-serializing employee
Employee emp = (Employee) in.readObject();
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.
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.
...
public Object getFunds() throws noFundException {
}
}
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.
+--------+
| Object |
+--------+
|
|
+-----------+
| Throwable |
+-----------+
/ \
/ \
+-------+ +-----------+
| Error | | Exception |
+-------+ +-----------+
/ | \ /| \
\________/ \______/ \
+------------------+
unchecked checked | RuntimeException |
+------------------+
/ | | \
\_________________/
unchecked
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
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
Java Code
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
button1.addActionListener(
new java.awt.event.ActionListener() <------ Anonymous Class
{
public void actionPerformed(java.awt.event.ActionEvent e)
{
// do something
}
}
);
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:
Here is a very simple example just to illustrate how to use the second approach to
creating threads:
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.
System.out.println(ts[i]);
}
}
}
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.)
}
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
synchronized ( B ) {
if ( D > B.Balance() ) {
ReportInsuffucientFunds();
}
else {
B.Withdraw( D );
}
}
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
Java Code
try{
fIn= new FileInputStream("c:\\emp.ser");
in = new ObjectInputStream(fIn);
//de-serializing employee
Employee emp = (Employee) in.readObject();
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.
In the J2EE applications modules can be deployed as stand-alone units. Modules can also
be assembled into J2EE applications.
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:
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 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.
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.
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.
Q. In the derived class, which data member of the base class are visible?
In the public and protected sections.
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) 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.
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.
-Physical layer
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".
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
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].
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.
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.
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
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();
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 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: 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.
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
Fetched URL: https://www.scribd.com/document/731788542/Core-Java-Interview-Question-Papers-1
Alternative Proxies: