Wednesday, June 18, 2008

J2EE Fundas

A WAR file is a convenient way to bundle up all pieces of a web application. All servlet containers know how to deploy a WAR file, they expand the bundle, look for the WEB-INF directory, and read the web.xml found there for further deployment instructions.

The EAR file provides the same type of functionality for a full-fledged J2EE application. JBoss expands the EAR, finds the required deployment descriptors, and proceeds from there.

Each component in the EAR is a specific piece of the J2EE puzzle.

Web module : A WAR file containing presentation tier components.
EJB module : An EJB JAR file containing the middle-tier components. (EJBs, MDBs, etc.)
Java module: A regular JAR file containing classes and libraries that are shared across the entire application. An application client JAR and a common JAR are two examples of Java modules.

Java JDBC

What is Java DataBase Connectivity?
The JDBC API defines a set of interfaces that encapsulate major database functionality. Database vendors provide drivers that implement the API for specific databses.


What is the latest version of JDBC ? What are the new features are added in that ?
JDBC 2.0 provides features like treating resultsets as javaBeans, pooling databse connections, and looking up database connection info from a naming service,storing java Objects in databases etc.


What are 4 drivers available in JDBC ?
1) JDBC-ODBC Bridge Driver -> Uses a bridge technology to connect a Java client to an ODBC database.
2) Native API Partly Java Drivers -> LIke Oracle drivers, they are native C++ Api's with a java wrapper.
3) Net Protocol All Java Drivers. -> Define a generic Netowrk protocol that interfaces with custom middleware like WebLogic
4) Native- Protocol All Java Drivers -> Written entirely in Java they can access a database directly over the Net without any additional software.


How do you connect to the Database ?
1. Loading the driver:
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName automatically creates an instance of a driver and registers it with the DriverManager. When the driver is loaded it is available for making a connection with a DBMS.
2. Making the Connection :
The second step in establishing a connection is to have the appropriate driver connect to the DBMS.
If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with jdbc:odbc: . The rest of the URL is generally the data source name or database system. So, if the ODBC data source is called “Fred" the JDBC URL could be jdbc:odbc:Fred .

String url = "jdbc:oracle:thin:"+
userID+"/"+Pswd+
"@"+hostName+":"+oraclePort+":"+oraInstance;
Connection con = DriverManager.getConnection(url);


How many types of JDBC Statements are there?
1) Statement.
2) Prepared Statement.
3) Callable Statement.


What is a statement, how do you create one?
A Statement object sends SQL statement to the DBMS. A Statement object is created and then executed with the appropriate “execute” method with the SQL statement. For SELECT statements, the method used is “executeQuery” and for statements that create or modify tables, the method used is “executeUpdate”. An active connection is required to create a Statement object:


String sqlQuery =” create table temp (name VARCHAR (32), empid INTEGER, salary INTEGER)”;
Statement stmt = con.createStatement();
stmt.executeUpdate(sqlQuery);

“sqlQuery” is a DDL (data definition language) statement. Statements that create, alter, or drop tables are DDL statements and are executed with the method executeUpdate. executeUpdate is also used to execute SQL statements that update a table.


What is a a Prepared Statement, How do you create one?
If you want to execute a Statement object many times, a PreparedStatement object can be used to reduce execution time. Unlike a Statement object, a Prepared Statement is given an SQL statement when it is created. The advantage is that this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains an SQL statement that has been precompiled.

PreparedStatement updateTemp= con.prepareStatement("update temp set salary = ? where name like ?");
updateTemp.clearParameters();
updateTemp.setInt(1,5000);
updateTemp.setSting(2,”Srujan”);
updateTemp.executeUpdate();


The return value of an executeUpdate method is an int with the number of rows updated. When the method executeUpdate is used to execute a DDL statement it returns 0.


What is a Stored Procedure?
A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. Stored procedures are used to encapsulate a set of operations or queries to execute on a database server. Stored procedures can be compiled and executed with different parameters and results, and they may have any combination of input, output, and input/output parameters.
Oracle PL/SQL Stored Procedure

CREATE OR REPLACE PROCEDURE show_temp
( id IN INTEGER
sal IN OUT INTEGER) IS
BEGIN
SELECT salary INTO sal FROM temp
where empid = id ;
sal := sal + sal * 0.12; // 12 % hike :)
UPDATE temp SET salary = sal WHERE empid = id;
END;


The procedure “show_temp” will be compiled and stored in the database as a database object that can be called.


What is a Callable Statement, How do you create one?
A CallableStatement object contains a call to a stored procedure. The first line of code below creates a call to the stored procedure “show_temp” using the connection con . The part that is enclosed in curly braces is the escape syntax for stored procedures. When the driver encounters "{call show_temp}”, it will translate this escape syntax into the native SQL used by the database to call the stored procedure named “show_temp” .

CallableStatement cs = con.prepareCall("{call show_temp(?,?)}");
cs.registerOutParameter(2, Types.Interger);
cs.setInt(1,14075);
cs.setInt(2,1000);
cs.executeQuery(); //ResultSet rs can be used as well.
out.println( cs.getInt(2));


If the procedure had contained one update or one DDL statement, the method executeUpdate would have been used. A stored procedure may contain more than one SQL statement, in which case it will produce more than one result set, more than one update count, or some combination of result sets and update counts. In this case, where there are multiple results, the method execute should be used to execute the CallableStatement .

The class CallableStatement is a subclass of PreparedStatement , so a CallableStatement object can take input parameters just as a PreparedStatement object can.


How do you create and use Result Sets.
JDBC returns results in a ResultSet object.

sqlQuery =”select name,empid from temp”;
ResultSet rs = stmt.executeQuery(sqlQuery);
while (rs.next()) {
String s = rs.getString("name");
int n = rs.getInt("empid");
System.out.println(s + " " + n);
}

The variable rs , which is an instance of ResultSet , contains the rows of results. To access the data we go to each row and retrieve the values according to their types. The method next moves what is called a cursor to the next row and makes that row (called the current row) the one upon which we can operate. Since the cursor is initially positioned just above the first row of a ResultSet object, the first call to the method next moves the cursor to the first row and makes it the current row. Successive invocations of the method next move the cursor down one row at a time from top to bottom. The JDBC 2.0 API, allows the cursor to move backwards, to specific positions, and to positions relative to the current row in addition to moving the cursor forward.

getXXX methods of the appropriate type are used to retrieve the value of each column. JDBC allows you to use either the column name or the column number as the argument to a getXXX method. Using the column number is slightly more efficient.

String s = rs.getString(1);
Int n = rs.getInt(2);

A ResultSet object is created with a cursor pointing above the first row. The first call to the next method positions the cursor on the first row of rs.




What is a transaction? How do you commit a transaction, how do you disable Auto-commit Mode?
A transaction is a set of SQL Statements that must behave atomically. When a connection is created, it is in auto-commit mode. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode. If auto-commit is disabled, no SQL statements will be committed until the method “commit” is called explicitly.

con.setAutoCommit(false);
con.commit();
con.rollback(); To roll back a transaction if there was an Exception in the catch block.


What is Connection Pooling? How is it implemented?
Opening a connection to a database is a time-consuming process. For shortqueries, it can take much longer to open the connection than to perform theactual database retrieval.A connection pool class should be able to perform the following tasks:

1. Preallocate the connections.
Perform this task in the class constructor.
Assume thatmakeNewConnection simply calls the getConnectionmethod ofDriverManager.

availableConnections = new Vector(initialConnections);
busyConnections = new Vector();
for(int i=0; i < initialConnections; i++)
{
availableConnections.addElement(makeNewConnection());
}


2. Manage available connections.
If a connection is required and an idle connection is available,put it in the list of busy connections and then return it.

public synchronized Connection getConnection()throws SQLException
{
if (!availableConnections.isEmpty())
{
Connection existingConnection =(Connection)availableConnections.lastElement();
int lastIndex = availableConnections.size() -1;
availableConnections.removeElementAt(lastIndex);
if (existingConnection.isClosed())
{
notifyAll();
// Freed up a spot for anybody waiting.
return(getConnection()); // Repeat process.
}
else
{
busyConnections.addElement(existingConnection);
return(existingConnection);
}
}
}


3. Allocate new connections.If a connection is required, there is no idle connection available,and the connection limit has not been reached, then start a background thread to allocate a new connection.

if ((totalConnections() < maxConnections) &&!connectionPending)
{ // Pending = connecting in bg
makeBackgroundConnection();
}
try
{
wait(); // Give up lock and suspend self.
} catch(InterruptedException ie) {}
return(getConnection()); // Try again.


4. Wait for a connection to become available.
This situation occurs when there is no idle connection and you’ve reached the limit on the number of connections. This waiting should be accomplished without continual polling. The natural approach is to use the wait method, which gives up the thread synchronization lock and suspends the thread until notify or notifyAll is called. Since notifyAllcould stemfrom several possible sources, threads that wake up still need totest to see if they can proceed.

try {wait();}
catch(InterruptedException ie) {}
return(getConnection());

It may be that you don’t want to let clients wait and would rather throw an exception when no connections are available and theconnection limit has been reached. In such a case, do the following instead

throw new SQLException("Connection limit reached");


5. Close connections when required.Note that connections are closed when they are garbage col-lected, so you don’t always have to close them explicitly. But,you sometimes want more explicit control over the process.

public synchronized void closeAllConnections()
{
// The closeConnections method loops down Vector, calling
// close and ignoring any exceptions thrown.
closeConnections(availableConnections);
availableConnections = new Vector();
closeConnections(busyConnections);
busyConnections = new Vector();
}



If you are truncated using JDBC, How can you know ..that how much data is truncated ?

Java Garbage Collection

What do you know about the garbage collector ?
The JVM's heap stores all objects created by a Java program. Objects are created by Java's "new" operator, and memory for new objects is allocated on the heap at run time. Garbage collection is the process of automatically freeing objects that are no longer referenced by the program. The garbage collector runs finalizers on objects, since it is not generally possible to predict exactly when unreferenced objects will be garbage collected, it is not possible to predict when object finalizers will be run. Programmers should avoid writing code for which program correctness depends upon the timely finalization of objects.


How can you force garbage collection?
You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

Dates in C#

String to DateTime // String to DateTime
String MyString; MyString = "1999-09-01 21:34 PM";
DateTime MyDateTime; MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt", null);

DateTime to String //DateTime to String
MyDateTime = new DateTime(1999, 09, 01, 21, 34, 00);
String MyString; MyString = MyDateTime.ToString("yyyy-MM-dd HH:mm tt");

Format String For Dates
The following is the most communally used format characters:
d - Numeric day of the month without a leading zero.
dd - Numeric day of the month with a leading zero.
ddd - Abbreviated name of the day of the week.
dddd - Full name of the day of the week.
f,ff,fff,ffff,fffff,ffffff,fffffff - Fraction of a second. The more F's the higher the presision.
h - 12 Hour clock, no leading zero.
hh - 12 Hour clock with leading zero.
H - 24 Hour clock, no leading zero.
HH - 24 Hour clock with leading zero.
m - Minutes with no leading zero.
mm - Minutes with leading zero.
M - Numeric month with no leading zero.
MM - Numeric month with a leading zero.
MMM - Abbreviated name of month.
MMMM - Full month name.
s - Seconds with no leading zero.
ss - Seconds with leading zero.
t - AM/PM but only the first letter.
tt - AM/PM
y - Year with out century and leading zero.
yy - Year with out century, with leading zero.
yyyy - Year with century.
zz - Time zone off set with +/-.

SQL Server stuff

To select into a declared variable
SELECT @VariableName = (SELECT ColumnName FROM TabelName WHERE Condition)

C# antics

Alright here are some things abt C#

? Nullable value:
int? value , implies that value is an integer and is nullable.

?? Null Coalescing Operator
Takes 2 operands and returns the left operand if it is not null else returns the right operand

? nullableObject = null;
temp = nullableObject ?? new SomeObjectType();
this is equivalent to
temp = (nullableObject.HasValue )? nullableObject.Value : new SomeObjectType();
string filename = GetFileName() ?? "Untitled File";

@ Operator
string path = "C:\\Program Files\\MyPage" and
string path = @"C:\Program Files\MyPage"
are the same. "@" tells the compiler that the string should be treated as verbatim and so no escaping of characters is required.
Converting From Streams and Back
Here is a sample where I convert from a stream to a byte array:

strm = mqMsg.BodyStream;
BinaryReader br = new BinaryReader(strm);
byteArray= br.ReadBytes(Convert.ToInt32(strm.Length));

Here is a sample where I convert from a byte array to a stream:

MemoryStream memStream = new MemoryStream();
BinaryWriter binWriter = new BinaryWriter(memStream);
binWriter.Write(byteArray);

Windows Explorer Issues

Disabling Duration/Dimension/Bitrate/Artist etc. in Windows Explorer
To disable, run : regsvr32 /u shmedia.dll
To renable, run : regsvr32 shmedia.dll

Not Viewing Zip Files as Folders in Windows explorer
To turn off Windows XP : regsvr32 /u zipfldr.dll

Sql Server Delete All Records

This is a nifty bit of code. (use 'GO' statement after each line incase you are not using a GUI tool)
exec sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
exec sp_MSforeachtable 'ALTER TABLE ? DISABLE TRIGGER ALL'
exec sp_MSforeachtable
@command1 = 'DELETE from ?',
@whereand = 'and name not like ''lt%''' //tables with names starting with lt are left out :)
exec sp_MSforeachtable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
exec sp_MSforeachtable 'ALTER TABLE ? ENABLE TRIGGER ALL'

-- or --
use DBNAME
exec sp_MSforeachtable @command1="ALTER TABLE ? NOCHECK CONSTRAINT ALL"
exec sp_MSforeachtable @command1="ALTER TABLE ? DISABLE TRIGGER ALL"
exec sp_MSforeachtable "DROP TABLE ? PRINT '? dropped' "
exec sp_MSforeachtable @command1="ALTER TABLE ? CHECK CONSTRAINT ALL"
exec sp_MSforeachtable @command1="ALTER TABLE ? ENABLE TRIGGER ALL"

For Dropping all Stored Procs
use DBNAme
declare @procName sysname
declare someCursor cursor FOR
SELECT name FROM sysobjects WHERE type = 'P' AND objectproperty(id, 'IsMSShipped') = 0
open someCursor
fetch next FROM someCursor INTO @procName
while @@FETCH_STATUS = 0
begin
print 'dropping '+@procName
exec('drop proc ' + @procName)
fetch next FROM someCursor INTO @procName
end
close someCursor
deallocate someCursor
go

Design Patterns

Patterns support reuse of software architecture and design

Creational Patterns
Factory Method – Method in a derived class creates associates
Abstract Factory – Factory for building related objects
Builder – Factory for building complex objects incrementally
Prototype – Factory for cloning new instances from a prototype
Singleton - Factory for a singular (sole) instance

Structural Patterns
Adapter – Translator adapts a server interface for a client
Bridge - Abstraction for binding one of many implementations
Composite – Structure for building recursive aggregations
Decorator – Decorator extends an object transparently
Facade – Facade simplifies the interface for a subsystem
Flyweight – Many fine-grained objects shared efficiently
Proxy – One object approximates another

Behavioral Patterns
Chain of Responsibility – Request delegated to the responsible service provider
Command – Request as first-class object
Interpreter – Language interpreter for a small grammar
Iterator – Aggregate elements are accessed sequentially
Mediator – Mediator coordinates interactions between its associates
Memento – Snapshot captures and restores object states privately
Observer – Dependents update automatically when a subject changes
State – Object whose behavior depends on its state
Strategy – Abstraction for selecting one of many algorithms
Template Method – Algorithm with some steps supplied by a derived class
Visitor – Operations applied to elements of an heterogeneous object structure

Java Servlets

Servlets are modules of Java code that run in a server application, similar to "Applets" on the client side. Servlets are not tied to a specific client-server protocol but they are most commonly used with HTTP.
Servlets make use of the Java classes in "javax.servlet" and "javax.servlet.http" extensions of the Servlet framework for Servlets that answer HTTP requests.

HTTP Servlets are used for:
1) Processing and/or storing data submitted by an HTML form.
2) Providing dynamic content, e.g. returning database query results to the client.
3) Managing state information on top of the stateless HTTP.

Servlets have several advantages over CGI:

1) A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.
2) A Servlet stays in memory between requests. A CGI program needs to be loaded and started for each CGI request.
3) There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
4) A Servlet can be run by a Servlet Engine in a restrictive Sandbox.

The Basic Servlet Architecture
A Servlet is an instance of a class which implements the javax.servlet.Servlet interface. Most Servlets extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet.

Servlets run on the web server platform as part of the same process as the web server itself. The web server is responsible for initializing, invoking, and destroying each servlet instance.

The init() method

When a servlet is first loaded, its init() method is invoked. This allows the servlet to per form any setup processing such as opening files or establishing connections to their servers. If a servlet has been permanently installed in a server, it loads when the server starts to run. Otherwise, the server activates a servlet when it receives the first client request for the services provided by the servlet.
The init() method takes one argument, a reference to a ServletConfig object which provides initialization arguments for the servlet. This object has a method getServletContext() that returns a ServletContext object containing information about the servlet's environment.

The service() Method

The service() method is the heart of the servlet. Each request message from a client results in a single call to the servlet's service() method. The method is called concurrently and should be implemented in a thread-safe manner. The service() method reads the request and produces the response message from its two parameters:

A ServletRequest object with data from the client. The data consists of name/value pairs of parameters and an InputStream. Several methods are provided that return the client's parameter information. The InputStream from the client can be obtained via the getInputStream() method. This method returns a ServletInputStream, which can be used to get additional data from the client.

A ServletResponse represents the servlet's reply back to the client. When preparing a response, the method setContentType() is called first to set the MIME type of the reply. Next, the method getOutputStream() or getWriter() can be used to obtain a ServletOutputStream or PrintWriter, respectively, to send data back to the client.

The destroy() Method

The destroy() method is called to allow your servlet to clean up any resources before the servlet is unloaded. There may still be threads that execute the service method when destroy is called, so destroy has to be thread-safe.

In an HTTP Servlet the seervice method analyses the request and calls appropriate doGet, doPost, doHead etc function calls.


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloClientServlet extends HttpServlet
{
private ServletConfig config;
public void init (ServletConfig config) throws ServletException
{
this.config = config;
}
public void destroy() {} // do nothing

public ServletConfig getServletConfig()
{
return config;
}

public void service (ServletRequest req,
ServletResponse res
) throws ServletException, IOException {
res.setContentType( "text/html" );
PrintWriter out = res.getWriter();
out.println(" < HTML > < HEAD > < TITLE > Hello Client! < / TITLE >"+
"< / HEAD > < BODY > Hello Client! < / BODY > < / HTML >");
out.close();
}

protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println(" < HTML > < HEAD > < TITLE > Hello Client! < / TITLE >"+
"< / HEAD > < BODY > Hello Client! < / BODY > < / HTML >");
out.close();
}
}

The doGet method replies to GET requests
The doPost method replies to POST requests

Java Exceptions

# What is User Defined Exception ?
Java supports exception handling by its try catch constructs. Exceptions are conditions which JVM or applications developed in java are unable to handle. These classes are derived from java.lang.Throwable class. User Defined Exceptions are those exceptions which an application provider or an API provider defines by subclassing java.lang.Throwable class. The statements following the throw keyword in a program are not executed.

# What is the difference between ‘throw’ and ‘throws’ ?And it’s application?
Exceptions that are thrown by java runtime systems can be handled by Try and catch blocks. With throw exception we can handle the exceptions thrown by the program itself. If a method is capable of causing an exception that it does not handle, it must specify this behavior so the callers of the method can guard against that exception.

# What is the difference between ‘Exception’ and ‘error’ in java?
Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. With exception class we can subclass to create our own custom exception.
Error defines exceptions that are not excepted to be caught by you program. Example is Stack Overflow.

# Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

# What will happen to the Exception object after exception handling?
It will go for Garbage Collection and frees the memory.

# How can you minimize the need of garbage collection and make the memory use more effective?
Use object pooling and weak object references.

# What comes to mind when you hear about a young generation in Java?
Garbage collection.

# What are Checked and UnChecked Exception?
A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, 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. eg, 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.

# Use of throws exception

# What is finally in exception handling
Vector class

Java Threads

Threads can be created by extending the Thread Class or implementing the Runnable interface.
A thread has 4 states:
(1) NEW, created but not started.
(2) RUNNABLE, currently running, or ready to run but waiting for CPU time
(3) BLOCKED, by Thread.sleep(),IO operation,a synchronized statement or method lock.wait ( ).
(4) DEAD, when its run completes normally, or by an uncaught exception.
One Thread can wait for another to complete by calling the "join" method on that specific thread. "join" will halt the current thread till the other thread complets.
A dead thread can be started by calling the start method.
A Process is a program in execution whereas thread is a separate path of execution in a program.

What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and sleep() is defined in the class Thread.

How does wait and notify work?
wait() Waits indefinitely for notification. (has an overloaded (int) method.) When using the wait method you must put the condition that you are waiting on in a while for loop, This is because when the thread goes into a wait state it comes out of the synchronized block and re-enters when a notify is received. Since it is possible that some other thread has changed that condition the entry point must be where the "while(condition)" will be rechecked. If a notify is raised and nothing is waiting then the notification is lost, a subsequent wait call will have to wait for the next notify. The notifyAll method wakes up all threads waiting on the object in question. The awakened threads compete for the lock. One thread gets it, and the others go back to waiting. The Object class also defines the notify method, which arbitrarily wakes up one of the threads waiting on this object.

What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control
the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to
significant errors.

Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.


How does thread synchronization occur inside a monitor ?
To accomplish resource allocation or release, a thread calls a monitor entry (a special function or procedure that serves as an entry point into a monitor). If there is no other thread executing code within the monitor, the calling thread is allowed to enter the monitor and execute the monitor entry's code. But if a thread is already inside of the monitor, the monitor makes the calling thread wait outside of the monitor until the other thread leaves the monitor. The monitor then allows the waiting thread to enter. A synchronized method is a method that serves as a monitor entry. That method's signature is prefixed with keyword "synchronized".

What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?- Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.

Suppose If we have variable ' I ' in run method, If I can create one or more
thread each thread will occupy a separate copy or same variable will be shared ?
Occupy a seperate copy.


Explain Thead pools.
A thread pool is a managed collection of threads that are available to perform tasks. Thread pools usually provide:
1) Improved performance when executing large numbers of tasks due to reduced per-task invocation overhead.
2) A means of bounding the resources, including threads, consumed when executing a collection of tasks.
3) To use thread pools, you instantiate an implementation of the ExecutorService interface and hand it a set of runnable tasks.

ExecutorService es=Executors.newFixedThreadPool(10);
WorkerThread[] workers = new WorkerThread[10];
for (int i = 0; i < 10; i++) {
workers[i] = new WorkerThread(i);
es.execute(workers[i]);
}
es.shutdown();

Core Java Questions

# Can you write a Java class that could be used both as an applet as well as an application?
Yes. Add a main() method to the applet.
# What it the root class for all Java classes --> Object
# What's the difference between constructors and other methods?
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

# Can you call one constructor from another if a class has multiple constructors
Yes. Use "this()" syntax.

# 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.

# Can an inner class declared inside a method access local variables of this method?
It's possible if these variables are final.

# Difference between Interface & Abstract class?
An Abstract class declares have at least one instance method that is declared abstract which will be implemented by the subclasses(an abstract class that does not have any of its methods abstract implies that the class cannot be instantiated). An abstract class can have instance methods that implement a default behavior. Since java does not allow multiple inheritance a class can be extended from only one abstract classes whereas a class can implement multiple Interfaces. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
An Interface can only declare constants and instance methods, but cannot implement default behavior. Interfaces cannot be final. Only public and abstract modifiers are allowed for Interfaces.

# What is a class loader ? How many types are there? When will we use them ?
A class loader is an object that is responsible for loading classes. The class ClassLoader is an abstract class. Given the name of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class. A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system.

# What are the restriction for static method?
Static means one per class, not one for each object no matter how many instance of a class might exist. They can be used without creating an instance of a class. Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

# What is the difference between Assignment and Initialization?
Assignment can be done many times but initialization is done only once.

# You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.

# Can you write a Java class that could be used both as an applet as well as an application?
Yes. Add a main() method to the applet.

# Explain the usage of Java packages.
This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

# 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.java. In 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.xyz.hr.Employee

# What would you use to compare two String variables - the operator == or the method equals()?
I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

# What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}
A single ampersand here would lead to a NullPointerException.

# What's the main difference between a Vector and an ArrayList
The Java Vector class is internally synchronized and ArrayList is not.

# When should the method invokeLater()be used?
This method is used to ensure that Swing components are updated through the event-dispatching thread.

# 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; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.

# Explain the usage of the keyword transient?
Transient: Indicates that the value of this member variable does not have to be serialized with the object. When the class is de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers). Volatile: Applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

# What comes to mind when someone mentions a shallow copy in Java?
Object cloning.

# If you're overriding the method equals() of an object, which other method you might also consider?
hashCode()

# You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use: ArrayList or LinkedList?
ArrayList

# 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().

# There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.

# What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
You do not need to specify any access level, and Java will use a default package access level.

# What are different types of inner classes?

A: Nested top-level classes, Member classes, Local classes, Anonymous classes

Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.
Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a
more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

# What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.

# How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.

# Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.

# How can I customize the seralization process? i.e. how can one have a control over the serialization process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.

# What is the common usage of serialization?
A: Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.

# What is Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.

# What happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.

# What one should take care of while serializing the object?
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.

# What happens to the static fields of a class during serialization? Are these fields serialized as a part of each serialized object?
Yes the static fields do get serialized. If the static field is an object then it must have implemented Serializable interface. The static fields are serialized as a part of every object. But the commonness of the static fields across all the instances is maintained even after serialization.

# How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

C++ Questions

What are the major differences between C and C++?
The main difference between C & C++ is the OOPS technology, C++ is an object oriented programing language.

# What are the differences between new and malloc?
The main difference between malloc() and new is that new calls a class constructor after allocating the memory. The malloc() function allocates the requested number of bytes and returns a pointer to them. The main difference between delete and free() is that delete calls the class destructor method before returning the memory to the system.

# What is the difference between delete and delete[]?
The delete [] form should be used when freeing up arrays, The delete form should be used for single instances.

# What's the difference between "const Fred* p", "Fred* const p" and "const Fred* const p"?
You have to read pointer declarations right-to-left.

const Fred* p means "p points to a Fred that is const" — that is, the Fred object can't be changed via p.
Fred* const p means "p is a const pointer to a Fred" — that is, you can change the Fred object via p, but you can't change the pointer p itself.
const Fred* const p means "p is a const pointer to a const Fred" — that is, you can't change the pointer p itself, nor can you change the Fred object via p.

What are the differences between a struct in C and in C++?
What are the advantages/disadvantages of using #define?
What are the advantages/disadvantages of using inline and const?
What is the difference between a pointer and a reference?
When would you use a pointer? A reference?
What does it mean to take the address of a reference?
What does it mean to declare a function or variable as static?
What is the order of initalization for data?
What is name mangling/name decoration?
What kind of problems does name mangling cause?
How do you work around them?
What is a class?
What is the difference between public, private, and protected access?
For class CFoo { }; what default methods will the compiler generate for you>?
How can you force the compiler to not generate them?
What is the purpose of a constructor? Destructor?
What is a constructor initializer list?
When must you use a constructor initializer list?
What is a:
Constructor?
Destructor?
Default constructor?
Copy constructor?
Conversion constructor?
What does it mean to declare a...
member function as virtual?
member function as static?
member function as static?
member variable as static?
destructor as static?
Can you explain the term "resource acquisition is initialization?"
What is a "pure virtual" member function?
What is the difference between public, private, and protected inheritance?

What is virtual inheritance?

# What is placement new?
Operator new allocates memory from the heap. Standard C++ also supports placement new operator, which constructs an object on a pre-allocated buffer. This is useful when building a memory pool, a garbage collector or simply when performance and exception safety are paramount (there's no danger of allocation failure since the memory has already been allocated, and constructing an object on a pre-allocated buffer takes less time):

void placement() {

char *buf = new char[1000]; //pre-allocated buffer
string *p = new (buf) string("hi"); //placement new
string *q = new string("hi"); //ordinary heap allocation
cout< c_str()< c_str();



What is the difference between operator new and the new operator?
What is exception handling?
Explain what happens when an exception is thrown in C++.
What happens if an exception is not caught?
What happens if an exception is throws from an object's constructor?
What happens if an exception is throws from an object's destructor?
What are the costs and benefits of using exceptions?
When would you choose to return an error code rather than throw an exception?
What is a template?
What is partial specialization or template specialization?
How can you force instantiation of a template?
What is an iterator?
What is an algorithm (in terms of the STL/C++ standard library)?
What is std::auto_ptr?
What is wrong with this statement? std::auto_ptr ptr(new char[10]);
It is possible to build a C++ compiler on top of a C compiler. How would you do this? (I was asking him how cfront was put together.)

# How does the Assignment operator work?
The assignment operator has five steps:
Test for assignment to self.
Free up existing memory. (delete)
Allocate new memory.
Copy.
Return *this;


Every class that has external resources (dynamic memory) should implement the destructor, assignment operator, and copy constructor.
# Where is the copy constructor used:
Initializing variables.
Passing function argument values.
Returning values from a function.

Polymorphism

Polymorphism is the ability of a pointer or reference to a base class type to behave in different ways when it is used to manipulate objects of different subtypes of that base class. The first requirement for polymorphism is that the objects must be accessed via pointer or reference. A second requirement for polymorphism to work is that the methods whose polymorphic behavior is desired must be declared as virtual. Overridden methods not declared as virtual will behave correctly only for statically bound objects.For base class pointers or references bound to objects during execution, polymorphism will not be seen if a method is not declared virtual. That means that the base class method will be used rather than the subclass method even if the subclass overrides the method.

Virtual Functions

Any base class method intended to be overridden in any subclass should be declared as virtual.
Virtual is optional, but recommended in subclasses
Polymorphism in C++ works only with pointers and references and only with methods declared as virtual.
If a class declares any virtual methods, the destructor of the class should be declared as virtual as well. This ensures that regardless of the actual subclass of an object accessed via a base class pointer or reference, the correct destructor will clean it up.

In Java, all methods are virtual by default.

class BaseClass
{
virtual void functionName();
virtual ~BaseClass() {}
};

Inheritance

Inheritance defines an "is a" relationship. The derived class is a type of its base class. A derived class inherits both the data members and methods of its base class. It may also define additional members and methods that support specialized functionality.

class DerivedClass : public BaseClass
{
....
};
The parts of a class that are declared public can be accessed by the class itself, publicly derived subclasses, and other classes, functions and code. The parts of a class declared as protected can be accessed by the class itself and by publicly derived subclasses. The parts of a class declared as private can be accessed only by the class itself.
Constructors, Copy constructors, and Destructors are not inherited.
The base class part of an object is always constructed first and destroyed last. The subclass part of an object is constructed last and destroyed first.

Argument passing

Base () : Age(30), Name("Srujan") {}
Base(int w) : Age(w), Name("Srujan") {}
BAse(int w, string f) : Age(w), Name(f) {}

Derived() {}
Derived(int w) : Base(w) {}
Derived(int w, string f) : Base(w,f) {}

Overriding Methods

A derived class can use the methods of its base class(es), or it can override them. The method in the derived class must have the same signature and return type as the base class method to override. The signature is number and type of arguments and the constantness (const, non- const) of the method. When an object of the base class is used, the base class method is called. When an object of the subclass is used, its version of the method is used if the method is overridden. If the base class had overloaded a particular method, overriding a single one of the overloads in the derived will hide the rest of the overloaded methods to the derived classes. Overridden methods should usually be virtual.

Operator Overloading

Operator overloading provides a way to define and use operators such as +, -, *, /, and [] for user defined types such as classes and enumerations.

Operator Overloading Rules :

Only existing operator symbols may be overloaded. New symbols cannot be defined.
The operators ::, .*, . and ?: cannot be overloaded.
Operators =, [], () and -> can only be defined as members of a class and not as global functions.
At least one operand for any overload must be a class or enumeration type. One cannot overload operators involving only built-in data types such as "int".
The number of operands for an operator cannot be changed. For example, addition, +, may not be defined to take other than two arguments regardless of data type.
Operator Overloading does not change operator precedence.

class Number
{
public:
Number(int num = 0)
{
this->number = num;
}
Number operator+(const Number &other)
{
Number temp;
temp.number = this->number + other.number;
return temp;
}
// in the below case if you do just a++ then the return is simply ignored, but incase of c = a++ the return assigned "a"
// For the prefix method, the calling object exists before, during and after the method execution, so a reference can be used to avoid extra copies.

Number& operator++() // simple or regular prefix increment
{
number += number;
return *this;
}
//For postfix method, the 'temp' object goes out of scope when the ++ method returns. Returning a reference to an out of scope object will coredump.
Number operator++(int)// postfix, we create a dummy overloaded function(for uniqueness) and return by value so that a copy is made and returned
{
Number temp(number);
this->number += number;
return temp;
}

// we declare this here but the actual method definition can be written anywhere as long as the NUMBER class is declared.
friend Number operator+(const int i, const Fraction f);

void print() { cout << number<< endl; }
private:
int number =0 ;
};

int main() {
Number a(2),b(4),c;
c = a + b;
c.print(); // output will be 2 + 4 = 6
c = ++a; //prefix
c.print(); // output will be 12
c = a++;// postfix
c.print(); // output will still be 12
a.print(); // output will be 24

}

Friend classes

A method declared as a friend to a class can access the non-public members and methods of that class, as well as the public members and methods of that class.
In order to allow an external function to have access to the private and protected members of a class a prototye of the external function preceded by the keyword 'friend' should be declared within the class that shares its members.

From the classes described in the Operator Overloading example

Number operator+(const float i, const Number f)
{
Number temp;
temp.number = f.number;
temp.num = f.num + abs(i);
return temp;
}
int main() {
Number a(2), c;
c = 4.123 + a;
c.print(); // output will be 4 + 2= 6
}

Friend classes (friend)
We can also define a class as friend of another one, allowing the second one access to the protected and private members of the first.

class Square; // pre decleration
class Rectangle
{
int width, height;
public:
int area (void) {return (width * height);}
void convert (Square a);
};

class Square
{
int side;
public:
void set_side (int a) {side=a;}
friend class Rectangle;
};

void Rectangle::convert (Square a) {
width = a.side;
height = a.side;
}

int main () {
Square sqr;
Rectangle rect;
sqr.set_side(4);
rect.convert(sqr);
cout << rect.area(); // will print 16
return 0;
}

Rectangle is a friend of Square so Rectangle can access the protected and private members of Square, more concretely Square::side, that defines the square side width.

Bit Fields

About bit fields in C/C++...

A Bit Field allows us to create variable names for individual bits. Allocation is done from RIGHT to LEFT.

struct bit_field
{
unsigned int Firstbit :1;
unsigned int Secondbit :1;
unsigned int Next2bits :2;
unsigned int Last4bits :4;
} bitField;


{[15][14][13][12][11][10][9][8][7][6][5][4][3][2][1][0]}
[0] -- Firstbit
[1] -- Secondbit
[3][2] -- Next2bits
[7][6][5][4] -- Last4bits
[15][14][13][12][11][10][9][8] -- Un Used bits.


If you use just "int" instead of "unsigned int" then the leftmost bit in the bitfield in question will be a sign bit.
It can be used as follows : printf(bitField.Firstbit);