Tuesday, December 18, 2012

Creating Data Source Object in Windows for type 1 JDBC Driver


database is a structured collection of data. The data are typically organized to model relevant aspects of reality (for example, the availability of rooms in hotels), in a way that supports processes requiring this information (for example, finding a hotel with vacancies).

Datasource is a name given to the connection set up to a database from a server. The name is commonly used when creating a query to the database.
JDBC is a Java-based data access technology (Java Standard Edition platform) from Sun Microsystems. It is an acronym as it is unofficially referred to as Java Database Connectivity.

The JDBC type 1 driver, also known as the JDBC-ODBC bridge, is a database driver implementation that employs theODBC driver to connect to the database. The driver converts JDBC method calls into ODBC function calls.The driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the underlying operating system the JVM is running upon.
Functions :
Translates a query by JDBC into a corresponding ODBC query, which is then handled by the ODBC driver.
Advantages :
Almost any database for which ODBC driver is installed, can be accessed.
Disadvantages :
  • Performance overhead since the calls have to go through the jdbc Overhead bridge to the ODBC driver,then to the native db connectivity interface (thus may be slower than othe types of driver).
  • The ODBC driver needs to be intalled on the client machine.
  • Not suitable fo rapplets, because the ODBC driver needs to be intalled on the client.

Steps to Create Object Data Source :


Step 1 :
Search for ODBC Data Source Administrator in the Start menu.
Select ODBC Data Source Administrator.

Step 2 :
Window : ODBC Data Source Administrator
Under the "User DSN" tab click "Add" Button.
Step 3 :
Window : Create New Data Source
Select " Microsoft Access Driver(*.mdb,*.accdb)"
Click "Finish"
If you can find the option it is due to the Driver Problems , maybe because your system has 64 bit operating system.
To build and run an application as a 32-bit application on a 64-bit operating system, you must create the ODBC data source with the ODBC Administrator in %windir%\SysWOW64\odbcad32.exe.


Step 4 :
Window : ODBC Microsoft Access Setup
Name the Data Source. (Here CMDSN)
DSN name is Case sensitive so be careful.
It should be the same as the DSN name in you Java Program. 
Then click "Select"






Step 4 :
Window: Select Database
Browse the Directories for you MS Access Database.
Then Select the required Database in the left panel and the click "OK"
The "List Files of type:" should be "Access Databases"







Step 4:
Window: ODBC Microsoft Access Setup
Click "OK"
The Selected file Path and Name is shown beside the "Database" Label
Click "OK" 
DONE

NEXT:
You can now Manipulate you tables through you Java Program.





[edit]


Java Job Interview Questions Difficulty level-TOUGH


Questions 1 to 40


1.Is “abc” a primitive value?
Ans: The String literal “abc” is not a primitive value. It is a String object.

2.What restrictions are placed on the values of each case of a switch statement?
Ans: During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

3.What modifiers may be used with an interface declaration?
Ans: An interface may be declared as public or abstract.

4.Is a class a subclass of itself?
Ans: A class is a subclass of itself.

5.What is the difference between a while statement and a do statement?
Ans: A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

6.What modifiers can be used with a local inner class?
Ans: A local inner class may be final or abstract.

7.What is the purpose of the File class?
Ans: The File class is used to create objects that provide access to the files and directories of a local file system.

8.Can an exception be re-thrown?
Ans: Yes, an exception can be re-thrown.

9.When does the compiler supply a default constructor for a class?
Ans: The compiler supplies a default constructor for a class if no other constructors are provided.

10.If a method is declared as protected, where may the method be accessed?
Ans: A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

11.Which non-Unicode letter characters may be used as the first character of an identifier?
Ans: The non-Unicode letter characters $ and _ may appear as the first character of an identifier

12.What restrictions are placed on method overloading?
Ans: Two methods may not have the same name and argument list but different return types.

13.What is casting?
Ans: There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

14.What is the return type of a program’s main() method?
Ans: A program’s main() method has a void return type.

15.What class of exceptions are generated by the Java run-time system?
Ans: The Java run-time system generates RuntimeException and Error exceptions.

16.What class allows you to read objects directly from a stream?
Ans: The ObjectInputStream class supports the reading of objects from input streams.

17.What is the difference between a field variable and a local variable?
Ans: A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.

18.How are this() and super() used with constructors?
Ans: this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor

19.What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution?
Ans: A method’s throws clause must declare any checked exceptions that are not caught within the body of the method.

20.Why are the methods of the Math class static?
Ans: So they can be invoked as if they are a mathematical code library.

21.What are the legal operands of the instanceof operator?
Ans: The left operand is an object reference or null value and the right operand is a class, interface, or array type.

22.What an I/O filter?
Ans: An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

23.If an object is garbage collected, can it become reachable again?
Ans: Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.

24.What are E and PI?
Ans: E is the base of the natural logarithm and PI is mathematical value pi.

25.Are true and false keywords?
Ans: The values true and false are not keywords.

26.What is the difference between the File and RandomAccessFile classes?
Ans: The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

27.What happens when you add a double value to a String?
Ans: The result is a String object.

28.What is your platform’s default character encoding?
Ans: If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.

29.Which package is always imported by default?
Ans: The java.lang package is always imported by default.

30.What interface must an object implement before it can be written to a stream as an object?
Ans: An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

31.How can my application get to know when a HttpSession is removed?
Ans: Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method. Create an instance of that class and put that instance in HttpSession.

32.Whats the difference between notify() and notifyAll()?
Ans: notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing a “writer” lock on a file might permit all “readers” to resume).

33.Why can’t I say just abs() or sin() instead of Math.abs() and Math.sin()?
Ans: The import statement does not bring methods into your local name space. It lets you abbreviate class names, but not get rid of them altogether. That’s just the way it works, you’ll get used to it. It’s really a lot safer this way.
However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn’t need to inherit from anything else, make it inherit from java.lang.Math. That *does* bring all the methods into your local name space. But you can’t use this trick in an applet, because you have to inherit from java.awt.Applet. And actually, you can’t use it on java.lang.Math at all, because Math is a “final” class which means it can’t be extended.

34.Why are there no global variables in Java?
Ans: Global variables are considered bad form for a variety of reasons: Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables), State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state, When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once. For these reasons, Java decided to ban global variables.

35.What does it mean that a class or member is final?
Ans: A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. Methods may be declared final as well. This means they may not be overridden in a subclass. Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it’s initialized, and it must include an initializer statement where it’s declared. For example, public final double c = 2.998; It’s also possible to make a static field final to get the effect of C++’s const statement or some uses of C’s #define, e.g. public static final double c = 2.998;

36.What does it mean that a method or class is abstract?
Ans: An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:

public abstract class Container extends Component {

Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example,

public abstract float price();

Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.


37.What is a transient variable?
Ans: transient variable is a variable that may not be serialized.

38.How are Observer and Observable used?
Ans: 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

39.Can a lock be acquired on a class?
Ans: Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.

40.What state does a thread enter when it terminates its processing?
Ans: When a thread terminates its processing, it enters the dead state.

Database Management System DBMS


What is Database ?

"A database is a structured collection of data. The data are typically organized to model relevant aspects of reality (for example, the availability of rooms in hotels), in a way that supports processes requiring this information (for example, finding a hotel with vacancies)." - Wikipedia



What is a Database Management System?

" A Database Management System (DBMS) is a set of programs that enables you to store, modify, and extract information from a database, it also provides users with tools to add, delete, access, modify, and analyze data stored in one location. " -Wikipedia


A DBMS is a software (and hardware) package providing the
following services:
• A data definition language (DDL).
• A data manipulation language (DML).
• Efficiency in query response and storage space.
• Maintenance of integrity and consistency.
• Concurrency control and data sharing.
• Transaction management (commit and rollback).
• Recovery from failure.
• Security.
• Data administration facilities.
• Adherence to standards (e.g. SQL).


Why Do We Need DBMS ?

Assume that a DBMS is a software (and hardware) package that
handles all the interaction of an application with the database.
1. It saves programmer time and maintenance.
2. It provides data independence.
3. It provide provides programmers with various tools.

Basic Concepts in Data Management


Field
Individual piece of data
Made up of one or more bytes, or characters
Examples: name, address, phone number
Record
Fields that are grouped together for a specific purpose
Primary key
A field, or group of fields, that uniquely identifies an individual record
Student id number for records describing students

DBMS Functions

Manage stored data
Transform data into information
Transforms the way data is physically stored into whatever logical view of the data that the
user chooses
Hides the physical details of how the data is actually stored
Provide security
DBMSs control who can add, view, change, or delete data in the database
Allow multiuser access
Controls concurrency of access to data
Prevents one user from accessing data that has not been completely updated
Programming and Query Language Ability
Data Definition Language (DDL) to define and modify the structure of the data (physical
and logical views)
Data Manipulation Language (DML) to allow the users to enter, modify, delete, and
retrieve data from thedatabase
Provide a Data Dictionary
Metadata – data about data
Data dictionary contains metadata
 – data about the characteristics of databases controlled by the DBMS


Database Models

•Database model – a representation of the relationship between structures in a database
•Four common database models
Flat file model
Hierarchical, or tree structure, model
Network model
Relational model (this one is the most common)

SQL

Structured Query Language (SQL)
–Standard DDL and DML for a relational database
Used for :
Creating tables
Deleting tables
Add, change, delete, and retrieve data
Do a SQL Crash Course 

Data Mining

•Process of applying analytical and statistical methods to data to find patterns
•Retailers use data mining to determine purchasing patterns
•Pro football teams use data mining to scout the opposition






Most Commonly used Database Softwares :

  • MySql
  • Oracle 10g
  • MS Sql Server
  • MS Access
Reference Prentice Hall Inc

Java Tutorial : Crash Course


Java Tutorial 

Java is:
platform independent programming language
similar to C++ in syntax


Interesting features:
  • automatic type checking,
  • automatic garbage collection,
  • simplifies pointers; 
  • no directly accessible pointer to memory, 
  • simplified network access, 
  • multi-threading!

How it works .......
Platform Independent Why ?
Only depends on the Java Virtual Machine (JVM),
code is compiled to bytecode, which is interpreted by the resident JVM,
JIT (just in time) compilers attempt to increase speed.
Security:
Pointer denial - reduces chances of virulent programs corrupting host,
Applets even more restricted -
May not run local executables,
Read or write to local file system,
Communicate with any server other than the originating server.
Object-Oriented
Java supports OOD
  • Polymorphism
  • Inheritance
  • Encapsulation

Java programs contain nothing but definitions and instantiations of classes
Everything is encapsulated in a class!
Java Advantages
  • Portable - Write Once, Run Anywhere
  • Security has been well thought through
  • Robust memory management
  • Designed for network programming
  • Multi-threaded (multiple simultaneous tasks)
  • Dynamic & extensible (loads of libraries)


Basic Java Syntax :

Primitive Types and Variables :
boolean, char, byte, short, int, long, float, double etc.
These basic (or primitive) types are the only types that are not objects (due to performance issues).
This means that you don’t use the new operator to create a primitive variable.
Declaring primitive variables:
float initVal;
int retVal, index = 2;
double gamma = 1.2, brightness
boolean valueOk = false;

Initialisation :
If no value is assigned prior to use, then the compiler will give an error
Java sets primitive variables to zero or false in the case of a boolean variable
All object references are initially set to null
An array of anything is an object
Set to null on declaration
Elements to zero false or null on creation

Declarations :
int index = 1.2;   // compiler error
boolean retOk = 1;  // compiler error
double fiveFourths = 5 / 4;   // no error!
float ratio = 5.8f;  // correct
double fiveFourths = 5.0 / 4.0;  // correct
1.2f is a float value accurate to 7 decimal places.
1.2 is a double value accurate to 15 decimal places.
Assignment
All Java assignments are right associative
  int a = 1, b = 2, c = 5
  a = b = c
   System.out.print(
  “a= “ + a + “b= “ + b + “c= “ + c)
What is the value of a, b & c
Done right to left: a = (b = c);
Basic Mathematical Operators
* / % + - are the mathematical operators
* / % have a higher precedence than + or -
double myVal = a + b % d – c * d / b;
Is the same as:
double myVal = (a + (b % d)) –
    ((c * d) / b);

Statements & Blocks :
A simple statement is a command terminated by a semi-colon:
  name = “Fred”;
A block is a compound statement enclosed in curly brackets:
  {
  name1 = “Fred”; name2 = “Bill”;
  }
Blocks may contain other blocks

Flow of Control :
Java executes one statement after the other in the order they are written
Many Java statements are flow control statements:
Alternation:   if, if else, switch
Looping:  for, while, do while
Escapes:  break, continue, return
If – The Conditional Statement
The if statement evaluates an expression and if that evaluation is true then the specified action is taken
if ( x < 10 ) x = 10;
If the value of x is less than 10, make x equal to 10
It could have been written:
if ( x < 10 )
x = 10;
Or, alternatively:
if ( x < 10 ) { x = 10; }

Relational Operators :
  • ==  Equal 
  • !=  Not equal
  • >=  Greater than or equal
  • <=  Less than or equal
  • >  Greater than
  • <  Less than

If… else
The if … else statement evaluates an expression and performs one action if that evaluation is true or a different action if it is false.
   if (x != oldx) {
  System.out.print(“x was changed”);
}
else {
  System.out.print(“x is unchanged”);
}
Nested if … else
if ( myVal > 100 ) {
  if ( remainderOn == true) {
    myVal = mVal % 100;
  }
  else {
  myVal = myVal / 100.0;
  }
}
else
{
  System.out.print(“myVal is in range”);
}
else if
Useful for choosing between alternatives:
if ( n == 1 ) {
  // execute code block #1
}
else if ( j == 2 ) {
  // execute code block #2
}
else {
  // if all previous tests have failed, execute code block #3
}

CORRECT!
if( i == j ) {
  if ( j == k )
  System.out.print(
      “i equals k”);
}
else
  System.out.print(“i is not equal to j”);  // Correct!
The switch Statement
switch ( n ) {
  case 1:
  // execute code block #1
  break;
  case 2:
  // execute code block #2
  break;
  default:
  // if all previous tests fail then          //execute code block #4
  break;
}
The for loop
Loop n times
for ( i = 0; i < n; n++ ) {
  // this code body will execute n times
  // ifrom  0 to n-1
}
Nested for:
for ( j = 0; j < 10; j++ ) {
  for ( i = 0; i < 20; i++ ){
  // this code body will execute 200 times
  }
}
 
while loops
while(response == 1) {
  System.out.print( “ID =” + userID[n]);
  n++;
  response = readInt( “Enter “);
}
do {… } while loops
do {
  System.out.print( “ID =” + userID[n] );
  n++;
  response = readInt( “Enter ” );
}while (response == 1);
Break
A break statement causes an  exit from the innermost containing while, do, for or switch statement.
for ( int i = 0; i < maxID, i++ ) {
  if ( userID[i] == targetID ) {
  index = i;
  break;
  }
}  // program jumps here after break
Continue
Can only be used with while, do or for.
The continue statement causes the innermost loop to start the next iteration immediately
for ( int i = 0; i < maxID; i++ ) {
  if ( userID[i] != -1 ) continue;
  System.out.print( “UserID ” + i + “ :” +     userID);
}

Arrays
Am array is a list of similar things
An array has a fixed:
name
type
length
These must be declared when the array is created.
Arrays sizes cannot be changed during the execution of the code
Declaring Arrays
int myArray[];
declares myArray to be an array of integers
myArray = new int[8];
sets up 8 integer-sized spaces in memory, labelled myArray[0] to myArray[7]
int myArray[] = new int[8];
combines the two statements in one line
Assigning Values
refer to the array elements by index to store values in them.
myArray[0] = 3;
myArray[1] = 6;
myArray[2] = 3;   ...
can create and initialise in one step:
int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};
Iterating Through Arrays
for loops are useful when dealing with arrays:
for (int i = 0; i < myArray.length; i++) {
  myArray[i] = getsomevalue();
}
Arrays of Objects
So far we have looked at an array of primitive types.
integers
could also use doubles, floats, characters…
Often want to have an array of objects
Students, Books, Loans ……
Need to follow 3 steps.
Declaring the Array
1. Declare the array
  private Student studentList[];
this declares studentList
2 .Create the array
  studentList = new Student[10];
this sets up 10 spaces in memory that can hold references to Student objects
3. Create Student objects and add them to the array: studentList[0] = new Student("george", "Computing");

Java Methods & Classes
Classes ARE Object Definitions
OOP - object oriented programming
code built from objects
Java these are called classes
Each class definition is coded in a separate .java file
Name of the object must match the class/object name    

The three principles of OOP
Encapsulation
Objects hide their functions (methods) and data (instance variables)
Inheritance
Each subclass inherits all variables of its superclass
Polymorphism
Interface same despite different data types

Methods :
A method is a named sequence of code that can be invoked by other Java code.
A method takes some parameters, performs some computations and then optionally returns a value (or object).
Methods can be used as part of an expression statement.
 
public float convertCelsius(float tempC) {
  return( ((tempC * 9.0f) / 5.0f) + 32.0 );
  }
Method Signatures
A method signature specifies:
The name of the method.
The type and name of each parameter.
The type of the value (or object) returned by the method.
The checked exceptions thrown by the method.
Various method modifiers.
modifiers type name ( parameter list ) [throws exceptions ]
public float convertCelsius (float tCelsius ) {}
public boolean setUserInfo ( int i, int j, String name ) throws IndexOutOfBoundsException {}
Public/private
Methods/data may be declared public or private meaning they may or may not be accessed by code in other classes …
Good practice:
keep data private
keep most methods private
well-defined interface between classes - helps to eliminate errors
Using objects
Here, code in one class creates an instance of another class and does something with it …
Fruit plum=new Fruit();
int cals;
cals = plum.total_calories();
Dot operator allows you to access (public) data/methods inside Fruit class
Constructors
The line
plum = new Fruit();
invokes a constructor method with which you can set the initial data of an object
You may choose several different type of constructor with different argument lists
 eg Fruit(), Fruit(a) ...
Overloading
Can have several versions of a method in class with different types/numbers of arguments
  Fruit() {grams=50;}
    Fruit(a,b) { grams=a; cals_per_gram=b;}
By looking at arguments Java decides which version to use
Java Development Kit
javac - The Java Compiler
java -   The Java Interpreter
jdb -     The Java Debugger
appletviewer -Tool to run the applets
javap - to print the Java bytecodes
javaprof - Java profiler
javadoc - documentation generator
javah - creates C header files
Stream Manipulation
Streams and I/O
basic classes for file IO
FileInputStream, for reading from a file
FileOutputStream, for writing to a file
Example:
Open a file "myfile.txt" for reading
FileInputStream fis = new FileInputStream("myfile.txt");
Open a file "outfile.txt" for writing
FileOutputStream fos = new FileOutputStream ("myfile.txt");

General IO stream manipulation utilities.

 This class provides static utility methods for input/output operations.
 closeQuietly - these methods close a stream ignoring nulls and exceptions
 read - these methods read data from a stream
 write - these methods write data to a stream
 copy - these methods copy all the data from one stream to another
 contentEquals - these methods compare the content of two streams


Object Serialization :

Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link. The byte stream can then be deserialised - converted into a replica of the original object.
import java.io.*; 
public class SerializationDemo { 
public static void main(String args[]) { 
// Object serialization 
try { 
MyClass object1 = new MyClass("Hello", -7, 2.7e10); 
System.out.println("object1: " + object1); 
FileOutputStream fos = new FileOutputStream("serial"); 
ObjectOutputStream oos = new ObjectOutputStream(fos); 
oos.writeObject(object1); 
oos.flush(); 
oos.close(); 

catch(Exception e) { 
System.out.println("Exception during serialization: " + e); 
System.exit(0); 

// Object deserialization 
try { 
MyClass object2; 
FileInputStream fis = new FileInputStream("serial"); 
ObjectInputStream ois = new ObjectInputStream(fis); 
object2 = (MyClass)ois.readObject(); 
ois.close(); 
System.out.println("object2: " + object2); 

catch(Exception e) { 
System.out.println("Exception during deserialization: " + 
e); 
System.exit(0); 



class MyClass implements Serializable { 
String s; 
int i; 
double d; 
public MyClass(String s, int i, double d) { 
this.s = s; 
this.i = i; 
this.d = d; 

public String toString() { 
return "s=" + s + "; i=" + i + "; d=" + d; 

}