Friday 20 December 2013

Java Experienced Interview Questions And Answers

What is difference between Vector and ArrayList in Java

One of the most popular Java question at 2 years experience level which aims to check your knowledge on Java collection API. key point to mention is synchronization and speed, since ArrayList is not synchronized its fast compare to Vector. See Vector vs ArrayList in Java for more difference between both of them.

What is the difference between private, protected, and public?

These keywords are for allowing privileges to components such as java methods and variables. 
Public: accessible to all classes 
Private: accessible only to the class to which they belong 
Protected: accessible to the class to which they belong and any subclasses. 
Access specifiers are keywords that determines the type of access to the member of a class. These are: 
-Public 
-Protected 
-Private 
-Defaults

What's the difference between an interface and an abstract class? Also discuss the similarities. (Very Important)

Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. Interface is a Java Object containing method declaration and doesn't contain implementation. The classes which have implementing the Interfaces must provide the method definition for all the methods 
Abstract class is a Class prefix with a abstract keyword followed by Class definition. Interface is a Interface which starts with interface keyword. 
Abstract class contains one or more abstract methods. where as Interface contains all abstract methods and final declarations 
Abstract classes are useful in a situation that Some general methods should be implemented and specialization behavior should be implemented by child classes. Interfaces are useful in a situation that all properties should be implemented. 
Differences are as follows: 

-Interfaces provide a form of multiple inheritance. A class can extend only one other class. 
-Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc. 
-A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class. 
-Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast. 

Similarities: 
-Neither Abstract classes or Interface can be instantiated. 

How to define an Abstract class?
A class containing abstract method is called Abstract class. An Abstract class can't be instantiated. Example of Abstract class: 
abstract class testAbstractClass { 
protected String myString; 
public String getMyString() { 
return myString; 
public abstract string anyAbstractFunction(); 

How to define an Interface? 
Answer: In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface. 
Example of Interface: 

public interface sampleInterface { 
public void functionOne(); 
public long CONSTANT_ONE = 1000; 
}

What are the advantages of Java layout managers?

In Java Button, Checkbox, Lists, Scrollbars, Text Fields, and Text Area etc positioned by the default layout manager. Using algorithm layout manager automatically arranges the controls within a window. In Windows environment, we can control layout manually. But we do not do it manual because of following two reasons: 

It is very tedious to manually lay out a large number of components. 
Sometimes the width and height information is not available when you need to arrange some control, because the native toolkit components have not been realized. This is a chicken-and-egg situation. 
Java uses layout managers to lay out components in a consistent manner across all windowing platforms.

Explain the Struts1/Struts2/MVC application architecture?

Struts was adopted by the Java developer community as a default web framework for developing web applications The MVC(Model–view–controller) an application that consist of three distinct parts. The problem domain is represented by the Model. The output to the user is represented by the View. And, the input from the user is represented by Controller.

What is the difference between forward and sendredirect?

Both method calls redirect you to new resource/page/servlet. The difference between the two is that sendRedirect always sends a header back to the client/browser, containing the data in which you wanted to be redirected.

How does the version control process works? Answer: Initiate, pull, branch, merge, commit, push. (Init) Make your own repository. (Pull) Download an existing repository from a url. (Branch / Merge )Make revisions. Commit then push your modifications.

How does a 3 tier application differ from a 2 tier one?

Tiers are the physical units of separation or deployment, while layers are the logical units of separation. Imagine that you’re designing an e-commerce website. A 3 tier architecture would consist of web pages, a web server and a database, with the corresponding 3 layers being the “Presentation”, “Business Logic” and “Database” layers. If you take the database tier and layer out then your have a 2 tier architecture.

What is the difference between JAR and WAR files?

JAR files (Java ARchive) allows aggregating many files into one, it is usually used to hold Java classes in a library. WAR files (Web Application aRchive) stores XML, java classes, and JavaServer pages for Web Application purposes.

What is a Left outer join?

This deals with SQL. Left outer join preserves the unmatched rows from the first (left) table, joining them with a NULL row in the shape of the second (right) table.

What is the difference between UNION and UNION ALL?

This deals with SQL. UNION only selects distinct values, UNION ALL selects all values.

How do you know if an explicit object casting is needed?

If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example: Object a; Client b; b = (Client) a;

If a class is located in a package, what do you need to change in the OS environment to be able to use it?

You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.javIn this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows: c:\>java com.PQR.HRD.Employee

How can a subclass call a method or a constructor defined in a superclass?

Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.

What's the difference between a queue and a stack?

Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

What is Collection API?

The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap. Example of interfaces: Collection, Set, List and Map.

How would you make a copy of an entire Java object with its state?

Have this class implement Cloneable interface and call its method clone().

How can you minimize the need of garbage collection and make the memory use more effective?

Use object pooling and weak object references.

Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.

Explain the user defined Exceptions?

User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions. 
Example: 


class myCustomException extends Exception { 
// The class simply has to exist to be an exception 
}

Does networking is support in Java ?

Yes, Java supports two types of classes: 
Low-Level Classes: provide support for socket programming like Socket, DatagramSocket, and ServerSocket classes. 
High-Level Classes: provide web programming URL, URLEncoder, and URLConnection classes. 

Networking programming classes ease the programming of network applications. Java networking like anything else in Java is platform-independent.

Describe java's security model.

The Java security model was introduced in Java 2. It is divided into two pieces: 
User Adjustable Security Manager: checks various API operations like file access 
Byte Code Verifier: that asserts the validity of compiled byte code. 
Public abstract class SecurityManager java.lang. SecurityManager is an abstract class which helps to different applications subclass to implement a particular security policy. It allows an application to determine whether or not a particular operation will generate a security exception.

Describe what happens when an object is created in Java.

Several things happen in a particular order to ensure the object is constructed properly: 

* Memory allocation: To hold all instance variables and implementation-specific data of the object and its super classes. 
* Initialization: the objects are initialized to their default values. 
* Constructor: Constructors call the constructors for its super classes. This process continues until the constructor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. 
* Execution: Before the body of the constructor is executed all instance variable initializes and initialization blocks must get executed. Then the body of the constructor is executed

Explain 3-Tier architecture in .net

3 tier architecture example in asp.net with C#

Introduction


Here I will explain about uses of 3-Tier architecture and how to create or implement 3-tier architecture for our project in asp.net 

Description

1.    What is the use of 3-tier architecture and why we go for that architecture? 
2.    First we need to know what 3-Tier architecture is. 
3.    How to create 3-Tier architecture for our project?

Uses of 3-Tier Architecture
  
1.    To make application more understandable. 
2.    Easy to maintain, easy to modify application and we can maintain good look of architecture.
3.    If we use this 3-Tier application we can maintain our application in consistency manner.   

Basically 3-Tier architecture contains 3 layers

1.    Application Layer or Presentation Layer 
2.    Business Access Layer(BAL) or Business Logic Layer(BLL) 
3.    Data Access Layer(DAL)
Here I will explain each layer with simple example that is User Registration

Application Layer or Presentation Layer

Presentation layer contains UI part of our application i.e., our aspx pages or input is taken from the user. This layer mainly used for design purpose and get or set the data back and forth. Here I have designed my registration aspx page like this
This is Presentation Layer for our project Design your page like this and double click on button save now in code behind we need to write statements to insert data into database this entire process related to Business Logic Layer and Data Access Layer.
Now we will discuss about Business Access Layer or Business Logic Layer 

Business Access Layer (BAL) or Business Logic Layer (BLL)

This layer contains our business logic, calculations related with the data like insert data, retrieve data and validating the data. This acts as a interface between Application layer and Data Access Layer
Now I will explain this business logic layer with my sample
I have already finished form design (Application Layer) now I need to insert user details into database if user click on button save. Here user entering details regarding Username, password, Firstname, Lastname, Email, phone no, Location. I need to insert all these 7 parameters to database. Here we are placing all of our database actions into data access layer (DAL) in this case we need to pass all these 7 parameters to data access layers.
In this situation we will write one function and we will pass these 7 parameters to function like this
String Username= InserDetails (string Username, string Password, string Email, string Firstname, string Lastname, string phnno, string Location)
If we need this functionality in another button click there also we need to declare the parameters likestring Username, string Password like this rite. If we place all these parameters into one place and use these parameters to pass values from application layer to data access layer by using single object to whenever we require how much coding will reduce think about it for this reason we will create entity layer or property layer this layer comes under sub of group of our Business Logic layer
Don't get confuse just follow my instructions enough
How we have to create entity layer it is very simple 
Right click on your project web application---> select add new item ----> select class file in wizard --->give name as BEL.CS because here I am using this name click ok
 Open the BEL.CS class file declare the parameters like this in entity layer 
Don’t worry about code it’s very simple for looking it’s very big nothing is there just parameters declaration that’s all check I have declared whatever the parameters I need to pass to data access layer I have declared those parameters only 
BEL.CS



#region Variables
/// <summary>
/// User Registration Variables
/// </summary>
private string _UserName;
private string _Password;
private string _FirstName;
private string _LastName;
private string _Email;
private string _Phoneno;
private string _Location;
private string _Created_By;
#endregion

/// <summary>
/// Gets or sets the <b>_UserName</b> attribute value.
/// </summary>
/// <value>The <b>_UserName</b> attribute value.</value>
public string UserName
{
get
{
return _UserName;
}
set
{
_UserName = value;
}
}

/// <summary>
/// Gets or sets the <b>_Password</b> attribute value.
/// </summary>
/// <value>The <b>_Password</b> attribute value.</value>
public string Password
{
get
{
return _Password;
}
set
{
_Password = value;
}
}

/// <summary>
/// Gets or sets the <b>_FirstName</b> attribute value.
/// </summary>
/// <value>The <b>_FirstName</b> attribute value.</value>
public string FirstName
{
get
{
return _FirstName;
}
set
{
_FirstName = value;
}
}
/// <summary>
/// Gets or sets the <b>_LastName</b> attribute value.
/// </summary>
/// <value>The <b>_LastName</b> attribute value.</value>
public string LastName
{
get
{
return _LastName;
}
set
{
_LastName = value;
}
}

/// <summary>
/// Gets or sets the <b>_Email</b> attribute value.
/// </summary>
/// <value>The <b>_Email</b> attribute value.</value>
public string Email
{
get
{
return _Email;
}
set
{
_Email = value;
}
}

/// <summary>
/// Gets or sets the <b>_Phoneno</b> attribute value.
/// </summary>
/// <value>The <b>_Phoneno</b> attribute value.</value>
public string Phoneno
{
get
{
return _Phoneno;
}
set
{
_Phoneno = value;
}
}

/// <summary>
/// Gets or sets the <b>_Location</b> attribute value.
/// </summary>
/// <value>The <b>_Location</b> attribute value.</value>
public string Location
{
get
{
return _Location;
}
set
{
_Location = value;
}
}

/// <summary>
/// Gets or sets the <b>_Created_By</b> attribute value.
/// </summary>
/// <value>The <b>_Created_By</b> attribute value.</value>
public string Created_By
{
get
{
return _Created_By;
}
set
{
_Created_By = value;
}


Our parameters declaration is finished now I need to create Business logic layer how I have create it follow same process for add one class file now give name called BLL.CS. Here one point don’t forget this layer will act as only mediator between application layer and data access layer based on this assume what this layer contains. Now I am writing the following BLL.CS(Business Logic layer)



#region Insert UserInformationDetails
/// <summary>
/// Insert UserDetails
/// </summary>
/// <param name="objUserBEL"></param>
/// <returns></returns>
public string InsertUserDetails(BEL objUserDetails)
{
DAL objUserDAL = new DAL();
try
{
return objUserDAL.InsertUserInformation(objUserDetails);
}
catch (Exception ex)
{
throw ex;
}
finally
{
objUserDAL = null;
}
}
#endregion
Here if you observe above code you will get doubt regarding these
what is
BEL objUserDetails
DAL objUserDAL = new DAL();


and how this method comes
return objUserDAL.InsertUserInformation(objUserDetails);
Here BEL objUserDetails means we already created one class file called BEL.CS with some parameters have you got it now I am passing all these parameters to Data access Layer by simply create one object for our BEL class file 
What is about these statements I will explain about it in data access layer
DAL objUserDAL = new DAL();
return objUserDAL.InsertUserInformation(objUserDetails);
this DAL related our Data access layer. Check below information to know about that function and Data access layer
Data Access Layer(DAL)
Data Access Layer contains methods to connect with database and to perform insert,update,delete,get data from database based on our input data
I think it’s to much data now directly I will enter into DAL
Create one more class file like same as above process and give name as DAL.CS
Write the following code in DAL class file



//SQL Connection string
string ConnectionString = ConfigurationManager.AppSettings["LocalConnection"].ToString();

#region Insert User Details
/// <summary>
/// Insert Job Details
/// </summary>
/// <param name="objBELJobs"></param>
/// <returns></returns>
public string InsertUserInformation(BEL objBELUserDetails)
{
SqlConnection con = new SqlConnection(ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("sp_userinformation", con);
cmd.CommandType = CommandType.StoredProcedure;
try
{
cmd.Parameters.AddWithValue("@UserName",objBELUserDetails.UserName);
cmd.Parameters.AddWithValue("@Password", objBELUserDetails.Password);
cmd.Parameters.AddWithValue("@FirstName", objBELUserDetails.FirstName);
cmd.Parameters.AddWithValue("@LastName", objBELUserDetails.LastName);
cmd.Parameters.AddWithValue("@Email", objBELUserDetails.Email);
cmd.Parameters.AddWithValue("@PhoneNo", objBELUserDetails.Phoneno);
cmd.Parameters.AddWithValue("@Location", objBELUserDetails.Location);
cmd.Parameters.AddWithValue("@Created_By", objBELUserDetails.Created_By);
cmd.Parameters.Add("@ERROR"SqlDbType.Char, 500);
cmd.Parameters["@ERROR"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
string strMessage = (string) cmd.Parameters["@ERROR"].Value;
con.Close();
return strMessage;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
#endregion


Here if you observe above functionality I am getting all the parameters by simply creating BELobjBELUserDetails. If we create one entity file we can access all parameters through out our project by simply creation of one object for that entity class based on this we can reduce redundancy of code and increase re usability
Observe above code have u seen this function before? in BLL.CS i said i will explain it later got it inDAL.CS I have created one function InsertUserInformation and using this one in BLL.CS by simply creating one object of DAL in BLL.CS.
Here you will get one doubt that is why BLL.CS we can use this DAL.CS directly into our code behind  we already discuss Business logic layer provide interface between DAL and Application layer by using this we can maintain consistency to our application.
Now our Business Logic Layer is ready and our Data access layer is ready now how we can use this in our application layer write following code in your save button click like this



protected void btnsubmit_Click(object sender, EventArgs e)
{
string Output = string.Empty;
if (txtpwd.Text == txtcnmpwd.Text)
{
BEL objUserBEL = new BEL();

objUserBEL.UserName = txtuser.Text;
objUserBEL.Password = txtpwd.Text;
objUserBEL.FirstName = txtfname.Text;
objUserBEL.LastName = txtlname.Text;
objUserBEL.Email = txtEmail.Text;
objUserBEL.Phoneno = txtphone.Text;
objUserBEL.Location = txtlocation.Text;
objUserBEL.Created_By = txtuser.Text;
BLL objUserBLL = new BLL();
Output = objUserBLL.InsertUserDetails(objUserBEL);

}
else
{
Page.RegisterStartupScript("UserMsg""<Script language='javascript'>alert('" + "Password mismatch" +"');</script>");
}
lblErrorMsg.Text = Output;
}


Here if you observe I am passing all parameters using this BEL(Entity Layer) and we are calling the methodInsertUserDetails by using this BLL(Business Logic Layer)
Now run your applciation test with debugger you can get idea clearly.