Database Design

Database Design Considerations

Designing a database requires an understanding of both the business functions you want to model and the database concepts and features used to represent those business functions.

It is important to accurately design a database to model the business because it can be time consuming to change the design of a database significantly once implemented. A well-designed database also performs better.
When designing a database, consider:

1) The purpose of the database and how it affects the design. Create a database plan to fit your purpose.
2) Database normalization rules that prevent mistakes in the database design.
Protection of your data integrity.
3) Security requirements of the database and user permissions.
4 ) Performance needs of the application. You must ensure that the database design takes advantage of Microsoft® SQL Server™ 2000 features that improve performance.
5) Achieving a balance between the size of the database and the hardware configuration is also important for performance.
6 ) Maintenance.
7) Estimating the size of a database.

Creating a Database Plan

The first step in creating a database is creating a plan that serves both as a guide to be used when implementing the database and as a functional specification for the database after it has been implemented. The complexity and detail of a database design is dictated by the complexity and size of the database application as well as the user population.
The nature and complexity of a database application, as well as the process of planning it, can vary greatly. A database can be relatively simple and designed for use by a single person, or it can be large and complex and designed, for example, to handle all the banking transactions for hundreds of thousands of clients. In the first case, the database design may be little more than a few notes on some scratch paper. In the latter case, the design may be a formal document with hundreds of pages that contain every possible detail about the database.

In planning the database, regardless of its size and complexity, use these basic steps:
1) Gather information.
2) Identify the objects.
3) Model the objects.
4) Identify the types of information for each object.
5) Identify the relationships between objects.

Gathering Information

Before creating a database, you must have a good understanding of the job the database is expected to perform. If the database is to replace a paper-based or manually performed information system, the existing system will give you most of the information you need. It is important to interview everyone involved in the system to find out what they do and what they need from the database. It is also important to identify what they want the new system to do, as well as to identify the problems, limitations, and bottlenecks of any existing system. Collect copies of customer statements, inventory lists, management reports, and any other documents that are part of the existing system, because these will be useful to you in designing the database and the interfaces.

Identifying the Objects

During the process of gathering information, you must identify the key objects or entities that will be managed by the database. The object can be a tangible thing, such as a person or a product, or it can be a more intangible item, such as a business transaction, a department in a company, or a payroll period. There are usually a few primary objects, and after these are identified, the related items become apparent. Each distinct item in your database should have a corresponding table.
The primary object in the pubs sample database included with Microsoft® SQL Server™ 2000 is a book. The objects related to books within this company's business are the authors who write the books, the publishers who manufacture the books, the stores which sell them, and the sales transactions performed with the stores. Each of these objects is a table in the database.

Modeling the Objects

As the objects in the system are identified, it is important to record them in a way that represents the system visually. You can use your database model as a reference during implementation of the database.
For this purpose, database developers use tools that range in technical complexity from pencils and scratch paper to word processing or spreadsheet programs, and even to software programs specifically dedicated to the job of data modeling for database designs. Whatever tool you decide to use, it is important that you keep it up-to-date.
SQL Server Enterprise Manager includes visual design tools such as the Database Designer that can be used to design and create objects in the database.

Identifying the Types of Information for Each Object

After the primary objects in the database have been identified as candidates for tables, the next step is to identify the types of information that must be stored for each object. These are the columns in the object's table. The columns in a database table contain a few common types of information:

1) Raw data columns
These columns store tangible pieces of information, such as names, determined by a source external to the database.

2) Categorical columns
These columns classify or group the data and store a limited selection of data such as true/false, married/single, VP/Director/Group Manager, and so on.

3) Identifier columns
These columns provide a mechanism to identify each item stored in the table. These columns often have id or number in their names (for example, employee_id, invoice_number, and publisher_id). The identifier column is the primary component used by both users and internal database processing for gaining access to a row of data in the table. Sometimes the object has a tangible form of ID used in the table (for example, a social security number), but in most situations you can define the table so that a reliable, artificial ID can be created for the row.

4)Relational or referential columns
These columns establish a link between information in one table and related information in another table. For example, a table that tracks sales transactions will commonly have a link to the customers table so that the complete customer information can be associated with the sales transaction.

Identifying the Relationships Between Objects

One of the strengths of a relational database is the ability to relate or associate information about various items in the database. Isolated types of information can be stored separately, but the database engine can combine data when necessary. Identifying the relationships between objects in the design process requires looking at the tables, determining how they are logically related, and adding relational columns that establish a link from one table to another.

For example, the designer of the pubs database has created tables for titles and publishers in the database. The titles table contains information for each book: an identifier column named title_id; raw data columns for the title, the price of the book, and the publishing date; and some columns with sales information for the book. The table contains a categorical column named type, which allows the books to be grouped by the type of content in the book. Each book also has a publisher, but the publisher information is in another table; therefore, the titles table has a pub_id column to store just the ID of the publisher. When a row of data is added for a book, the publisher ID is stored with the rest of the book information.
Online Transaction Processing vs. Decision Support

Many applications fall into two main categories of database applications:


Online transaction processing (OLTP)Decision support


The characteristics of these application types have a dramatic effect on the design considerations for a database.
Online Transaction Processing
Online Transaction processing database applications are optimal for managing changing data, and usually have a large number of users who will be simultaneously performing transactions that change real-time data. Although individual requests by users for data tend to reference few records, many of these requests are being made at the same time. Common examples of these types of databases are airline ticketing systems and banking transaction systems. The primary concerns in this type of application are concurrency and atomicity.
Concurrency controls in a database system ensure that two users cannot change the same data, or that one user cannot change a piece of data before another user is done with it. For example, if you are talking to an airline ticket agent to reserve the last available seat on a flight and the agent begins the process of reserving the seat in your name, another agent should not be able to tell another passenger that the seat is available.
Atomicity ensures that all of the steps involved in a transaction complete successfully as a group. If any step fails, no other steps should be completed. For example, a banking transaction may involve two steps: taking funds out of your checking account and placing them into your savings account. If the step that removes the funds from your checking account succeeds, you want to make sure that the funds are placed into your savings account or put back into your checking account.
Online Transaction Processing Design Considerations

Transaction processing system databases should be designed to promote:
Good data placement.
I/O bottlenecks are a big concern for OLTP systems due to the number of users modifying data all over the database. Determine the likely access patterns of the data and place frequently accessed data together. Use filegroups and RAID (redundant array of independent disks) systems to assist in this.
Short transactions to minimize long-term locks and improve concurrency.
Avoid user interaction during transactions. Whenever possible, execute a single stored procedure to process the entire transaction. The order in which you reference tables within your transactions can affect concurrency. Place references to frequently accessed tables at the end of the transaction to minimize the duration that locks are held.
Online backup.
OLTP systems are often characterized by continuous operations (24 hours a day, 7 days a week) for which downtime is kept to an absolute minimum. Although Microsoft® SQL Server™ 2000 can back up a database while it is being used, schedule the backup process to occur during times of low activity to minimize effects on users.
High normalization of the database.

Reduce redundant information as much as possible to increase the speed of updates and hence improve concurrency. Reducing data also improves the speed of backups because less data needs to be backed up.

Little or no historical or aggregated data.

Data that is rarely referenced can be archived into separate databases, or moved out of the heavily updated tables into tables containing only historical data. This keeps tables as small as possible, improving backup times and query performance.
Careful use of indexes.
Indexes must be updated each time a row is added or modified. To avoid over-indexing heavily updated tables, keep indexes narrow. Use the Index Tuning Wizard to design your indexes.
Optimum hardware configuration to handle the large numbers of concurrent users and quick response times required by an OLTP system.

Decision Support

Decision-support database applications are optimal for data queries that do not change data. For example, a company can periodically summarize its sales data by date, sales region, or product and store this information in a separate database to be used for analysis by senior management. To make business decisions, users need to be able to determine trends in sales quickly by querying the data based on various criteria. However, they do not need to change this data. The tables in a decision-support database are heavily indexed, and the raw data is often preprocessed and organized to support the various types of queries to be used. Because the users are not changing data, concurrency and atomicity issues are not a concern; the data is changed only by periodic, bulk updates made during off-hour, low-traffic times in the database.

Decision Support Design Considerations

Decision-support system databases should be designed to promote:
Heavy indexing.
Decision-support systems have low update requirements but large volumes of data. Use many indexes to improve query performance.
Denormalization of the database.
Introduce preaggregated or summarized data to satisfy common query requirements and improve query response times.
Use of a star or snowflake schema to organize the data within the database.

Normalization

The logical design of the database, including the tables and the relationships between them, is the core of an optimized relational database. A good logical database design can lay the foundation for optimal database and application performance. A poor logical database design can impair the performance of the entire system.
Normalizing a logical database design involves using formal methods to separate the data into multiple, related tables. A greater number of narrow tables (with fewer columns) is characteristic of a normalized database. A few wide tables (with more columns) is characteristic of an nonnomalized database.
Reasonable normalization often improves performance. When useful indexes are available, the Microsoft® SQL Server™ 2000 query optimizer is efficient at selecting rapid, efficient joins between tables.
1 Some of the benefits of normalization include:
2 Faster sorting and index creation.
3 A larger number of clustered indexes.
4 Narrower and more compact indexes.
5 Fewer indexes per table, which improves the performance of INSERT, UPDATE, and DELETE statements.

Fewer null values and less opportunity for inconsistency, which increase database compactness.
As normalization increases, so do the number and complexity of joins required to retrieve data. Too many complex relational joins between too many tables can hinder performance. Reasonable normalization often includes few regularly executed queries that use joins involving more than four tables.
Sometimes the logical database design is already fixed and total redesign is not feasible. Even then, however, it might be possible to normalize a large table selectively into several smaller tables. If the database is accessed through stored procedures, this schema change could take place without affecting applications. If not, it might be possible to create a view that hides the schema change from the applications.

Achieving a Well-Designed Database

In relational-database design theory, normalization rules identify certain attributes that must be present or absent in a well-designed database. A complete discussion of normalization rules goes well beyond the scope of this topic. However, there are a few rules that can help you achieve a sound database design:
A table should have an identifier.

The fundamental rule of database design theory is that each table should have a unique row identifier, a column or set of columns used to distinguish any single record from every other record in the table. Each table should have an ID column, and no two records can share the same ID value. The column or columns serving as the unique row identifier for a table is the primary key of the table.
A table should store only data for a single type of entity.

Attempting to store too much information in a table can prevent the efficient and reliable management of the data in the table. In the pubs database in SQL Server 2000, the titles and publishers information is stored in two separate tables. Although it is possible to have columns that contain information for both the book and the publisher in the titles table, this design leads to several problems. The publisher information must be added and stored redundantly for each book published by a publisher. This uses extra storage space in the database. If the address for the publisher changes, the change must be made for each book. And if the last book for a publisher is removed from the title table, the information for that publisher is lost.

In the pubs database, with the information for books and publishers stored in the titles and publishers tables, the information about the publisher has to be entered only once and then linked to each book. Therefore, if the publisher information is changed, it must be changed in only one place, and the publisher information will be there even if the publisher has no books in the database.
A table should avoid nullable columns.

Tables can have columns defined to allow null values. A null value indicates that there is no value. Although it can be useful to allow null values in isolated cases, it is best to use them sparingly because they require special handling that increases the complexity of data operations. If you have a table with several nullable columns and several of the rows have null values in the columns, you should consider placing these columns in another table linked to the primary table. Storing the data in two separate tables allows the primary table to be simple in design but able to accommodate the occasional need for storing this information.
A table should not have repeating values or columns.

The table for an item in the database should not contain a list of values for a specific piece of information. For example, a book in the pubs database might be coauthored. If there is a column in the titles table for the name of the author, this presents a problem. One solution is to store the name of both authors in the column, but this makes it difficult to show a list of the individual authors. Another solution is to change the structure of the table to add another column for the name of the second author, but this accommodates only two authors. Yet another column must be added if a book has three authors.

If you find that you need to store a list of values in a single column, or if you have multiple columns for a single piece of data (au_lname1, au_lname2, and so on), you should consider placing the duplicated data in another table with a link back to the primary table. The pubs database has a table for book information and another table that stores only the ID values for the books and the IDs of the authors of the books. This design allows any number of authors for a book without modifying the definition of the table and allocates no unused storage space for books with a single author.

Data Integrity

Enforcing data integrity ensures the quality of the data in the database. For example, if an employee is entered with an employee_id value of 123, the database should not allow another employee to have an ID with the same value. If you have an employee_rating column intended to have values ranging from 1 to 5, the database should not accept a value of 6. If the table has a dept_id column that stores the department number for the employee, the database should allow only values that are valid for the department numbers in the company.

Two important steps in planning tables are to identify valid values for a column and to decide how to enforce the integrity of the data in the column. Data integrity falls into these categories:

1 Entity integrity
2 Domain integrity
3 Referential integrity
4 User-defined integrity

Entity Integrity

Entity integrity defines a row as a unique entity for a particular table. Entity integrity enforces the integrity of the identifier column(s) or the primary key of a table (through indexes, UNIQUE constraints, PRIMARY KEY constraints, or IDENTITY properties).

Domain Integrity

Domain integrity is the validity of entries for a given column. You can enforce domain integrity by restricting the type (through data types), the format (through CHECK constraints and rules), or the range of possible values (through FOREIGN KEY constraints, CHECK constraints, DEFAULT definitions, NOT NULL definitions, and rules).

Referential Integrity

Referential integrity preserves the defined relationships between tables when records are entered or deleted. In Microsoft® SQL Server™ 2000, referential integrity is based on relationships between foreign keys and primary keys or between foreign keys and unique keys (through FOREIGN KEY and CHECK constraints). Referential integrity ensures that key values are consistent across tables. Such consistency requires that there be no references to nonexistent values and that if a key value changes, all references to it change consistently throughout the database.
When you enforce referential integrity, SQL Server prevents users from:
Adding records to a related table if there is no associated record in the primary table.
Changing values in a primary table that result in orphaned records in a related table.
Deleting records from a primary table if there are matching related records.
For example, with the sales and titles tables in the pubs database, referential integrity is based on the relationship between the foreign key (title_id) in the sales table and the primary key (title_id) in the titles table.

User-Defined Integrity

User-defined integrity allows you to define specific business rules that do not fall into one of the other integrity categories. All of the integrity categories support user-defined integrity (all column- and table-level constraints in CREATE TABLE, stored procedures, and triggers).

Database Performance

When you design a database, you must ensure that the database performs all the important functions correctly and quickly. Some performance issues can be resolved after the database is in production, but other performance issues may be the result of a poor database design and can be addressed only by changing the structure and design of the database.

When you design and implement a database, you should identify the large tables in the database and the more complex processes that the database will perform, and give special consideration to performance when designing these tables. Also consider the effect on performance of increasing the number of users who can access the database.
Examples of design changes that improve performance include:
If a table containing hundreds of thousands of rows must be summarized for a daily report, you can add a column or columns to the table that contains preaggregated data to be used only for the report.

Databases can be overnormalized, which means the database is defined with numerous, small, interrelated tables. When the database is processing the data in these tables, it has to perform a great deal of extra work to combine the related data. This extra processing can reduce the performance of the database. In these situations, denormalizing the database slightly to simplify complex processes can improve performance.

In conjunction with correct database design, correct use of indexes, RAID (redundant array of independent disks), and filegroups is important for achieving good performance.

Hardware Considerations

Generally, the larger the database, the greater the hardware requirements. But there are other determining factors: the number of concurrent users/sessions, transaction throughput, and the types of operations within the database. For example, a database containing infrequently updated data for a school library would generally have lower hardware requirements than a 1-terabyte (TB) data warehouse containing frequently analyzed sales, product, and customer information of a large corporation. Aside from the disk storage requirements, more memory and faster processors would be needed for the data warehouse to enable more of the data to be cached in memory and queries referencing large amounts of data to be processed quickly.
Maintenance

After a database has been created and all objects and data have been added and are in use, there will be times when maintenance must be performed. For example, it is important to back up the database regularly. You may also need to create some new indexes to improve performance. These issues should be taken into consideration when you design the database to minimize the effect on users, the time taken to perform the task, and the effort involved.

Maintenance design guidelines include:
Designing the database to be as small as possible and to exclude redundant information.

Normalizing your database can help you achieve this. For example, reducing the size of the database can help reduce the time taken to back up or, more importantly, restore a database. This is especially important during a restore operation because the database is unavailable while it is being restored.
Designing partitioned tables rather than a single table, if the table will contain a large number of rows.
For example, a table containing every credit card transaction received by a bank could be split into multiple tables, with each table holding data for a single month. This can ease index maintenance if new indexes would otherwise have to be added to improve query performance. It may be necessary to create the index only on data from the last three months because older data is no longer referenced. The larger the table, the longer it takes to create new indexes.
Microsoft® SQL Server™ 2000 provides the Database Maintenance Plan Wizard for automating many of these tasks, thereby reducing or removing the work involved in database maintenance.

JAVA FAQS1

What is JAVA ?
Java is a pure object oriented programming language, which has derived C syntax and C++ object oriented programming features.
Is a compiled and interpreted language and is platform independent and
Can do graphics, networking, multithreading. It was initially called as OAK.

What r the four cornerstones of OOP ?
Abstraction : Can manage complexity through abstraction. Gives the complete overview of a particular task and the details are handled by its derived classes. Ex : Car.
Encapsulation : Nothing but data hiding, like the variables declared under private of a particular class are accessed only in that class and cannot access in any other the class.
Inheritance : Is the process in which one object acquires the properties of another object, ie., derived object.
Polymorphism : One method different forms, ie., method overriding and interfaces are the examples of polymorphism.

what is downcasting ?
Doing a cast from a base class to a more specific class. The cast does not convert the object, just asserts it actually is a more specific extended object.
e.g. Dalamatian d = (Dalmatian) aDog;
Most people will stare blankly at you if you use the word downcast. Just use cast.

What is Java Interpreter ?
It is Java Virtual Machine. ie., a java program compiles the Unicode to intermediary code called as Bytecode which is not an executable code. that is executed by Java interpreter.

What are Java Buzzwords ?Simple : Easy to learn.
Secure : Provided by firewalls between networked applications.
Portable : Can be dynamically downloaded at various platforms connect to internet.
OOP : Four Corner stones.
Multithread : Can perform more than one task concurrently in a single program.
Robust : overcomes problems of de-allocation of memory and exceptions.
Interpreted : Convert into byte code and the executes by JVM.
Distributed : Concept of RMI.
Dynamic : Verifying and accessing objects at run time.


What are public static void main(String args[]) and System.out.println() ?Public keyword is an access specifier.
Static allows main() to be called without having to instantiate a particular instance of class.
Void does not return any value.
main() is the method where java application begins.
String args[] receives any command line arguments during runtime.

System is a predefined class that provides access to the system.
out is output stream connected to console.
println displays the output.

What are identifiers and literals ?Identifiers are the variables that are declared under particular datatype.
Literals are the values assigned to the Identifiers.

What is Typed language ?This means that the variables are at first must be declared by a particular datatype whereas this is not the case with javascript.

Scope and lifetime of variables ?
scope of variables is only to that particular block
lifetime will be till the block ends.
variables declared above the block within the class are valid to that inner block also.

Casting Incompatible types ?Can be done either implicitly and explicitly. ie., int b = (int) c; where c is float.
There are two types of castings related to classes : 1) unicast and 2)multicast.

Declaration of Arrays ?
int a[] = new int[10]; int a[][] = new int[2][2];

What does String define ?String is an array of characters, but in java it defines an object.
and the variable of type string can be assigned to another variable of type String.

Define class ?A class is a one which defines new datatype, and is template of an object, and is a protoype.

Types of Constructors ?
Default Constructor, Parameterized Constructor, Copy Constructors
Garbage collector takes the responsibility releasing the memory of object implicitly.

Define this , finalize, and final( for variables, methods, classes ) ?this is used inside any method to refer to the current object. and is mostly avoided.
finalize method is used to perform the actions specified in this method just before an object is destroyed. ie just before garbage collector process.
final with variables is we cant change the literals of the variables ie nothing but const.
final with method means we cant override that method.
final with class means we cannot have derived classes of that particular class.

What is passed by reference ?
Objects are passed by reference.
In java we can create an object pointing to a particular location ie NULL location by specifying : ;
and also can create object that allocates space for the variables declared in that particular class by specifying : = new ();

Explain about Static ?When a member is declared as static it can be accessed before any objects of its class are created and without any reference to any object.
these are global variables, no copy of these variables can be made.
static can also be declared for methods. and cannot refer to this or super.

What r nested classes ?
There are two types : static and non-static.
static class means the members in its enclosing class (class within class) can be accessed by creating an object and cannot be accessed directly without creating the object.
non-static class means inner class and can be accessed directly with the object created for the outer class no need to create again an object like static class.

Briefly about super() ?This is used to initialize constructor of base class from the derived class and also access the variables of base class like super.i = 10.

method overloading : same method name with different arguments.
method overriding : same method name and same number of arguments.

What is Dynamic Method Dispatch ?this is the mechanism by which a call to an overridden function is resolved at runtime rather than at compile time. And this is how Java implements runtime polymorphism.

What r abstract classes ?
To create a superclass that only defines generalized form that will be shared by all its subclasses, leaving it to each subclass to fill in the details.
• we cannot declare abstract constructors and abstract static methods.
• An abstract class contains at least one abstract method.
• And this abstract class is not directly instantiated with new operator.
• Can create a reference to abstract class and can be point to subclass object.

What is Object class and java.lang ?Object class is the superclass of all the classes and means that reference variable of type object can refer to an object of any other class. and also defines methods like finalise,wait.
java.lang contains all the basic language functions and is imported in all the programs implicitly.

What r packages and why ? how to execute a program in a package ?Package is a set of classes, which can be accessed by themselves and cannot be accessed outside the package. and can be defined as package .
Package name and the directory name must be the same.
And the execution of programs in package is done by : java mypack.account
where mypack is directory name and account is program name.

What does a java source file can contain ?
specifying package name.
importing more than one package
specifying classes and there methods
………………

Why interface and what extends what ?Interface is similar to abstract classes. this define only method declarations and definitions are specified in the classes which implements these interfaces.
and “ one interface multiple methods “ signifies the polymorphism concept.
Here an interface can extend another interface.
and a class implements more than one interface.

How Exception handling is done in Java ?
Is managed via 5 keywords :
try : statements that you want to monitor the exceptions contain in try block.
catch : the exception thrown by try is catched by this.
throw : to manually throw exception we go for this.
throws : Exception that is thrown out of a method must be specified by throws after the method declaration.
finally : this block is executed whether or not an exception is thrown. and also it is executed just before the method returns. and this is optional block.

What r checked and unchecked Exceptions ?* Unchecked Exceptions are those which r not included in throws list and are derived from RuntimeException which are automatically available and are in java.lang.
* Checked Exceptions are those which cannot handle by itself.

What is Thread and multithread ? How is thread created ?
Thread is a small unit of dispatchable code. ie., a single program can perform more than one task simultaneously. This is a light weight process and is of low cost.
MultiThreading writes more efficient programs and make maximum use of CPU ie., it minimizes its idle time.
A Thread is created in two ways :
1) By implementing the runnable interface.
2) By extending the Thread class itself.
First way is used to update only run() method. ie we can use only run() method in this class.
Second way is used to define several methods overridden by derived class.
Generally we override only run() method so we go for runnable interface.

What are the various states and methods of thread ?States : Running, Ready to run, Suspended, Resumed, blocked and terminated.
Methods : getName, getPriority, isAlive, join, run, sleep, start.
Thread priorities are MIN_PRIORITY, MAX_PRIORITY, NORM_PRIORITY.

What is interprocess synchronization ? ( also called Monitor, Semaphore )
Consider a small box namely MONITOR that can hold only one thread. Once a thread enters a monitor, all other threads must wait until that thread exits the monitor.
In this way, a monitor can be used to protect a shared asset from being manipulated by more than one thread at a time.
Once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object.

What is Stream ?
It is an Abstraction that either produces or consumes information.
Two types : Byte Stream and Character Stream.
Print Writer is to Print output in Real World Programs.

How to enter data in java ?First specify :
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
then say br.read(), and this is put in do while loop to receive as many as we require.

Define Inline Functions ?In ordinary functions, during the program execution, at any function call the controller jumps to the function definition, performs operation and returns the value, then comes back to the program.
whereas in Inline functions the controller copies the complete function definition into the program and performs operations.

What are the four components in URL ?http:// www. yahoo .com : 8080 / index.html
http: --- > is protocol
www. yahoo .com ---à is IP address
8080 --à port number and is a pointer to memory location.
index.html --à file path to be loaded

What is a StringTokenizer ?String Tokenizer provide parsing process in which it identifies the delimiters provided by the user , by default delimiters are spaces, tab, newline etc. and separates them from the tokens. Tokens are those which are separated by delimiters.

What are macros and Inline functions ? Which is best and Difference ?
Inline functions do Parameter passing, where as Macros do Text Substitution.
Its better to go for Inline functions than macros, else you may get different results.

How to Declare a pointer to function ?
int func_name(float) //ordinary declaration of function.
int (*func_name_ptr)(float) // Declaration of pointer.
Assigning the Address can be done as :
func_name_ptr = func_name. // Return type and Signatures must be Same.
Invoking a function pointer : int x = (*func_name_ptr)(values as specified);

What is a file ? What is a Directory ?
File : Describes the properties of file, like permissions, time, date, directory path, and to navigate subdirectory hierarchies.
Directory : Is a file that contains list of other files and directories .

What is Serialization ?The process of writing the state of an object to a byte stream. and can restore these objects by using deserialization.
Is also need to implement RMI, which allows a java object of one machine to invoke java object of another machine.
ie., the object is passed as an argument by serializing it and the receiving machine deserializes it.

Interfaces include by java.lang ?
Java.lang is the package of all the classes.
And is automatically imported into all Java programs.
Intefaces : Cloneable, Comparable, Runnable.

What is user defined exception?To handle situations specific to our applications we go for User Defined Exceptions.
and are defined by User using throw keyword.

What is the difference between process and threads?Process is a heavy weight task and is more cost.
Thread is a light weight task which is of low cost.
A Program can contain more than one thread.
A program under execution is called as process.

What is the difference between CGI and Servlet ?
CGI suffered serious performance problems. servlets performance is better.
CGI create separate process to handle client request. and Servlets do not.
CGI is platform dependent, whereas Servlet is platform-independent b’cauz written in java.
Servlets can communicate with applets, databases and RMI mechanisms.

Quick Revision Tips

Quick Revision Tips
1. An identifier in java must begin with a letter , a dollar sign($), or an underscore (-); subsequent characters may be letters, dollar signs, underscores, or digits.
2. There are three top-level elements that may appear in a file. None of these elements is required. If they are present, then they must appear in the following order:
-package declaration         
-import statements        
-class definitions 
3. A java source file (.java file) can't have more than one public class , interface or combination of both. 
4. "goto" is a keyword in Java.
5. NULL is not a keyword, but null is a keyword in Java.
6. A final class can't be subclassed.
7. A final method can't be overridden but a non final method can be overridden to final method.
8. Abstract classes can't be instantiated and should be subclassed.
9. Primitive Wrapper classes are immutable.
10. A static method can't refer to "this" or "super".
11. A static method can't be overridden to non-static and vice versa.
12. The variables in java can have the same name as method or class.
13. All the static variables are initialized when the class is loaded.
14. An interface can extend more than one interface, while a class can extend only one class.
15. The variables in an interface are implicitly final and static. If the interface , itself, is declared as public the methods and variables are implicitly public.
16. Variables cannot be synchronized.
17. Instance variables of a class are automatically initialized, but local variables of a function need to be initialized explicitly.
18. An abstract method cannot be static because the static methods can't be overridden.
19. The lifecycle methods of an Applet are init(), start(), stop() and destroy(). 
20. The transient keyword is applicable to variables only. 
21. The native keyword is applicable to methods only.
22. The final keyword is applicable to methods , variables and classes.
23. The abstract keyword is applicable to methods and classes.
24. The static keyword is applicable to variables, methods or a block of code called static initializes.
25. A native method can't be abstract but it can throw exception(s).
26. A final class cannot have abstract methods.
27. A class can't be both abstract and final.
28. A transient variable may not be serialized.
29. All methods of a final class are automatically final.
30. While casting one class to another subclass to superclass is allowed without any type casting.
e.g.. A extends B , B b = new A(); is valid but not the reverse.
31. The String class in java is immutable. Once an instance is created, the string it contains cannot be changed.
e.g. String s1 = new String("test"); s1.concat("test1"); Even after calling concat() method on s1, the value of s1 will remain to be "test". What actually happens is a new instance is created.
But the StringBuffer class is mutable.
32. The + and += operators are the only cases of operator overloading in java and is applicable to Strings.
33. Bit-wise operators - &, ^ and | operate on numeric and boolean operands.
34. The short circuit logical operators && and || provide logical AND and OR operations on boolean types and unlike & and | , these are not applicable to integral types. The valuable additional feature provided by these operators is the right operand is not evaluated if the result of the operation can be determined after evaluating only the left operand.
35. The difference between x = ++y; and x = y++;
In the first case y will be incremented first and then assigned to x. In second case first y will be assigned to x then it will be incremented.
36. Please make sure you know the difference between << , >> and >>>(unsigned rightshift) operators.
37. The initialization values for different data types in java is as follows
  byte = 0, int = 0, short = 0, char = '\u0000', long = 0L, float = 0.0f, double = 0.0d, boolean = false,
 object referenece (of any object) = null.
38. Setting the object reference to null makes it a candidate for garbage collection.
39. An overriding method may not throw a checked exception unless the overridden method also throws that exception or a superclass of that exception.
40. Interface methods can't be native, static, synchronized, final, private, protected or abstract.
41. Abstract classes can have constructors , and it can be called by super() when its subclassed.
42. A final variable is a constant and a static variable is like a global variable.
43. The String class is a final class, it can't be subclassed.
44. The Math class has a private constructor, it can't be instantiated.
45. The random() method of Math class in java returns a random number , a double , between 0.0 and 1.0.
46. The java.lang.Throwable class has two subclasses : Exception and Error.
47. An Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
48. The two kinds of exceptions in java are : Compile time (Checked ) and Run time (Unchecked) exceptions. All subclasses of Exception except the RunTimeException and its subclasses are checked exceptions.
Examples of Checked exception : IOException, ClassNotFoundException.
Examples of Runtime exception :ArrayIndexOutOfBoundsException,NullPointerException, ClassCastException, ArithmeticException, NumberFormatException.
49. The unchecked exceptions do not have to be caught.
50. A try block may not be followed by a catch but in that case, finally block must follow try.
51. While using multiple catch blocks, the type of exception caught must progress from the most specific exception to catch to the superclass(es) of these exceptions.
52. More than one exception can be listed in the throws clause of a method using commas. e.g. public void myMethod() throws IOException, ArithmeticException.
53. On dividing an integer by 0 in java will throw ArithmeticException.
54. The various methods of Java.lang.Object are
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString and wait. 
55. The Java.lang.System is a final class and can't be subclassed.
56. Garbage collection in java cannot be forced. The methods used to call garbage collection thread are System.gc() and Runtime.gc()
57. To perform some task when an object is about to be garbage collected, you can override the finalize() method of the Object class. The JVM only invokes finalize() method once per object. The signature of finalize() method of Object class is : protected void finalize() throws Throwable.
58. The parent classes of input and output streams : InputStream and OutputStream class are abstract classes.
59. File class can't be used to create a new file. For that any other output stream class such as FileOutputStream or filter streams like PrintWriter should be used. Please note that java will create a file only when the file is not available.
60. For the RandomAccessFile constructor, the mode argument must either be equal to "r" or "rw".
61. In java, console input is accomplished by reading from System.in .
62. System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream.
63. Both FileInputStream and FileOutputStream classes throws FileNotFoundException. In earlier versions of java, FileOutputStream() threw an IOException when an output could not be created.
64. System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream.
65. A method can't be overridden to be more private. e.g.. a public method can only be overridden to be public.
66. Both primitives and object references can be cast.
67. If inner class is declared in a method then it can access only final variables of the particular method but can access all variables of the enclosing class.
68. To refer to a field or method in the outer class instance from within the inner class, use Outer.this.fieldname .
69. Inner classes may not declare static initializers or static members unless they are compile time constants i.e. static final var = value;
70. A nested class cannot have the same name as any of its enclosing classes.
71. Inner class may be private, protected, final, abstract or static.
72. An example of creation of instance of an inner class from some other class:
class Outer
{
    public class Inner{}
}

class Another
{
    public void amethod()
    {
        Outer.Inner i = new Outer().new Inner();
    }
}
73. Classes defined in methods can be anonymous, in which case they must be instantiated at the same point they are defined. These classes can't have explicit constructor and may implement interface or extend other classes.
74. The Thread class resides in java.lang package and need not be imported.
75. The sleep and yield methods of Thread class are static methods.
76. The range of Thread priority in java is 1-10. The minimum priority is 1 and the maximum is 10. The default priority of any thread in java is 5.
77. There are two ways to provide the behavior of a thread in java: extending the Thread class or implementing the Runnable interface.
78. The only method of Runnable interface is "public void run();".
79. New thread take on the priority of the thread that spawned it.
80. Using the synchronized keyword in the method declaration, requires a thread obtain the lock for this object before it can execute the method.
81. A synchronized method can be overridden to be not synchronized and vice versa.
82. In java terminology, a monitor is any object that has some synchronized code.
83. Both wait() and notify() methods must be called in synchronized code.
84. The notify() mthod moves one thread, that is waiting on this object's monitor, into the Ready state. This could be any of the waiting threads.
85. The notifyAll() method moves all threads, waiting on this object's monitor into the Ready state.
86. Every object has a lock and at any moment that lock is controlled by, at most, one single thread.
87. There are two ways to mark code as synchronized:
a.) Synchronize an entire method by putting the synchronized modifier in the method's declaration.
b.) Synchronize a subset of a method by surrounding the desired lines of code with curly brackets ({}).
88. The argument to switch can be either byte, short , char or int.
89. The expression for an if and while statement in java must be a boolean.
90. Breaking to a label (using break ;) means that the loop at the label will be terminated and any outer loop will keep iterating. While a continue to a label (using continue ;) continues execution with the next iteration of the labeled loop.
91. A static method can only call static variables or other static methods, without using the instance of the class. e.g. main() method can't directly access any non static method or variable, but using the instance of the class it can.
92. instanceof is a java keyword not instanceOf.
93. The if() statement in java takes only boolean as an argument. Please note that if (a=true){}, provided a is of type boolean is a valid statement and the code inside the if block will be executed. 
94. The (-0.0 == 0.0) will return true, while (5.0==-5.0) will return false.
95. An abstract class may not have even a single abstract method but if a class has an abstract method it has to be declared as abstract.
96. Collection is an Interface where as Collections is a helper class.
97. The default Layout Manager for Panel and Applet is Flow. For Frame and Window its BorderLayout.
98. The FlowLayout always honors the a component's preferred size.
99. BorderLayout honors the preferred width of components on the East and West, while the preferred height is honored for the components in the North and South.
100. The java.awt.event package provides seven adapter classes, one for each listener interface. All these adapter classes have do-nothing methods (empty bodies) , implementing listener interface.
101. A componenet subclass may handle its own events by calling enableEvents(), passing in an even mask.
102. The Listener interfaces inherit directly from java.util.EventListener interface.
103. A Container in java is a Component (Container extends Component) that can contain other components. 
104. Graphics class is abstract, hence cannot be instantiated.
105. The repaint() method invokes a component's update() method() which in turn invokes paint() method.
106. The Applet class extends Panel, Frame class extends Window.
107. A String in java is initialized to null, not empty string and an empty string is not same as a null string.
108. The statement float f = 5.0; will give compilation error as default type for floating values is double and double can't be directly assigned to float without casting.
109. The equals() method in String class compares the values of two Strings while == compares the memory address of the objects being compared.
e.g. String s = new String("test"); String s1 = new String("test");
s.equals(s1) will return true while s==s1 will return false.
110. The valueOf() method converts data from its internal format into a human-readable form. It is a static method that is overloaded within String class for all of Java's built-in types, so that each type can be converted properly into a string.
111. The main difference between Vector and ArrayList is that Vector is synchronized while the ArrayList is not.
112. A Set is a collection, which cannot contain any duplicate elements and has no explicit order to its elements.
113. A List is a collection, which can contain duplicate elements, and the elements are ordered.
114. A Map does not implement the Collection interface.
115. The following definition of main method is valid : static public void main(String[] args).
116. The main() method can be declared final. 
117. The example of array declaration along with initialization - int k[] = new int[]{1,2,3,4,9};
118. The size of an array is given by arrayname.length.
119. The local variables (variables declared inside method) are not initialized by default. But the array elements are always initialized wherever they are defined be it class level or method level.
120. In an array , the first element is at index 0 and the last at length-1. Please note that length is a special array variable and not a method.
121. The octal number in java is preceded by 0 while the hexadecimal by 0x (x may be in small case or upper case)
e.g.
octal :022
hexadecimal :0x12
122. A constructor cannot be native, abstract, static, synchronized or final.
123. Constructors are not inherited so not possible to override them.
124. A constructor body can include a return statement providing no value is returned .
125. A constructor never return a value. If you specify a return value, the JVM (java virtual machine) will interpret it as a method.
126. A call to this() or super() in a constructor must be placed at the first line.
127. If a class contains no constructor declarations, then a default constructor that takes no arguments is supplied. This default constructor invokes the no-argument constructor of the super class  via super() call (if there is any super class).
128. Be careful for static and abstract key word in the program.
129. Also be careful for private keyword in front of a class.
130. The UTF characters in java are as big as they need to be while Unicode characters are all 16 bits.

Hibernate

What is Hibernate?

• Hibernate is an object-relational mapping tool (ORM) that allows for persisting Java objects in a relational database
• Driven by XML configuration files to configure data connectivity and map classes to database tables
• Not a Java/SQL code generation tool
• Developer writes code to call API
• API executes necessary SQL at runtime

Why Use Hibernate?

• Eliminate need for repetitive SQL
• Work with classes and objects instead of queries and result sets
• More OO, less procedural
• Mapping approach can resist changes in object/data model more easily
• Strong support for caching
• Handles all create-read-update-delete (CRUD) operations using simple API; no SQL
• Generates DDL scripts to create DB schema (tables, constraints, sequences)
• Flexibility to hand-tune SQL and call stored procedures to optimize performance
• Supports over 20 RDBMS; change the database by tweaking configuration files

Plain Old Java Object (POJO)

Default constructor
• Identifier property
• Get/set pairs
• Collection

property is an interface type

Creating Objects

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
AuctionItem item = new AuctionItem();
item.setDescription(”Batman Begins”);
item.setType(”DVD”);
session.save(item);
tx.commit();
session.close();

Updating Objects

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
AuctionItem item =(AuctionItem) session.get(ActionItem.class, itemId);
item.setDescription(newDescription);
tx.commit();
session.close();

Deleting Objects

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
AuctionItem item =(AuctionItem) session.get(ActionItem.class, itemId);
session.delete(item);
tx.commit();
session.close();

Selecting Objects

• Hibernate Query Language (HQL), similar to SQL

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

List allAuctions = session.createQuery(”select item from AuctionItem item
join item.bids bid where item.description like ‘Batman%’
and bid.amount < 15 “).list();

tx.commit();
session.close();

Key Hibernate Classes

Configuration – uses mapping and database connection metadata to create SessionFactory

SessionFactory –thread-safe cache of compiled mappings for database; created

once at application startup (expensive)

•– Session – represents a “conversation” between application and database; holds 1st

level cache of objects

• Transaction – an atomic unit of work SessionFactory

• Once the Configuration is prepared, obtaining the SessionFactory is

easy:

Configuration cfg = new Configuration();

// … do some configuration …

cfg.configure();

SessionFactory sf = cfg.buildSessionFactory();
Hibernate Querying Options


• HQL

– Syntax similar to SQL
– Unlike SQL, HQL is still database-agnostic

• Criteria

– Java-based API for building queries
– Good for queries that are built up using lots of conditional logic; avoids messy string manipulation

• SQL / PLSQL

– Often needed to optimize for performance or
leverage vendor-specific features

Syntax Code

Connecting to a Database

This example uses the JDBC-ODBC bridge to connect to a database called ''mydatabase''.
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String url = "jdbc:odbc:mydatabase";
Connection con = DriverManager.getConnection(
url, "login", "password");
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
}

Creating a Table

This example creates a table called ''mytable'' with three columns: COL_A which holds strings, COL_B which holds integers, and COL_C which holds floating point numbers.
try {
Statement stmt = con.createStatement();

stmt.executeUpdate("CREATE TABLE mytable (
COL_A VARCHAR(100), COL_B INTEGER, COL_C FLOAT)");
} catch (SQLException e) {
}

Entering a New Row into a Table

This example enters a row containing a string, an integer, and a floating point number into the table called ''mytable''.
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO mytable
VALUES ('Patrick Chan', 123, 1.23)");
connection.close();
} catch (SQLException e) {
}

Getting All Rows from a Table

This example retrieves all the rows from a table called ''mytable''. A row in ''mytable'' consists of a string, integer, and floating point number.
try {
Statement stmt = connection.createStatement();

// Get data using colunm names.
ResultSet rs = stmt.executeQuery(
"SELECT * FROM mytable");
while (rs.next()) {
String s = rs.getString("COL_A");
int i = rs.getInt("COL_B");
float f = rs.getFloat("COL_C");
process(s, i, f);
}

// Get data using colunm numbers.
rs = stmt.executeQuery(
"SELECT * FROM mytable");
while (rs.next()) {
String s = rs.getString(1);
int i = rs.getInt(2);
float f = rs.getFloat(3);
process(s, i, f);
}
} catch (SQLException e) {
}

Getting Particular Rows from a Table

This example retrieves all rows from a table called ''mytable'' whose column COL_A equals ``Patrick Chan''. A row in ''mytable'' consists of a string, integer, and floating point number.
try {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(
"SELECT * FROM mytable WHERE COL_A = 'Patrick Chan'");
rs.next();
String s = rs.getString("COL_A");
int i = rs.getInt("COL_B");
float f = rs.getFloat("COL_C");
process(s, i, f);
} catch (SQLException e) {
}

Updating a Row of Data in a Table

This example updates a row in a table called ``mytable''. In particular, for all rows whose column COL_B equals 123, column COL_A is set to ''John Doe''.
try {
Statement stmt = connection.createStatement();
int numUpdated = stmt.executeUpdate(
"UPDATE mytable SET COL_A = 'John Doe'
WHERE COL_B = 123");
connection.close();
} catch (SQLException e) {
}

Using a Prepared Statement

A prepared statement should be used in cases where a particular SQL statement is used frequently. The prepared statement is more expensive to set up but executes faster than a statement. This example demonstrates a prepared statement for getting all rows from a table called ''mytable'' whose column COL_A equals ''Patrick Chan''. This example also demonstrates a prepared statement for updating data in the table. In particular, for all rows whose column COL_B equals 123, column COL_A is set to ''John Doe''.
try {
// Retrieving rows from the database.
PreparedStatement stmt = connection.prepareStatement(
"SELECT * FROM mytable WHERE COL_A = ?");
int colunm = 1;
stmt.setString(colunm, "Patrick Chan");
ResultSet rs = stmt.executeQuery();

// Updating the database.
stmt = connection.prepareStatement(
"UPDATE mytable SET COL_A = ? WHERE COL_B = ?");
colunm = 1;
stmt.setString(colunm, "John Doe");
colunm = 2;
stmt.setInt(colunm, 123);
int numUpdated = stmt.executeUpdate();
} catch (SQLException e) {
}


Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan.

Handling Events with an Anonymous Class

If an event handler is specific to a component (that is, not shared by other components), there is no need to declare a class to handle the event. The event handler can be implemented using an anonymous inner class. This example demonstrates an anonymous inner class to handle key events for a component.

component.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
}
});

Handling Action Events

Action events are fired by subclasses of AbstractButton and includes buttons, checkboxes, and menus.

AbstractButton button = new JButton(quot;OK");
button.addActionListener(new MyActionListener());

public class MyActionListener
implements ActionListener {
public void actionPerformed(ActionEvent evt) {
// Determine which abstract
// button fired the event.
AbstractButton button =
(AbstractButton)evt.getSource();
}
}

Handling Key Presses

You can get the key that was pressed either as a key character (which is a Unicode character) or as a key code (a special value representing a particular key on the keyboard).

component.addKeyListener(new MyKeyListener());

public class MyKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
// Check for key characters.
if (evt.getKeyChar() == 'a') {
process(evt.getKeyChar());
}

// Check for key codes.
if (evt.getKeyCode() == KeyEvent.VK_HOME) {
process(evt.getKeyCode());
}
}
}

Handling Mouse Clicks

component.addMouseListener(
new MyMouseListener());

public class MyMouseListener
extends MouseAdapter {
public void mouseClicked(MouseEvent evt) {
if ((evt.getModifiers() &
InputEvent.BUTTON1_MASK) != 0) {
processLeft(evt.getPoint());
}
if ((evt.getModifiers() &
InputEvent.BUTTON2_MASK) != 0) {
processMiddle(evt.getPoint());
}
if ((evt.getModifiers() &
InputEvent.BUTTON3_MASK) != 0) {
processRight(evt.getPoint());
}
}
}

Handling Mouse Motion

component.addMouseMotionListener(
new MyMouseMotionListener());

public class MyMouseMotionListener
extends MouseMotionAdapter {
public void mouseMoved(MouseEvent evt) {
// Process current position of cursor
// while all mouse buttons are up.
process(evt.getPoint());
}
public void mouseDragged(MouseEvent evt) {
// Process current position of cursor
// while mouse button is pressed.
process(evt.getPoint());
}
}

Detecting Double and Triple Clicks

component.addMouseListener(
new MyMouseListener());

public class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 3) {
// triple-click
} else if (evt.getClickCount() == 2) {
// double-click
}
}
}

Handling Focus Changes

component.addFocusListener(
new MyFocusListener());

public class MyFocusListener
extends FocusAdapter {
public void focusGained(FocusEvent evt) {
// The component gained the focus.
}
public void focusLost(FocusEvent evt) {
// The component lost the focus.
}
}
Files, Streams, I/O (java.io)


Constructing a Path

On Windows, this example creates the path \blash a\blash b. On Unix, the path would be /a/b.

String path = File.separator +
"a" + File.separator + "b";


Reading Text from Standard Input

try {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String str = "";
while (str != null) {
System.out.print("> prompt ");
str = in.readLine();
process(str);
}
} catch (IOException e) {
}


Reading Text from a File

try {
BufferedReader in = new BufferedReader(
new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
} catch (IOException e) {
}

Writing to a File

If the file does not already exist, it is automatically created.
try {
BufferedWriter out = new BufferedWriter(
new FileWriter("outfilename"));
out.write("aString");
out.close();
} catch (IOException e) {
}

Creating a Directory

(new File("directoryName")).mkdir();

Appending to a File

try {
BufferedWriter out = new BufferedWriter(
new FileWriter("filename", true));
out.write("aString");
out.close();
} catch (IOException e) {
}

Deleting a File


(new File("filename")).delete();

Deleting a Directory

(new File("directoryName")).delete();
 
Creating a Temporary File


try {
// Create temp file.
File temp = File.createTempFile(
"pattern", ".suffix");

// Delete temp file when program exits.
temp.deleteOnExit();

// Write to temp file
BufferedWriter out = new BufferedWriter(
new FileWriter(temp));
out.write("aString");
out.close();
} catch (IOException e) {
}

Using a Random Access File

try {
File f = new File("filename");
RandomAccessFile raf =
new RandomAccessFile(f, "rw");

// Read a character.
char ch = raf.readChar();

// Seek to end of file.
raf.seek(f.length());

// Append to the end.
raf.writeChars("aString");
raf.close();
} catch (IOException e) {
}

Serializing an Object

The object to be serialized must implement java.io.Serializable.
try {
ObjectOutput out = new ObjectOutputStream(
new FileOutputStream("filename.ser"));
out.writeObject(object);
out.close();
} catch (IOException e) {
}

Deserializing an Object

This example deserializes a java.awt.Button object.
try {
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("filename.ser"));
AnObject object = (AnObject) in.readObject();
in.close();
} catch (ClassNotFoundException e) {
} catch (IOException e) {
}

Traversing a Directory

public static void traverse(File f) {
process(f);

if (f.isDirectory()) {
String[] children = f.list();
for (int i=0; i < children.length; i++) {
traverse(new File(f, children[i]));
}
}
}

Reading UTF-8 Encoded Data

try {
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(
"infilename"), "UTF8"));
String str = in.readLine();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}

Writing UTF-8 Encoded Data

try {
Writer out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(
"outfilename"), "UTF8"));
out.write(aString);
out.close();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}

Reading ISO Latin-1 Encoded Data

try {
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(
"infilename"), "8859_1"));
String str = in.readLine();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}

Writing ISO Latin-1 Encoded Data

try {
Writer out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(
"outfilename"), "8859_1"));
out.write(aString);
out.close();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}


Networking (java.net)


Creating a URL

try {
// With components.
URL url = new URL("http","hostname", 80, "index.html");

// With a single string.
url = new URL(
"http://hostname:80/index.html");
} catch (MalformedURLException e) {
}

Parsing a URL

try {
URL url = new URL("http://hostname:80/index.html#_top_");
String protocol = url.getProtocol(); // http
String host = url.getHost(); // hostname
int port = url.getPort(); // 80
String file = url.getFile(); // index.html
String ref = url.getRef(); // _top_
} catch (MalformedURLException e) {
}

Reading Text from a URL

try {
URL url = new URL("http://hostname:80/index.html");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));

String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

Resolving a Hostname

Creating a Client Socket
try {
InetAddress addr = InetAddress.getByName("java.sun.com");
int port = 80;
Socket sock = new Socket(addr, port);
} catch (IOException e) {
}

Creating a Server Socket
try {
int port = 2000;
ServerSocket srv = new ServerSocket(port);

// Wait for connection from client.
Socket socket = srv.accept();
} catch (IOException e) {
}

Reading Text from a Socket
try {
BufferedReader rd = new BufferedReader(
new InputStreamReader(socket.getInputStream()));

String str;
while ((str = rd.readLine()) != null) {
process(str);

}
rd.close();
} catch (IOException e) {
}

Writing Text to a Socket
try {
BufferedWriter wr = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
wr.write("aString");
wr.flush();
} catch (IOException e) {
}

Sending a Datagram
public static void send(InetAddress dst,
int port, byte[] outbuf, int len) {
try {
DatagramPacket request = new DatagramPacket(
outbuf, len, dst, port);
DatagramSocket socket = new DatagramSocket();
socket.send(request);
} catch (SocketException e) {
} catch (IOException e) {
}
}
Receiving a Datagram
try {
byte[] inbuf = new byte[256]; // default size
DatagramSocket socket = new DatagramSocket();

// Wait for packet
DatagramPacket packet = new DatagramPacket(
inbuf, inbuf.length);
socket.receive(packet);

// Data is now in inbuf
int numBytesReceived = packet.getLength();
} catch (SocketException e) {
} catch (IOException e) {
}

Joining a Multicast Group
public void join(String groupName, int port) {
try {
MulticastSocket msocket = new MulticastSocket(port);
group = InetAddress.getByName(groupName);
msocket.joinGroup(group);
} catch (IOException e) {
}
}

Receiving from a Multicast Group
public void read(MulticastSocket msocket,
byte[] inbuf) {
try {
DatagramPacket packet = new DatagramPacket(
inbuf, inbuf.length);

// Wait for packet
msocket.receive(packet);

// Data is now in inbuf
int numBytesReceived = packet.getLength();
} catch (IOException e) {
}
}

Sending to a Multicast Group
byte[] outbuf = new byte[1024];
int port = 1234;
try {
DatagramSocket socket = new DatagramSocket();
InetAddress groupAddr = InetAddress.getByName(
"228.1.2.3");
DatagramPacket packet = new DatagramPacket(
outbuf, outbuf.length, groupAddr, port);
socket.send(packet);
} catch (SocketException e) {
} catch (IOException e) {
}
Defining and Exporting a Remote Object
1. Define the remote interface.
import java.rmi.*;

public interface RObject extends Remote {
void aMethod() throws RemoteException;
}

Looking Up a Remote Object and Invoking a Method
try {
// Look up remote object
RObject robj = (RObject) Naming.lookup(
"//localhost/RObjectServer");

// Invoke method on remote object
robj.aMethod();
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (NotBoundException e) {
} catch (RemoteException e) {
}

Passing Parameters to a Remote Method
Arguments to remote methods must be primitive, serializable, or Remote. This example demonstrates the declaration and use of all three parameter types.

1. Define the remote interface.
import java.rmi.*;

public interface RObject extends Remote {
// This parameter is primitive.
void primitiveArg(int num) throws RemoteException;

// This parameter implements Serializable.
void byValueArg(Integer num) throws RemoteException;

// This parameter implements Remote.
void byRefArg(ArgObject arg) throws RemoteException;
}

public interface ArgObject extends Remote {
int aMethod() throws RemoteException;
}

2. Define the remote object implementation.
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;

public class RObjectImpl extends UnicastRemoteObject implements RObject {
public RObjectImpl() throws RemoteException {
super();
}
public void primitiveArg(int num) throws RemoteException {
}
public void byValueArg(Integer num) throws RemoteException {
}
public void byRefArg(ArgObject arg) throws RemoteException {
}
}

3. Compile the remote object implementation.
> javac RObject.java RObjectImpl.java

4. Generate the skeletons and stubs.
> rmic RObjectImpl

5. Create an instance of RObjectImpl and bind it to the RMI Registry.
try {
RObject robj = new RObjectImpl();
Naming.rebind("//localhost/RObjectServer", robj);
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (RemoteException e) {
}

6. Look Up the Remote object and pass the parameters.
try {
// Look up the remote object
RObject robj = (RObject) Naming.lookup("//localhost/RObjectServer");

// Pass a primitive value as argument
robj.primitiveArg(1998);

// Pass a serializable object as argument
robj.byValueArg(new Integer(9));

// Pass a Remote object as argument
robj.byRefArg(new ArgObjectImpl());
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (NotBoundException e) {
} catch (RemoteException e) {
}
Returning Values from a Remote Method
Return values from remote methods must be primitive, serializable, or Remote. This example demonstrates the declaration and use of all three return types. 1. Define the remote interface.

import java.rmi.*;
public interface RObject extends Remote {
// This return value is primitive.
int primitiveRet() throws RemoteException;

// This return value implements Serializable.
Integer byValueRet() throws RemoteException;

// This return value implements Remote.
ArgObject byRefRet() throws RemoteException;
}

public interface ArgObject extends Remote {
int aMethod() throws RemoteException;
}

2. Define the remote object implementation.
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;

public class RObjectImpl extends UnicastRemoteObject
implements RObject {
public RObjectImpl() throws RemoteException {
super();
}
public int primitiveRet() throws RemoteException {
return 3000;
}
public Integer byValueRet() throws RemoteException {
return new Integer(2000);
}
public ArgObject byRefRet() throws RemoteException {
return new ArgObjectImpl();
}
}

3. Compile the remote object implementation.
> javac RObject.java RObjectImpl.java

4. Generate the skeletons and stubs.
> rmic RObjectImpl

5. Create an instance of RObjectImpl and bind it to the RMI Registry.
try {
RObject robj = new RObjectImpl();
Naming.rebind("//localhost/RObjectServer", robj);
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (RemoteException e) {
}
6. Look Up the Remote object, invoke the methods, and receive the return values.
try {
// Look up the remote object
RObject robj = (RObject) Naming.lookup(
"//localhost/RObjectServer");

// Receive the primitive value as return value
int r1 = robj.primitiveRet();

// Receive the serializable object as return value
Integer r2 = robj.byValueRet();

// Receive the Remote Object as return value
ArgObject aobj = robj.byRefRet();
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (NotBoundException e) {
} catch (RemoteException e) {
}

Throwing an Exception from a Remote Method

1. Define the remote interface.
import java.rmi.*;

public interface RObject extends Remote {
void aMethod() throws RemoteException;
}

2. Define the remote object implementation.
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;

public class RObjectImpl extends
UnicastRemoteObject implements RObject {
public RObjectImpl() throws RemoteException {
super();
}
public void aMethod() throws RemoteException {
// The actual exception must be wrapped in
// a RemoteException
throw new RemoteException(
"message", new FileNotFoundException("message"));
}
}

3. Compile the remote object implementation.
> javac RObject.java RObjectImpl.java

4. Generate the skeletons and stubs.
> rmic RObjectImpl
5. Create an instance of RObjectImpl and bind it to the RMI Registry.
try {
RObject robj = new RObjectImpl();
Naming.rebind("//localhost/RObjectServer", robj);
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (RemoteException e) {
}

6. Look up the Remote object, invoke the method, and catch the exception.
try {
// Look up the remote object.
RObject robj = (RObject) Naming.lookup(
"//localhost/RObjectServer");

// Invoke the method.
robj.aMethod();
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (NotBoundException e) {
} catch (RemoteException e) {
// Get the actual exception that was thrown.
Throwable realException = e.detail;
}

Strings (java.lang)


Constructing a String
If you are constructing a string with several appends, it may be more efficient to construct it using a StringBuffer and then convert it to an immutable String object.
StringBuffer buf = new StringBuffer("Initial Text");

// Modify
int index = 1;
buf.insert(index, "abc");
buf.append("def");

// Convert to string
String s = buf.toString();
Getting a Substring from a String
int start = 1;
int end = 4;
String substr = "aString".substring(start, end); // Str

Searching a String
String string = "aString";

// First occurrence.
int index = string.indexOf('S'); // 1

// Last occurrence.
index = string.lastIndexOf('i'); // 4

// Not found.
index = string.lastIndexOf('z'); // -1

Replacing Characters in a String
// Replace all occurrences of 'a' with 'o'
String newString = string.replace('a', 'o');

Replacing Substrings in a String
static String replace(String str,
String pattern, String replace) {
int s = 0;
int e = 0;
StringBuffer result = new StringBuffer();

while ((e = str.indexOf(pattern, s)) >= 0) {
result.append(str.substring(s, e));
result.append(replace);
s = e+pattern.length();
}
result.append(str.substring(s));
return result.toString();
}
Converting a String to Upper or Lower Case

// Convert to upper case
String upper = string.toUpperCase();

// Convert to lower case
String lower = string.toLowerCase();

Converting a String to a Number
int i = Integer.parseInt("123");
long l = Long.parseLong("123");
float f = Float.parseFloat("123.4");
double d = Double.parseDouble("123.4e10");

Converting Unicode to UTF-8
try {
String string = "\u5639\u563b";
byte[] utf8 = string.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
}

Converting UTF-8 to Unicode
public static String toUnicode(byte[] utf8buf) {
try {
return new String(utf8buf, "UTF8");
} catch (UnsupportedEncodingException e) {
}
return null;
}

Determining a Character's Unicode Block
char ch = '\u5639';
Character.UnicodeBlock block =
Character.UnicodeBlock.of(ch);

Breaking a String into Words

String aString = "word1 word2 word3";
StringTokenizer parser =
new StringTokenizer(aString);
while (parser.hasMoreTokens()) {
processWord(parser.nextToken());
}
 
Some More Syntax is to Added

paper 1