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

Saturday, July 6, 2019

How to prepare for a java developer before the interview

In this post you will know the best way to prepare for a java developer one day before. The following concepts you must be confident in:


  • OOPS
  • Basic programming(sorting,searching etc..)
  • Exception handling
  • Multi threading
  • system design
  • jvm
  • collections



some of the frequently asked interview questions are as follows:


  1. ArrayList, LinkedList, and Vector are all implementations of the List interface. Which of them is most efficient for adding and removing elements from the list? Explain your answer, including any other alternatives you may be aware of.
  2. Why would it be more secure to store sensitive data (such as a password, social security number, etc.) in a character array rather than in a String?
  3. What is the ThreadLocal class? How and why would you use it?
  4. What is the volatile keyword? How and why would you use it?
  5. Compare the sleep() and wait() methods in Java, including when and why you would use one vs. the other.
  6. Tail recursion is functionally equivalent to iteration. Since Java does not yet support tail call optimization, describe how to transform a simple tail recursive function into a loop and why one is typically preferred over the other.
  7. How can you catch an exception thrown by another thread in Java?
  8. What is the Java Classloader? List and explain the purpose of the three types of class loaders.
  9. When designing an abstract class, why should you avoid calling abstract methods inside its constructor?
  10. What variance is imposed on generic type parameters? How much control does Java give you over this?
  11. If one needs a Set, how do you choose between HashSet vs. TreeSet?
  12. What are method references, and how are they useful?
  13. How are Java enums more powerful than integer constants? How can this capability be used?
  14. What does it mean for a collection to be “backed by” another? Give an example of when this property is useful.
  15. What is reflection? Give an example of functionality that can only be implemented using reflection.
  16. What are static initializers and when would you use them?
  17. Nested classes can be static or non-static (also called an inner class). How do you decide which to use? Does it matter?
  18. A third party library is throwing NoClassDefFoundError or NoSuchMethodError, even though all your code compiles without error. What is happening?
  19. What is the difference between String s = "Test" and String s = new String("Test")? Which is better and why?

Finally you should follow these tips also:

Be honest, don't tell lie
Must be in a position to write code
explain your project with efficiently
don't argue with the interviewer
tell about your achievements
Ask questions if you have any doubts related organization culture,policy etc..

Thursday, January 25, 2018

Java 8 Interview Questions

In this post you will learn some frequently asked java 8 interview questions and answers for freshers and experienced as well. 

1. What are the new features added in Java 8?

Ans: Lambda Expressions:

Lambdas are anonymous functions that capture the variables of its surrounding context. They can be used to treat code as data, or, as an example, to be referenced and used as an ordinary object and passed as argument an to methods and constructors.

Functional interfaces: Functional interfaces are plain old Java interfaces with only one abstract method.

Method References: Method references are also Lambda Expressions. When all a Lambda Expression does is to invoke one method or constructor, you can substitute for a much simpler syntax called Method Reference.

Stream API: a special iterator class that allows the processing of data in a declarative way. Streams can also leverage multi-core architectures without you having to write a single line of multi-threaded code. Writing parallel code is hard and error-prone, as we all know.

Default Methods: Interfaces can now contain implementation code, this is called default methods. It allows an Interface to have methods added to them without having to worry about classes who implement this interface.

2.What are main advantages of using Java 8?
Ans:
  • More compact code
  • Less boiler plate code
  • More readable and reusable code
  • More testable code
  • Parallel operations 
3. Can you create your own functional interface?
Yes, you can create your own functional interface. Java can implicitly identify functional interface but you can also annotate it with @FunctionalInterface.
Example:
Create interface named “Display” as below

public interface display {
void display();
default void displayColor()
{
System.out.println("display Color copy");
}
}
now Create main class named “FunctionalIntefaceMain”
class FunctionalIntefaceMain {

public static void main(String[] args)
{
FunctionalIntefaceMain pMain=new FunctionalIntefaceMain();
pMain.displayForm(() -> System.out.println("displayable form"));
}
public void printForm(display d)
{
d.display();
}
}
Output:
displayable form

5. What are method references?

Ans:
When all a lambda expression does is call one single method from an object or a class, or even a constructor, it can be expressed in a much less verbose way called Method Reference. So, method references are a syntax sugar to create lambda expressions that only invoke one method or constructor.

Syntax:
class::methodname

6.What is Optional?How can you use it?
Ans:

Java 8 has introduced new class Called Optional. This class is basically introduced to avoid NullPointerException in java.Optional class encapsulates optional value which is either present or not.It is a wrapper around object and can be use to avoid NullPointerExceptions.

7. What is the difference between Predicate and Function?
Ans:

Both are functional interfaces.
Predicate<T> is single argument function and either it returns true or false.This can be used as the assignment target for a lambda expression or method reference.
Function<T,R> is also single argument function but it returns an Object.Here T denotes type of input to the function and R denotes type of Result.

8.What is the difference between an interface with a default method and an abstract class?

Ans: Java 8 brought the concept of default methods or method implementations in an Interface. So one might ask what is the difference between an interface and an abstract class now.
Abstract classes can have many things that an interface cannot, like constructors and instance variables. Abstract classes, even if they have only one abstract method, can’t be used as functional interfaces, which seems pretty obvious but it is always better to make it clear.

9.What happens if you create an Interface that extends another interface which contains a Default Method?
Ans:
If an interface that contains a default method is extended, there are three options:

  1. The child interface does not mention the default method: The effect is that the default method is inherited;
  2. The child interface redeclares the method: The method then becomes abstract;
  3. The child interface redefines the method: The effect is that the new method overrides the one from the super interface
10.Do we have PermGen in Java 8? Are you aware of MetaSpace?
Ans:
Until Java 7, JVM used an area called PermGen to store classes. It got removed in Java 8 and replaced by MetaSpace.
Major advantage of MetaSpace over permgen:
PermGen was fixed in term of maximum size and can not grow dynamically but Metaspace can grow dynamically and do not have any size constraint.

11. What are Interface Static Methods in Java 8 ? How are they invoked?

Ans: Java 8 added the possibility to create static methods in interfaces. Neither the interfaces that extend an interface with a static method nor the classes that implement it, inherit this static method, it is necessary to invoke them explicitly using the interface name, just like any other static method: NameOfInteface.staticMethod();
A static method can only be invoked directly by the implementation methods (either static or default) from the defining interface.

12. Explain Java 8-Internal vs. External Iteration?
Ans:
External Iterators- This Iterator is also known as active iterator or explicit iterator. For this type of iterator the control over iteration of elements is with the programmer. Which means that the programmer define when and how the next element of iteration is called.
Internal Iterators- This Iterator is also known as passive iterator, implicit iterator or callback iterator. For this type of iterator the control over the iteration of elements lies with the iterator itself. The programmer only tells the iterator "What operation is to be performed on the elements of the collection". Thus the programmer only declares what is to be done and does not manage and control how the iteration of individual elements take place.

13.What is :: (double colon) operator in Java 8?
Ans:
Usually we use lambda expressions to create anonymous methods which return us the desired output. But sometimes lambda expressions do nothing but call an existing method. Because this lambda expression calls an existing method, method reference can be used here instead of Lambda function. Method reference is described using :: (double colon) symbol.




Sunday, April 2, 2017

Java Interview Questions for freshers

In this post i am sharing Java Interview Questions which are frequently ask for freshers and experienced developers.

1) What is difference between Java and C++?
A) (i) Java does not support pointers. Pointers are inherently insecure and troublesome. Since pointers do not exist in Java. (ii) Java does not support operator overloading. (iii) Java does not perform any automatic type conversions that result in a loss of precision (iv) All the code in a Java program is encapsulated within one or more classes. Therefore, Java does not have global variables or global functions. (v) Java does not support multiple inheritance.

2) What are local variables in Java?

Ans: In Java all variables which are declared inside a block,a method or a constructor are called local variables. These variables must be initialized before using them.

Example:
class Test{
public void age()

{
int age=0;

age=age+30;
System.out.println("my age is:"+age);
}
public static void main(String args[])
{
Test t=new Test();
t.age();
}
}

In the above example,age is local variable. This is declared inside age()method and its scope is limited to this method only.

3) What are instance variable in Java?

Ans: In Java,variables which are declared at class level outside a method or constructor or any block are called instance variables. These variables need not initialize before using them,instance variables are automatically initialized to their default value.Each instance of a class has their own copy of instance variables.

Example:
class Test{
int age;
public void myAge()
{
age=age+30;
System.out.println("my age is:"+age);
}
public static void main(String args[])
{
Test t=new Test();
t.age();
}
}


In the ave program age is instance variable since it is declared outside myAge() method.

4) Why main method is static in Java?

Ans:  main method is static since Java Virtual Machine can call it without creating any instance of class which contains main method. If main method were not declared static then JVM has to create instance of main class and since constructor can be overloaded and can have arguments there would be any certain and consistent way for JVM to find main method in java.

5) What is Encapsulation?

Ans: Wrapping of data and function into a single unit called encapsulation. 
Example: all java programs.
(Or)
Nothing but data hiding, like the variables declared under private of a particular class are accessed only in that class and cannot access in any other the class. Or Hiding the information from others is called as Encapsulation. Or Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse.

6) What is STACK in Java?

Ans: During method calls, objects are created for method arguments and method variables. These objects are created on stack.

7) What is Memory Heap?

Ans: Generally the objects are created using the new keyword. Some heap memory is allocated to this newly created object. This memory remains allocated throughout the life cycle of the object. When the object is no more referred, the memory allocated to the object is eligible to be back on the heap. 

8)Does Java supports Multiple inheritance?

Ans: When a class extends more than one classes then it is called multiple inheritance. Java Doesn't support multiple inheritance directly but by using interface is supported. Whereas C++ supports multiple inheritance.

9) What is abstract class?

Ans: An abstract class is class which can not be create the object of abstract class. We can only extended such classes.We can achieve partial abstraction using abstract classes,to achieve full abstraction we use interface.

10) Difference between transient and volatile variables?

Ans: The transient modifier applies to variables only, the object are variable will not persist. Transient variables are not serialized. Whereas volatile value will be changed unexpectedly by the other part of the program, "it tells the compiler a variable    may change asynchronously due to threads"

11) Difference between parameters and arguments?

Ans: While defining method, variable passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.

12)Can an application have multiple classes having main() method?

Ans: Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method

13)What is Garbage Collection in java?

Ans: In Java,destruction of object from memory is done automatically by the JVM. When there is no reference to an object then that object is assumed to be no longer needed and the memory occurred by the object are released. This mechanism is called Garbage Collection. This is accomplished by the JVM.

The Garbage Collection cannot be force explicitly. We may request JVM for garbage collection by calling System.gc() method. But there is no guarantee that JVM will perform the garbage collection.

14) What is method overloading in Java?

Ans: If two or more methods in a class have same name but different parameters it is known as method overloading. It is one of the way through which java supports polymorphism. Method overloading can be done by changing number of arguments or by changing the data type of arguments.

15) What is method overriding in Java?

Ans: If subclass(child class)has the same method as declared in the parent class,it is known as method overriding in java. In other words,if subclass provides specific implemention of the method that has been provided by one of its parent class,it is known as method overriding.

16)Can I have multiple main methods in the same class?

Ans: No the program fails to compile. The compiler says that the main method is already defined in the class.

17)Can we declare abstract method in final class?

Ans:  It indicates an error to declare abstract method in final class. Because of final class never allows any class to inherit it.

18)Can we declare final method in abstract class?

Ans: If a method is defined as final then we can’t provide the reimplementation for that final method in it’s derived classes i.e overriding is not possible for that method. We can declare final method in abstract class suppose of it is abstract too, then there is no used to declare like that. 

19) What is static block?

Ans: Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to  the main method the static block will execute.

20) Can you override private or static method in Java?

Ans: You can not override private or static method in java. If you create similar method with same return type and same method arguments that's called method hiding.

21) What is this keyword?

Ans: 'this' is a keyword in java. Which can be used inside method or constructor of class.'this' works as a reference to current object whose method or constructor is being invoked.'this' keyword can be used to refer any member of current object from within an instance method of a constructor.

22) What is difference between final,finally and finalize in java?

Ans: 
final: It is a keyword. The variable declared as final should be initialized only once and can not be changed. Java classes declared as final cannot be extended.Methods declared as final cannot be overridden

finally: It is a block. The finally block always executes when the try block exists. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling. It allows the programmer to avoid having clean up code accidentally bypassed by a return,continue,or break.Putting clean up code in a finally block is always good practice,even when no exceptions are anticipated.

finalize: It is a method. The finalize()method of a java class is useful during garbage collection.

23) Why static methods can not access instance variables?

Ans: Static methods can be invoked before the object is created; Instance variables are created only when the new object is created. Since there is no possibility to the static method to access the instance variables. Instance variables are called as non-static variables

24) What is difference between String and StringBuffer?

Ans: String is a fixed length of sequence of characters, String is immutable.
StringBuffer represent growable and writeable character sequence, StringBuffer is mutable which means that its value can be changed. It allocates room for 16-addition character space when no specific length is specified. Java.lang.StringBuffer is also a final class hence it cannot be sub classed. StringBuffer cannot be overridden the equals() method.

25) What is Synchronization?

Ans: 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. (Or) When two or more threads need to access the shared resources they need to some way ensure that the resources will be used by only one thread at a time. This process which is achieved is called synchronization.

26) What is System class?

Ans: System class hold a collection of static methods and variables. The standard input, output, error output of the java run time are stored in the in, out, err variables.

27)How does a Hashtable internally maintain the key-value pairs?

Ans: The Hashtable class uses an internal (private) class named Entry to hold the key-value pairs. All entries of the Hashtable are stored in an array of Entry objects with the hash value of the key serving as the index. If two or more different keys have the same hash value these entries are stored as a linked list under the same index.

28)If hash table is so fast, why don't we use it for everything? 

Ans:  One reason is that in a hash table the relations among keys disappear, so that certain operations (other than search, insertion, and deletion) cannot be easily implemented. For example, it is hard to traverse a hash table according to the order of the key. Another reason is that when no good hash function can be found for a certain application, the time and space cost is even higher than other data structures (array, linked list, or tree). 
Hashtable has two parameters that affect its efficiency: its capacity and its load factor. The load factor should be between 0.0 and 1.0. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity, the capacity is increased by calling the rehash method. Larger load factors use memory more efficiently, at the expense of larger expected time per lookup.
If many entries are to be put into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

29)What are the Difference between Iterator & Enumeration & List Iterator ?

Ans: Iterator is not synchronized and enumeration is synchronized. Both are interface, Iterator is collection interface that extends from ‘List’ interface. 

Enumeration is a legacy interface, Enumeration having 2 methods 'Boolean hasMoreElements()'& 'Object NextElement()'. Iterator having 3 methods 'boolean hasNext()', 'object next()', 'void remove()'. Iterator also has an extra feature not present in the older Enumeration interface - the ability to remove elements there is one method "void remove()".
List Iterator
It is an interface, List Iterator extends Iterator to allow bi-directional traversal of a list and modification of the elements. Methods are 'hasNext()', 'hasPrevious()'.

30) How can we sore an array?

Ans: Arrays class provides a series of sort() methods for sorting arrays. If the array is an array of primitives (or) an array of a class that implements Comparable then you can just call the method directly:
Arrays.sort(theArray);
  If, however, it is an array of objects that don't implement the Comparable interface then you need to provide a custom Comparator to help you sort the elements in the array.
Arrays.sort(theArray, theComparator);

31) What happens if an exception is not caught?

Ans: An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

32) What is try,catch,throw and throws?

Ans:
 try :This is used to fix up the error, to prevent the program from automatically terminating, 
try-catch is used to catching an exception that are thrown by the java runtime system. 
Throw :is used to throw an exception explicitly.
Throws :A Throws clause list the type of exceptions that a methods might through.

33) Difference between checked & unchecked exceptions in Java?

Ans: Checked exception is some subclass of Exception. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. 

Exampls: IOException thrown by java.io.FileInputStream's read() method•
             
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. 

Example:StringIndexOutOfBoundsException thrown by String's charAt() method• Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

34)What is difference between ClassNotFoundException and NoClassDefFoundError?

Ans: Though both of these errors are related to missing classes in the classpath,the main difference between them is their root cause.

ClassNotFoundException comes when you try to load a class at runtime by using Class.forName() or loadClass() and requested class is not present in classpath. While in case of NoClassDefFoundError requested class was present at compile time but not available at runtime. Sometimes due to an exception during class initialization. Example is exception from static block causes NoClassDefFoundError when a failed to load class was later referenced by the run time.

35)What is difference between an Exception and an error?

Ans: Errors indicate serious problems and abnormal conditions that most applications should not try to handle. Error defines problems that are not expected to be caught under normal circumstances by our program.

Examples:
  • Memory error
  • Hardware error
  • JVM error
Exceptions are conditions within the code. Developer takes responsibility to handle such conditions and take necessary corrective actions.

Example:

NullpointerException
ArithmeticException

Read Also:













Saturday, March 11, 2017

How to do Final Year Projects

In this post i am sharing for the sake of thousands of students who are studying Computer Science and Information technology have to do their final year projects. Most of the students are thinking about the Title,Methodology,Tools,and other related issues regarding their final year projects.The final year projects are considered as one of the core modules for computer science students and Information Technology Students at UG levels.

The Final year project aims to let the students to combine and utilize almost all core courses they have studied during their under graduate journey and to implement the idea using software development tools.Although the projects are mostly individual projects,however,there are cases where group projects are considered as final year projects. When it comes to the action point,students face many issues such as:


  • What is a proper topic that i can choose?
  • How can i conduct my Project?
  • Which methodology is good enough for my project?
  • What are the stages that i should go through?
  • What kind of tools should i use?
  • How can i prepare my report ?
  • What kind of documents should i submit?
How to choose a project:

To choose a proper topic is the first step in doing your project. Where you are studying, your college will be publish list of projects.The first step is to choose your project topic,it is very important to dedicate a proper amount of time in order to make your decision. It is better to choose a topic,which is truly of your interest.Also choose a topic where you interested areas such as programming,data base,networking,data mining etc...So, choose a topic which is helpful for your future career as well.
The following things make you to choose your project:

  • Interest in topic decides your passion for work
  • Interest drives your project and related work
  • You will be eager to know more and more,if you are interested in given topic at hand
  • If you and your college have better resources,use maximum of it,this will helps you accelerate the speed of project under taking
  • Project cost is the main factor which drives the complete project
  • First make sure of Costing factor before choosing costly project
  • Always approach relevant guide who is capable of guiding in the subject you have chosen
  • Never choose a guide who is not really interested in your work. Do take advice from seniors about him/her


Project Planning:

The next step,after you selected your project topic,is project planning. Project plan in a simple format is a document that explains what is going to be done,when it is going to be done,who is going to be do it,where this going to be done,and how is going to be done.

The following are questions about project plan:


  1. What are the main steps that the project goes through?
  2. What the project timeline(i.e.what happens when)
  3. In what time project should be deliver?
  4. What is the project quality criteria?
  5. How the project would be conducted?
Requirement Specifications:

Although requirement specification is very important in all kind of projects,but in your final year project,it become even more crucial.The reason in other projects,sometimes there are some ways boosting the development process. It can be happen by asking more time,or more budget or more human resources.But in the case of final year project can be applied these.Because academic period can not be extend and no one can be added to your project.Therefore it is highly crucial for you to know what going to do.

So several modules and approaches have been designed and introduced for the requirement management during past decades in the software industry. The following are the main requirements:


  • Functional Requirements
  • Usability Requirements
  • Reliability
  • Performance
  • Supportability
Use Case Modeling:

Use Case Modeling helps to developers to capture,organize,and manage requirements. It is useful tool in other development stages such as analysis,design and testing. It can be used in users guide preparing and even in user training process.

Use case is the way that user can communicate with the system. User asks to perform some function and system response  to the user's request through a course of actions.


Data Base Design:
Data Base Design plays a major role in application systems. DBMS is a software system,which manages database construction,update,and access control,and maintenance. I assume that your are familiar with some DBMSs such as MySql, Ms SQL,Oracle etc..You have to choose a DBMS as the database tool for your final year project if you are going to develop a database application.

Most of the final year projects are dealing with databases.If your project includes a database or if it is a database application then you have to design a proper database.However,RDBMS is most popular database,both in the market and education.

Implementation:

The implementation phase is the stage is that make your system alive.This is the time that you make your system real based your blueprints which you have prepared during the previous stages.You need to select and utilize an implementation tool.Your implementation tool should be adaptable with your methodology and should be able to support your design materiel. When you are decided to follow an object-oriented method you should choose an implementation tool such as JAVA,.NET,PYTHON etc...

Testing:
Evaluation and testing is an unavoidable part of any software and information technology projects. Despite my suggestion on the simplification of software development process in your final year project, i would like to pay as much attention as you can to the testing process. I strongly recommended is to utilize Use Cases,which you have documented in the analysis phase,in the testing stage.

Report Writing:

Most of the college provide you with a template based on which you would prepare your final report. You can find a template for the report structure below. However,depending on your specific project you may revise it.

Report Structure:

Cover page
Abstract
Acknowledgement 
Table of contents
List of Tables
Introduction
Methodology
solutions
Requirement Management
Analysis
Design
User Interface Design
Database Design
Software Design
Implementation
Testing
Conclusion and Feature work

This is all about how to do final year project of engineering college students. I hope you enjoy this post keep follow me for latest updates.




Saturday, February 18, 2017

JDBC Interview Questions and Answers

In this post i am sharing Java Data Base Connectivity Interview Questions. These questions are very useful for freshers and experienced candidates as well.  Let us look what questions they are.

1) What is JDBC?

Ans: Java Data Base Connectivity(JDBC) is a Java API that is used to connect and execute query to the database. JDBC API uses JDBC drivers to connects to the database.

2) What are JDBC 3.0 new features?

Ans: 
1.Transaction Savepoint support:  Added the Savepoint interface, which contains new methods to set, release, or roll back a transaction to designated savepoints.
 

2. Reuse of prepared statements by connection pools: - to control how prepared statements are pooled and reused by connections.
 

3. Connection pool configuration :- Defined a number of properties for the ConnectionPoolDataSource interface.These properties can be used to describe how PooledConnection objects created by DataSource objects should be pooled.
 

4. Retrieval of parameter metadata: - Added the interface ParameterMetaData, which describes the number, type and properties of parameters to prepared statements.
 

5. Retrieval of auto-generated keys: - Added a means of retrieving values from columns containing automatically generated values.
 

6. Multiple open ResultSet objects: - Added the new method getMoreResults(int).
 

7. BOOLEAN data type: - Added the data type java.sql.Types.BOOLEAN. BOOLEAN is logically equivalent to BIT.

8. Making internal updates to the data in Blob and Clob objects: - Added methods to allow the data contained in Blob and Clob objects to be altered.

9. Retrieving and updating the object referenced by a Ref object: - Added methods to retrieve the object referenced by a Ref object. Also added the ability to update a referenced object through the Ref object.
 

10. Updating of columns containing BLOB, CLOB, ARRAY and REF types: - Added of the updateBlob, updateClob, updateArray, and updateRef methods to the ResultSet interface.

3) What are the JDBC Drivers?

Ans:  JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers they are:

1)JDBC-ODBC bridge driver
2)Native-API driver(partially java driver)
3)Network Protocol driver(All java driver)
4)Thin driver(pure java driver)

 4) What are the steps to connect to the database in Java?

Ans: The following are the steps to connect to the database in Java:

Step 1: First thing is using jdbc you have to establish a connection to the data base  that means Registering the driver class. You must load the JDBC driver.

Step 2: After loading the JDBC driver then make a connection that means creating connection,to do this we can call the getConnection() method of driver manager class.

step 3: To execute any sql commands using jdbc connection you must first create a statement object to create this call 
statement st = con.createSteatement().
This is done by calling the createStatement() method in connection interface.


Step 4:
Once the statement is created you can executed it by calling execute() method of the statement interface. That means Executing queries.

Step 5: Closing connection.

5) What are the JDBC API componenets?

Ans:  The java.sql package contains interfaces and classes for JDBC API. They are

interfaces:

1)connection
2)Statement
3)preparedStatement
4)ResultSet
5)ResultSetMetaData
6)DabaseMetaData
7)CallableStatement 
etc......

classes:

Driver Manager
Blob
Clob
SQLException etc...

6) What is statement?

Ans: Statement acts like vehicle through which SQL commands can be sent. Through the connection object we create statement kind of objects.

7)Why you need JDBC if ODBC is available?
 

Ans: ODBC is purely written in “c” so we cannot directly connect with java. JDBC is a low level pure java API used to execute SQL statements. (i) ODBC is not appropriate for direct use from java because it uses “c” interfaces. Calls from java to native “c” code has number of drawbacks in the security, implementation and robustness.


8)Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
 

Ans:  No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.


9)Is the JDBC-ODBC Bridge multi-threaded?
 

Ans:  No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC


10) What is PreparedStatement?



Ans: PreparedStatements are pre compiled statements once we compile the statements and send it to the server for later use. P.S are partially compiled statements placed at server side with placeholders. Before execution of these statements user has to supply values for place holders, it will increase performance of application.

Example:

PreparedStatement pst = con.prepareStatement("SELECT * FROM EMP WHERE deptno=?");
DataInputStream dis = new DataInputStream(“System.in”);
Int dno = Integer.ParseInt(dis.readLine());
pst.setInt(1, dno);
ResultSet rs = pst.executeQuery()



11) What are CallableStatements?

Ans: Callable Statements are used to retrieve data by invoking stored procedures, stored procedure are program units placed at data base server side for re-usability. These are used by n-number of clients.Callable statement will call a single stored procedure, they perform multiple queries and updates without network traffic.


Example:
callableStatement cst = con.prepareCall(“{CALL procedure-name(??)} ”);
DataInputStream dis = new DataInputStream(“System.in”);
Int enum = Integer.ParseInt(dis.readLine());
cst.setInt(1, enum);
cst.registerOutParameter(2, types.VARCHAR)
resultset rs = cst.execute();

In       -> used to send information to the procedure.
Out    -> used to retrieve information from data base.
InOut -> both.

12) What is difference between Statement and PreparedStatement interface?



Ans: In case of Statement query is compiled each time whereas PreparedStatement query is compiled only once. So performance of PreparedStatement is better than Statement.



13) What does the JDBC Connection interface?


Ans: The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement,PreparedStatement,CallableStatement and DatabaseMetaData.

14) What is JDBC Connection pool?

Ans: When you are going to caret a pool of connection to the database. This will give access to a collection of already opened data base connections, which will reduce the time it takes to service the request and you can service “n” number of request at once.

15) How do you implement Connection pooling?

Ans: If you use an application server like WebLogic,jBoss,Tomcat.. then your application server provides the facilities to configure for connection pooling. If you are not using an application server then components like Apache Commons DBCP component can be used.

16)In which interface the methods commit() & rollback() savepoint() defined
 

Ans:   java.sql.Connection interface


17) What is ResultSetMetaData?


Ans: It is used to find out the information of a table in a data base.
      ResultSet rs = stmt.executeQuery("SELECT * FROM "+ table);
      ResultSetMetaData rsmd = rs.getMetaData();



18) How can we store and retrieve images from the database?


Ans: By using PreparedStatement interface,we can store and retrieve images.



19) What is the use of blob,clob data types in JDBC?


Ans: These are used to store large amount of data into database like images,movies etc.. which  are extremely large in size.

20)Why do you have to close database connections in Java?

Ans: You need to close the resultset,the statement and the connection. If the connection has come from a pool,closing it actually sends it back to the pool for reuse. We can do this in the finally {} block.

21) Why do you use a batch process?

Ans: Batch Processing allows you group related SQL statements into batch and submit them with one call to the database.

22) What does setAutoCommit() do?

Ans: When a connection is created,it is in auto-commit mode. This means that each individual  SQL statement is treated as a transaction and will be automatically committed right after it is executed. By setting auto-commit() to false no SQL statements will be committed until you explicitly call the commit method.

23) What is need to set auto commit mode to false?

Ans:  
  • To increase performance
  • To maintain the integrity of business processes
  • To use distributed Transactions


Watch Video :  Best JDBC Interview Questions for freshes

Thursday, February 16, 2017

Synchronization Interview Questions in Java

In this post I am sharing frequently asking Synchronization Interview Questions for Java Developers either Freshers or Experienced candidates. When you would face Technical Interview you must face these questions. I strongly Recommended before attend the interview must brush up the following questions.



1) What is synchronization?

Ans: Synchronization is the capability of control the access of multiple threads to any shared resource. 'synchronized' is the keyword applicable for the methods and blocks. If a method is declared as synchronized then at a time only one thread is allowed to execute that method on the given object. The main advantage of synchronized keyword is we can overcome data inconsistency problems. 

2) What class level lock?

Ans: If a thread wants to execute any static synchronized method then compulsory that thread should require class level lock. While a thread executing any static system method then remaining threads are not allowed to execute any static synchronized method of the same class simultaneously. But the remaining threads are allowed to execute any non-synchronized static methods.

3) What is difference between Synchronized method and block?

Ans:  When thread executing a synchronized method on the object,then the remaining threads are not allowed to execute any synchronized method on the same object .

Synchronized block is not recommended to declare entire method as synchronized if very few lines of code causes the problem that code we can declare inside synchronized block. So that we can improve the performance of the system.

Syntax:
synchronized(b)
{
//critical section.
}
Where ‘b’ is an object reference.

To get the lock for the current object we can define synchronized block as follows

synchronized(this)
{
//critical section.
}


4) What is the purpose of Synchronized block?

Ans:  Synchronized block is used to lock an object for any shared resource. Scope of synchronized block is smaller than the method.

5) What is Synchronized statement?

Ans:  The statement which are defined inside synchronized method or blocks are called synchronized statement.

6) What is Daemon Thread?

Ans: The threads which are running in the background to provide support for user defined threads are called 'Daemon Thread'.
We can check whether the given thread is daemon or not by using the following thread class thread.

public boolean isDaemon()

we can change the daemon nature of a thread by using setDaemon() method of thread class.

public void setDaemon(Boolean b)

7) What is DeadLock?

Ans: If two threads are waiting for each other forever then the threads are said to be in "deadlock" There is no deadlock resolution technique but prevention technique is available.

8) What is Thread Priority?

Ans: Every Thread in java having some priority. The range of valid thread priorities is (1-10) (1 is least & 10 isHighest). 

Thread class defines the following constant for representing some standard priorities.
Thread.MIN_PRIORITY ->1
Thread.NORM_PRIORITY ->2
Thread.MAX_PRIORITY >3

9) What Thread Scheduler?

Ans: Thread scheduler use these priorities while allocating C.P.U. The Thread which is having highest prioritywill get chance first for execution. If two threads having the same priority then which thread will get chancefirst for execution is decided by Thread Scheduler, which is vendor dependent i.e we can’t expect exactly.

The default priority for the main thread only the 5, but for all the remaining threads the priority will be inherit from parent i.e what ever the parent has the same priority the child thread also will get.



10) What is difference between notify() and notifyAll()?

Ans: notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state.

11) How do you ensure that N threads can access N resources without deadlock?

Ans: A very simple way to avoid deadlock while using N threads is to impose an ordering on the locks and force each thread to follow that ordering. Thus,if all threads lock and unlock the mutexes in the same order,no deadlocks can arise.

12) What is the meaning by multi-threaded program?

Ans: A multithreaded  program contains two or more parts that can run concurrently.Each part of such a program is called a thread,and each thread defines a separate path of execution.

13) What is difference between yield() and sleep() methods?

Ans: The thread which is called yield() method temporarily pause the execution to give the chance for remaining threads of same priority. If there is no waiting thread or all waiting threads having low priority. Then the same thread will get the chance immediately for the execution.

If a method has to wait some predefined amount of time with out execution then we should go for sleep() method.

The main difference is when a task invokes its yield() method it returns to the ready state. When a task invokes its sleep() method,it returns to the waiting state.

14) What is difference between the methods sleep() and wait()?

Ans: The code sleep(2000); puts thread aside for exactly two seconds. The code wait(2000),causes a wait of up to two seconds. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class object and the method sleep() is defined in the class Thread.

15) What is an object's lock and which object's have locks?

Ans: An object lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock.

Recommended to Read More Java Interview Questions:

Java Security Interview Questions
Java Design Pattern Interview Questions
Java OOPS Interview Questions
Top 10 Programmer Mistakes in Coding

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...