Showing posts with label questions. Show all posts
Showing posts with label questions. Show all posts

APTITUDE QUESTIONS

Saturday, August 6, 2016

guys download c,c++ and java programming aptitued questions and solved......
frequently asked questions in interview fields......

file size:742 kb

click here to download
Read More..

TCS APTITUDE QUESTIONS SOLVED

Saturday, March 12, 2016

guys download this TCS model paper.... it will be usefull for you....
good luck.....


click here to download(270KB)
Read More..

TECHNICAL INTERVIEW QUESTIONS

Sunday, February 7, 2016

friends i have uploaded full version of technical interview questions such as c,c++,java,data structure,os,networks and databases........

file size:750kb

click here to download
Read More..

Java stack data structure interview questions and answers

Saturday, March 15, 2014

The Java Collection library is one of the most frequently used libraries.The LIFO access mechanism used by a stack has many practical uses.  For example, Evaluation of expressions / syntax Parsing, validating and parsing XML, undo sequence in a text editor, pages visited history in a web browser, etc. Here are a few Java based interview questions and answers on a stack.

Q. What LIFO implementation would you use in Java?
A. The Vector based Stack class is a legacy and the Javadoc documentation for this class states that Deque should be used instead because it provides better LIFO operation support. Implementations of Deque are typically expected to perform better than Stack. J2SE 5 introduced a Queue interface and the Deque interface extends this interface. The Deque interface supports should be pronounced "deck" rather than "de-queue" and is not related to dequeue used to indicate removal from a queue. The double-ended queue supports addition or removal of elements from either end of the data structure, so it can be used as a queue (first-in-first-out/FIFO) or as a stack (last-in-first-out/LIFO).

Note:  The legacy Vector class uses internal synchronization, and it is rarely good enough for actual consistency, and can slow down execution when it is not really needed. The new java.util.concurrent package provides a more efficient way of thread-safety.

Q. Can you write a program to evaluate if a given string input has proper closing bracket for every opening bracket?
A. Firstly, think of the pseudo code. The pseudo-code goes as follows.

1. Store every opening parenthesis (i.e. a LHS parenthesis) in a stack. This will enable LIFO.
2. When you encounter a closing parenthesis (i.e. RHS parenthesis ), pop the last entry, which should be the corresponding opening parenthesis.
3. If not found, then the parentheses are not matched.

If required, draw a diagram as shown below.







Here is a sample program to illustrate a Stack (i.e. LIFO) in action in evaluating if a program has balanced parentheses. The enum constants class that defines the parentheses.


public enum PARENTHESIS {

LP((), RP()), LB({), RB(}), LSB([), RSB(]);

char symbol;

PARENTHESIS(Character symbol) {
this.symbol = symbol;
}

char getSymbol() {
return this.symbol;
}
}



Now, the stack in action using its LIFO mechanism to marry a closing parenthesis (i.e RHS) with an opening parenthesis (i.e. LHS). If you find any LHS parenthesis, push it into a stack, and when you find a RHS parenthesis, pop the stack to see if you have a corresponding LHS parenthesis.


import java.util.ArrayDeque;
import java.util.Deque;

public class Evaluate {

//stores the parentheses
final Deque<character> paranthesesStack = new ArrayDeque<character>();

public boolean isBalanced(String s) {

for (int i = 0; i < s.length(); i++) {

if (s.charAt(i) == PARENTHESIS.LP.getSymbol() ||
s.charAt(i) == PARENTHESIS.LB.getSymbol() ||
s.charAt(i) == PARENTHESIS.LSB.getSymbol())

paranthesesStack.push(s.charAt(i)); // auto boxing takes place
// push the opening parentheses

//for each RHS parenthesis check if there is a matching LHS Parenthesis
//if the stack is empty or does not have a matching LHS parenthesis then not balanced.
else if (s.charAt(i) == PARENTHESIS.RP.getSymbol()){
if (paranthesesStack.isEmpty() || paranthesesStack.pop() != PARENTHESIS.LP.getSymbol())
return false;
}

else if (s.charAt(i) == PARENTHESIS.RB.getSymbol() ) {
if (paranthesesStack.isEmpty() || paranthesesStack.pop() !=PARENTHESIS.LB.getSymbol() )
return false;
}

else if (s.charAt(i) == PARENTHESIS.RSB.getSymbol()) {
if (paranthesesStack.isEmpty() || paranthesesStack.pop() != PARENTHESIS.LSB.getSymbol())
return false;
}

}

return paranthesesStack.isEmpty(); //if the stack is empty, then all matched well, otherwise not matched.
}

}


Note: ArrayDeque is not thread-safe and does not allow for elements of the data structure to be null. The concurrent package has BlockingDeque and LinkedBlockingDequeue.

Finally, a simple JUnit class to test. You need to have the junit-xxx.jar in the classpth. The version xxx I used was 4.8.2.

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;


public class EvaluateTest {

Evaluate eval = null;

@Before
public void setUp(){
eval = new Evaluate();
}

@Test
public void testPositiveIsBalanced(){
boolean result = eval.isBalanced("public static void main(String[] args) {}");
Assert.assertTrue(result);

}


@Test
public void testNegativeIsBalanced(){
boolean result = eval.isBalanced("public static void main(String[ args) {}"); // missing ]
Assert.assertFalse(result);

result = eval.isBalanced("public static void main(String[] args) }"); // missing {
Assert.assertFalse(result);


result = eval.isBalanced("public static void main String[] args) {}"); // missing (
Assert.assertFalse(result);

}

}




Tip: When testing, test positive and negative scenarios.

Note: The above example is shown to illustrate how a LIFO mechanism can be used to determine if the parentheses are balanced. The actual implementation is far from being optimum. Where ever there is a large block of if-else or switch statements, one should think about an object oriented solution.

Q. Why Deque interface is different from other collection classes?
A. In Deque, You can insert and delete the objects from the both start and end of the the collection. Whereas in a normal collection, inserts/deletes are happening at last only.


Q. What are the different ways to look at the trace of your program execution?
A.

1. Java is a stack based language, and the program execution is pushed and popped out of a stack. When a method is entered into, it is pushed into a stack, and when that method invokes many other methods, they are pushed into the stack in the order in which they are executed. As each method completes its execution, they are popped out of the stack in the LIFO order. Say methodA( ) invoked methodB( ), and methodB( ) invoked methodC ( ), when execution of methodC( ) is completed, it is popped out first, and then followed by methodB( ) and then methodA( ). When an exception is thrown at any point, a stack trace is printed for you to be able to find where the issue is.




2. A Java developer can access a stack trace at any time. One way to do this is to call


Thread.currentThread().getStackTrace() ; //handy for tracing



You could get a stack trace of all the threads using the Java utilities such as jstack, JConsole or by sending a kill -quit signal (on a Posix operating system) or <ctrl><break> on WIN32 platform to get a thread dump. You could also use the JMX API as shown below. ThreadMXBean is the management interface for the thread system of the JVM.

ThreadMXBean bean = ManagementFactory.getThreadMXBean();
ThreadInfo[] infos = bean.dumpAllThreads(true, true);
for (ThreadInfo info : infos) {
StackTraceElement[] elems = info.getStackTrace();
//...do something
}


The thread dumps are very useful in identifying concurrency issues like dead locks, contention issues, thread starvation, etc.


Q. Is recursive method calls possible in Java?
A. Yes. Java is stack based and because of its LIFO (Last In First Out) property, it remembers its caller. So it knows whom to return when the method has to return.


Q. How would you go about analyzing stack traces correctly?
A.

1. One of the most important concepts of correctly understanding a stack trace is to recognize that it lists the execution path in reverse chronological order from most recent operation to earliest operation. That is, it is LIFO.

2. The stack trace below is simple and it tells you that the root cause is a NullPointerException on ClassC line 16. So you look at the top most class.

Exception in thread "main" java.lang.NullPointerException
at com.myapp.ClassC.methodC(ClassC.java:16)
at com.myapp.ClassB.methodB(ClassB.java:25)
at com.myapp.ClassA.main(ClassA.java:14)



3. The stack trace can get more complex with multiple "caused by" clauses, and in this case you usually look at the bottom most "caused by". For example,

Exception in thread "main" java.lang.IllegalStateException: ClassC has a null property
at com.myapp.ClassC.methodC(ClassC.java:16)
at com.myapp.ClassB.methodB(ClassB.java:25)
at com.myapp.ClassA.main(ClassA.java:14)
Caused by: com.myapp.MyAppValidationException
at com.myapp.ClassB.methodB(ClassB.java:25)
at com.myapp.ClassC.methodC(ClassC.java:16)
... 1 more
Caused by: java.lang.NullPointerException
at com.myapp.ClassC.methodC(ClassC.java:16)
... 1 more


The root cause is the last "caused by", which is a NullPointerException on ClassC line 16


4. When you use plethora of third-party libraries like Spring, Hibernate, etc, your stack traces "caused by" can really grow and you need to look at the bottom most "caused by" that has the package relevant to you application like com.myapp.ClassC and skip library specific ones like org.hibernate.exception.*.

Q. Can you reverse the following numbers {1, 4, 6, 7, 8, 9}?
A. There are a number of ways to achieve this. Speaking of LIFO, the following example illustrates using a stack based implementation.


import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;


public class ReverseNumbers {

public static void main(String[] args) {
Integer[] values = {1, 4, 6, 7, 8, 9};
Deque<integer> numberStack = new ArrayDeque<integer>(10);

for (int i = 0; i < values.length; i++) {
numberStack.push(values[i]); // push the numbers in given order
}

Integer[] valuesReversed = new Integer[values.length];

int i = 0;
while (!numberStack.isEmpty()) {
valuesReversed[i++] = numberStack.pop(); // pop it - as this happens in reverse order
// i++ is a post increment i.e.
// assign it and then increment it
// for the next round
}

System.out.println(Arrays.deepToString(valuesReversed));

}
}



The output will be


[9, 8, 7, 6, 4, 1]

Read More..

Java and Enterprise Java Interview Questions

Wednesday, February 26, 2014

Here are some frequently asked Java and J2EE Interview Questions with hints. You must at least be prepared with these most popular Java and J2EE interview questions.

Multi-threading  Interview Questions
  • What language features are available to allow shared access to data in a multi-threading environment? (Hint: Synchronized block,Synchronized method,wait, notify)
  • What is the difference between synchronized method and synchronized block?
    (Hint:Block on subset of data. Smaller code segment).
  • What Java language features would you use to implement a producer (one thread) and a consumer (another thread) passing data via a stack? (Hint: wait, notify)

Java language Interview Questions
  • What Java classes are provided for date manipulation? (Hint:Calendar, Date)
  • What is the difference between String and StringBuffer? (Hint: mutable, efficient)
  • How do you ensure a class is Serializable? (Hint:Implement Serializable)
  • What is the difference between static and instance field of a class? (Hint:Per class vs. Per Object)
  • What methods do you need to implement to store a class in Hashtable or HashMap? (Hint: hashCode(), equals()) .
  • How do you exclude a field of a class from serialization? (Hint: transient)



Inheritance Interview Questions
  • What is the difference between an Interface and an abstract base class? (Hint: interface inheritance, implementation inheritance.) What about overloading? (Hint: different signature)
  • What does overriding a method mean? (Hint: Inheritance)

Java Memory Management Interview Questions
  • What is the Java heap, and what is the stack? (Hint: dynamic, program thread execution.)
    Why does garbage collection occur and when can it occur? (Hint: To recover memory, as heap gets full.)
  • If I have a circular reference of objects, but I no longer reference any of them from any executing thread, will these cause garbage collection problems? (Hint: no)

Java Exceptions Handling Interview Questions  
  • What is the difference between a runtime exception and a checked exception? (Hint: Must catch or throw checked exceptions.)
  • What is the problem or benefit of catching or throwing type “java.lang.Exception”? (Hint: Hides all subsequent exceptions.)




Web components

JSP Interview Questions
  • What is the best practice regarding the use of scriptlets in JSP pages? Why? (Hint: Avoid)How can you avoid scriptlet code? (Hint:custom tags, Java beans)
  • What do you understand by the term JSP compilation? (Hint: compiles to servlet code)
Servlets Interview Questions
  • What does Servlet API provide to store user data between requests? (Hint: HttpSession)
  • What is the difference between forwarding a request and redirecting? (Hint: redirect return to browser )
  • What object do you use to forward a request? (Hint: RequestDispatcher)
  • What do you need to be concerned about with storing data in a servlet instance fields? (Hint: Multi-threaded.)
  • What’s the requirement on data stored in HttpSession in a clustered (distributable) environment? (Hint: Serializable)
  • If I store an object in session, then change its state, is the state replicated to distributed Session? (Hint: No, only on setAttribute() call.)
    How does URL-pattern for servlet work in the web.xml? (Hint: /ddd/* or *.jsp)
  • What is a filter, and how does it work? (Hint: Before/after request, chain.)

Enterprise Java

JDBC Interview Questions
  • What form of statement would you use to include user-supplied values? (Hint: PreparedStatement)
  • Why might a preparedStatement be more efficient than a statement? (Hint: Execution plan cache.)
  • How would you prevent an SQL injection attack in JDBC? (Hint: PreparsedStatement )
  • What is the performance impact of testing against NULL in WHERE clause on Oracle? (Hint: Full table scan. )
  • List advantages and disadvantages in using stored procedures? (Hint: Pro: integration with existing dbase, reduced network trafficCon: not portable, mutliple language knowledge required )
  • What is the difference between sql.Date, sql.Time, and sql.Timestamp? (Hint: Date only, time only, date and time )
  • If you had a missing int value how do you indicate this to PreparedStatement? (Hint: setNull(pos, TYPE))
  • How can I perform multiple inserts in one database interaction? (Hint: executeBatch)Given this problem: Program reads 100,000 rows, converts to Java class in list, then converts list to XML file using reflection. Runs out of program memory. How would you fix? (Hint: Read one row at time, limit select, allocate more heap (result set = cursor) )
  • How might you model object inheritance in database tables? (Hint: Table per hierarchy, table per class, table per concrete class)
JNDI Interview Questions
  • What are typical uses for the JNDI API within an enterprise application? (Hint: Resource management, LDAP access)
  • Explain the difference between a lookup of these “java:comp/env/ejb/MyBean” and “ejb/MyBean”? (Hint: logical mapping performed for java:comp/env )
  • What is the difference between new InitialContext() from servlet or from an EJB? (Hint: Different JNDI environments initialized EJB controller by ejb-jar.xml, servlet by web.xml.)
  • What is an LDAP server used for in an enterprise environment? (Hint: authentication, authorization)
  • What is authentication, and authorization? (Hint: Confirming identity, confirming access rights )
EJB Interview Questions

  • What is meant by a coarse-grained and a fine-grained interface? (Hint: Amount of data transferred per method call)
  • What is the difference between Stateless and Stateful session beans (used?) (Hint: Stateful holds per client state )
  • What is the difference between Session bean and Entity bean (when used?) (Hint: Entity used for persistence )
    With Stateless Session bean pooling, when would a container typically take a instance from the pool and when would it return it? (Hint: for each business method )
  • What is the difference between “Required”, “Supports”, “RequiresNew” “NotSupported”, “Mandatory”, “Never”? (Hint: Needs transaction, existing OK but doesn’t need, must start new one, suspends transaction, must already be started, error if transaction)
  • What is “pass-by-reference” and “pass-by-value”, and how does it affect J2EE applications? (Hint: Reference to actual object versus copy of object. RMI pass by value.)
    What EJB patterns, best practices are you aware of? Describe at least two? (Hint: Façade, delegate, value list, DAO, value object).
  • Describe some issues/concerns you have with the J2EE specification? (Hint: Get their general opinion of J2EE)
    What do you understand by the term “offline optimistic locking” or long-lived business transaction? How might you implement this using EJB? (Hint: version number, date, field comparisons.)
  • Explain performance difference between getting a list of summary information (e.g. customer list) via finder using a BMP entity vs. Session using DAO? (Hint: BMP: n+1 database reads, n RMI calls.)

XML/XSLT Interview Questions
  • What is the difference between a DOM parser and a SAX parser? (Hint: DOM: reads entire model, SAX: event published during parsing.)
  • What is the difference between DTD and XML Schema? (Hint: level of detail, Schema is in XML.)
  • What does the JAXP API do for you? (Hint: Parser independence. )What is XSLT and how can it be used? (Hint: XML transformation. )
  • What would be the XPath to select any element called table with the class attribute of info? (Hint: Table[@class=’info’])

JMS Interview Questions
  • How can asynchronous events be managed in J2EE? (Hint: JMS)
  • How do transactions affect the onMessage() handling of a MDB? (Hint: Taking off queue. )
  • If you send a JMS message from an EJB, and transaction rollback, will message be sent? (Hint: yes)
  • How do you indicate what topic or queue MDB should react to? (Hint: deployment descriptor )
  • What is the difference between a topic and a queue? (Hint: broadcast, single)

SOAP Interview Questions
  • What is a Web service, and how does it relate to SOAP? (Hint: SOAP is the protocol.)
  • What is a common transport for SOAP messages? (Hint: HTTP )
  • What is WSDL? How would you use a WSDL file? (Hint: XML description of Web Service: interface and how to bind to it. )
  • With new J2EE SOAP support what is: JAXR, JAX-RPC, and SAAJ? (Hint: registry, rpc, attachments)
Java Security Interview Questions

  • Where can container level security be applied in J2EE application? (Hint: Web Uri’s, EJB methods)
  • How can the current user be obtained in a J2EE application (Web and Enterprise)? (Hint: getUserPrincipal, getCallerPrincipal
  • How can you perform role checks in a J2EE application (Web and enterprise)? (Hint: IsUserInRole(), IsCallerInRole() )


Design Interview Questions
  • Name some types of UML diagrams? (Hint: class, sequence, activity, use case)
  • Describe some types of relationships can you show on class diagrams? (Hint: generalization, aggregation, uses)
  • What is the difference between association, aggregation, and generalization? (Hint: Relationship, ownership, inheritance)
  • What is a sequence diagram used to display? ( Hint: Object instance interactions via operations/signals)What design patterns do you use. Describe one you have used (not singleton)? (Hint: e.g. Builder, Factory, Visitor, Chain of Command )
  • Describe the observer pattern and an example of how it would be used (Hint: e.g. event notification when model changes to view )
  • What are Use Cases? (Hint: Define interaction between actors and the system )What is your understanding of encapsulation? (Hint: Encapsulate data and behavior within class )
  • What is your understanding of polymorphism? (Hint: Class hierarchy, runtime determine instance )
Development Process Interview Questions
  • Have you heard of or used test-driven development? (Hint: e.g. XP process )
  • What development processes have you followed in the past? (Hint: Rational, XP, waterfall )
  • How do you approach capturing client requirements? (Hint: Numbered requirements, use cases )
  • What process steps would you include between the capture of requirements and when coding begins? (Hint: Architecture, Design, UML modeling, etc )
  • How would you go about solving performance issue in an application? (Hint: Set goals, establish bench, profile application, make changes one at a time )
  • What developer based testing are you familiar with (before system testing?) (Hint: Unit test discussion )
  • How might you test a business system exposed via a Web interface? (Hint: Automated script emulating browser)
  • What is your experience with iterative development? (Hint: Multiple iteration before release)

Distributed Application Interview Questions
  • Explain a typical architecture of a business system exposed via Web interface? (Hint: Explain tiers (presentation, enterprise, resource) Java technology used in each tiers, hardware distribution of Web servers, application server, database server )
  • Describe what tiers you might use in a typical large scale (> 200 concurrent users) application and the responsibilities of each tier (where would validation, presentation, business logic, persistence occur). (Hint: Another way of asking same question as above if their answer wasn’t specific enough)
  • Describe what you understand by being able to “scale” an application? How does a J2EE environment aid scaling? (Hint: Vertical and Horizontal scaling. Thread management, clustering, split tiers )
  • What are some security issues in Internet based applications? (Hint: authentication, authorization, data encryption, denial service, xss attacks, SQL injection attacks )
General Interview Questions
  • What configuration management are you familiar with? (Hint: e.g. CVS, ClearCase )
  • What issue/tracking process have you followed? (Hint: Want details on bug recording and resolution process).
  • What are some key factors to working well within a team? (Hint: Gets a view on how you would work within interviewer’s environment.)
  • What attributes do you assess when considering a new job? (what makes it a good one)? (Hint: Insight into what motivates you.)
  • What was the last computing magazine you read? Last computing book?
  • What is a regular online magazine/reference you use? (Hint: Understand how up to date you keep yourself.)

Note: You will find answers to all of the above questions in the 400+ Java/J2EE Interview Questions and Answers companion book.

Read More..