How to sort list in reverse order

To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method. 
List list = new ArrayList(); 
Comparator comp = Collections.reverseOrder();
Collections.sort(list, comp) 

What is difference between Arrays and ArrayList?

Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as : 
int [] intArray= new int[6]; 
intArray[7]   // will give ArraysOutOfBoundException. 
Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.
Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime. 
List list = new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
ArrayList is one dimensional but array can be multidimensional. 
            int[][][] intArray= new int[3][2][1];   // 3 dimensional array 

What is difference between HashMap and HashTable?

Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
1. Access to the Hashtable is synchronized on the table while access to the HashMap isn't. You can add it, but it isn't there by default.
2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know. • Fail-safe - “if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException”
3. HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.

How can Arraylist be synchronized without using Vector?

 Arraylist can be synchronized using: 
• Collection.synchronizedList(List list) 
Other collections can be synchronized: 
• Collection.synchronizedMap(Map map) 
• Collection.synchronizedCollection(Collection c) 

What is difference between ArrayList and vector?

Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe. 
Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. 

Oracle PL/SQL WHERE CURRENT OF & FOR UPDATE

WHERE CURRENT OF & FOR UPDATE

The WHERE CURRENT OF clause is used in some UPDATE and DELETE statements.

The WHERE CURRENT OF clause in an UPDATE or DELETE statement states that the most recent row fetched from the table should be updated or deleted. We must declare the cursor with the FOR UPDATE clause to use this feature.

Inside a cursor loop, WHERE CURRENT OF allows the current row to be directly updated.

When the session opens a cursor with the FOR UPDATE clause, all rows in the return set will hold row-level exclusive locks. Other sessions can only query the rows, but they cannot update, delete, or select with FOR UPDATE.

Oracle provides the FOR UPDATE clause in SQL syntax to allow the developer to lock a set of Oracle rows for the duration of a transaction.

The syntax of using the WHERE CURRENT OF clause in UPDATE and DELETE statements follows:

WHERE [CURRENT OF cursor_name | search_condition]

Oracle PL/SQL: SQL ROLLUP

SQL ROLLUP

You can use WITH ROLLUP to generate a summary row for each group.

Example 1 of ROLLUP

Suppose we have the following table - Sales:


EmpIdYrSales
1200512000.00
1200618000.00
1200725000.00
2200515000.00
220066000.00
3200620000.00
3200724000.00


A simple Group by results in:

SELECT Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY Yr

YrSales
200527000.00
200644000.00
200749000.00

A simple group by with ROLLUP results in:

SELECT Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY Yr WITH ROLLUP

YrSales
200527000.00
200644000.00
200749000.00
NULL120000.00

Another example of group by with ROLLUP:

SELECT EmpId, Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY EmpId, Yr WITH ROLLUP

EmpIdYrSales
1200512000.00
1200618000.00
1200725000.00
1NULL55000.00
2200515000.00
220066000.00
2NULL21000.00
3200620000.00
3200724000.00
3NULL44000.00
NULLNULL120000.00

Dataset table row count - OLEDB Data Source VB.Net

The DataSet contains copy of the data we requested through the SQL statement. The DataSet consists of DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The data inside Table is in the form of Rows and Columns . The following VB.NET source code shows how to find the number of rows in a table that resides in the Dataset from OLEDB Data Source.
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
        Dim connetionString As String
        Dim connection As OleDbConnection
        Dim oledbAdapter As OleDbDataAdapter
        Dim ds As New DataSet
        Dim sql As String

        connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"
        sql = "Your SQL Statement Here"

        connection = New OleDbConnection(connetionString)
        Try
            connection.Open()
            oledbAdapter = New OleDbDataAdapter(sql, connection)
            oledbAdapter.Fill(ds, "OLEDB Temp Table")
            oledbAdapter.Dispose()
            connection.Close()

            MsgBox("number of Row(s)   -   " & ds.Tables(0).Rows.Count)

        Catch ex As Exception
            MsgBox("Can not open connection ! ")
        End Try
    End Sub
End Class

Using named arguments in JavaScript functions

Normally, a JavaScript function takes an list of arguments, with the order of each argument predetermined. As an example, the parseInt() function takes two arguments, a string representing a number, and the radix of that number. You need to specify those in exactly that order, first a string, then the number, or at the very least, just the first argument. However, ponder a function where you wish to specify only the second argument, or both of them in arbitrary order - the deficiency of the JavaScript arguments model prohibits this. In this tutorial, I'll teach you how to modify JavaScript functions to accept named arguments, with which you can specify in any order, as named arguments don't rely on order, but instead their name when passing into functions.
JavaScript functions do not natively support naming arguments, so the simplest way to simulate this functionality is via object literals. Let me illustrate with a custom parseInt() function that can accept its two arguments in any order:
JavaScript Function with Named Arguments
// Define function to take one "argument", which is in fact an object:
function fnParseInt( oArg ){ 
return parseInt( oArg.number, oArg.radix );
}

// Which you then call like this (pass in an object literal):
fnParseInt( { number : 'afy', radix : 36 } );
The key to the above is passing in an object literal as the function's sole parameter instead of separate, "authentic" parameter(s). Now, this is a pretty useless example, but it illustrates my point of creating a function that can accept arguments in any order and via a more intuitive name:value format. Such functions are much more robust than standard ones, not to mention user friendly in cases where the function takes on a lot of parameters.

Difference between Views & Materialized views in Oracle

Difference between Views & Materialized views

Materialized views are disk based and update periodically base upon the query definition.

Views are virtual only and run the query definition each time they are accessed.

Views evaluate the data in the tables underlying the view definition at the time the view is queried. It is a logical view of your tables, with no data stored anywhere else. The upside of a view is that it will always return the latest data to you. The downside of a view is that its performance depends on how good a select statement the view is based on. If the select statement used by the view joins many tables, or uses joins based on non-indexed columns, the view could perform poorly.

Materialized views are similar to regular views, in that they are a logical view of your data (based on a select statement), however, the underlying query resultset has been saved to a table. The upside of this is that when you query a materialized view, you are querying a table, which may also be indexed. In addition, because all the joins have been resolved at materialized view refresh time, you pay the price of the join once (or as often as you refresh your materialized view), rather than each time you select from the materialized view. In addition, with query rewrite enabled, Oracle can optimize a query that selects from the source of your materialized view in such a way that it instead reads from your materialized view. In situations where you create materialized views as forms of aggregate tables, or as copies of frequently executed queries, this can greatly speed up the response time of your end user application. The downside though is that the data you get back from the materialized view is only as up to date as the last time the materialized view has been refreshed.

Materialized views can be set to refresh manually, on a set schedule, or based on the database detecting a change in data from one of the underlying tables. Materialized views can be incrementally updated by combining them with materialized view logs, which act as change data capture sources on the underlying tables.

Materialized views are most often used in data warehousing / business intelligence applications where querying large fact tables with thousands of millions of rows would result in query response times that resulted in an unusable application

Difference between HAVING CLAUSE & WHERE CLAUSE in Oracle

SQL - Difference between HAVING CLAUSE & WHERE CLAUSE

1. HAVING specifies a search condition for a group or an aggregate function used in SELECT statement. The WHERE clause specifies the criteria which individual records must meet to be selected by a query. It can be used without the GROUP BY clause. The HAVING clause cannot be used without the GROUP BY clause.

2. The WHERE clause selects rows before grouping. The HAVING clause selects rows after grouping.

3. The WHERE clause cannot contain aggregate functions. The HAVING clause can contain aggregate functions

Disabling Triggers in Oracle PL/SQL


Disabling Triggers

To disable or enable a trigger:

alter trigger {disable | enable};

Viewing Defined Triggers in Oracle

Viewing Defined Triggers

To view all the defined triggers, use:

select name_of_trigger from user_triggers;

For more details on a particular trigger:

select trigger_type, triggering_event, table_name, referencing_names, trigger_body
from user_triggers
where trigger_name = '';

Displaying Trigger Errors in Oracle

Displaying Trigger Errors

If we get a message Warning: Trigger created with compilation errors. you can check the error messages with:

Show errors trigger ;

You can also type, SHO ERR (SHOW ERRORS) to see the most recent compilation error.

Types of Triggers in Oracle

Row Triggers and Statement Triggers: A statement trigger is fired once on behalf of the triggering statement, regardless of the number of rows in the table that the triggering statement affects. A row trigger fires once for each row affected by the triggering event.

BEFORE and AFTER Triggers: BEFORE triggers run the trigger action before the triggering statement is run. AFTER triggers run the trigger action after the triggering statement is run.

INSTEAD OF Triggers: INSTEAD OF triggers describe how to perform insert, update, and delete operations against views that are too complex to support these operations natively. INSTEAD OF triggers allow applications to use a view as the sole interface for all SQL operations (insert, delete, update and select).

Triggers on System Events and User Events: You can use triggers to publish information about database events to subscribers. System events are for example Database startup and shutdown, Data Guard role transitions etc and User Events are User logon and logoff, DDL statements (CREATE, ALTER, and DROP) etc

Example of PL/SQL trigger in Oracle


In the below example line 2 is A triggering event or statement, lines 4-9 are A trigger action.

Example of creating a trigger based on the following two tables:

CREATE TABLE T1 (a INTEGER);
CREATE TABLE T2 (b INTEGER);

We will create a trigger that may insert a tuple into T2 when a tuple is inserted into T1. The trigger checks if the inserted row in T1 is has a value less than 5 only then a tuple is inserted in T2.

1 CREATE TRIGGER tr1
2 AFTER INSERT ON T1
3 REFERENCING NEW AS newRow
4 FOR EACH ROW
5 WHEN (newRow.a <= 5)
6 BEGIN
7 INSERT INTO T2
VALUES(:newRow.a);
8 END tr1;
9 .
10 run;

PL/SQL Triggers in Oracle

PL/SQL Triggers

A PL/SQL trigger is a construct in PL/SQL that runs or "triggered" on event of changes being made to a table in the database. The triggering event is a INSERT, UPDATE or DELETE done on a table. The trigger can be made so it can be "fired" either BEFORE or AFTER the Data Manipulation Language is executed.

  • A database trigger is a block of code that is automatically executed in response to certain events.
  • Triggers are executed implicitly whenever the triggering event happens.
  • The triggering event is an INSERT, DELETE, or UPDATE command.
  • The timing can be either BEFORE or AFTER, INSTEAD OF trigger.

The trigger can be either row-level or statement-level, where the former fires once for each row affected by the triggering statement and the latter fires once for the whole statement.

You can write triggers that fire whenever one of the following operations occurs:

  1. DML statements (INSERT, UPDATE, DELETE) on a particular table or view, issued by any user

  2. DDL statements (CREATE or ALTER primarily) issued either by a particular schema/user or by any schema/user in the database

  3. Database events, such as logon/logoff, errors, or startup/shutdown, also issued either by a particular schema/user or by any schema/user in the database

A trigger has three basic parts:

  • A triggering event or statement
  • A trigger restriction
  • A trigger action

Oracle PL/SQL Collections

Records
    Table Based Records Table Based Records Cursor Based Records Cursor Based Records Programmer-defined Records Programmer-defined Records
PL/SQL Tables PL/SQL Tables

Varrays Varrays

Nested Tables Nested Tables

PL/SQL Function Example 2 in Oracle

Example 2 of PL/SQL Function:

create or replace function find_area
(Len in number, Wid in number)
return number
as
varea number;
begin
varea := Len * Wid;
return varea;
end;

SQL> select find_area (10, 30) area from dual;

AREA
---------
300

PL/SQL Function Example in Oracle

Example 1 of PL/SQL Function:

Creating a Function: Examples The following statement creates the function Ask_Balance on the sample table cust_orders (the PL/SQL is in italics):

CREATE FUNCTION Ask_Balance(acc_num IN NUMBER) 
   RETURN NUMBER 
   IS acc_bal NUMBER(11,2);
   BEGIN 
      SELECT order_total 
      INTO acc_bal 
      FROM cust_orders 
      WHERE customer_id = acc_num; 
      RETURN(acc_bal); 
    END;
/

The Ask_Balance function returns the balance of a specified account.

When you call the function, you must specify the argument acc_num, the number of the account whose balance is sought. The datatype of acc_num is NUMBER.

The function returns the account balance. The RETURN clause of the CREATE FUNCTION statement specifies the datatype of the return value to be NUMBER.

The function uses a SELECT statement to select the balance column from the row identified by the argument acc_num in the cust_orders table. The function uses a RETURN statement to return this value to the environment in which the function is called.

The function created in the preceding example can be used in a SQL statement. For example:

SELECT Ask_Balance(165) FROM DUAL;

Ask_Balance(165)
------------
2519

[Source]

Syntax of PL/SQL function in Oracle

PL/SQL Function

There are two types of PL/SQL blocks: named block and an anonymous block.
There are two types of named blocks: Functions and Procedures
 
FUNCTION name [(parameter[, parameter, …])] RETURN
datatype IS
[local declarations]
BEGIN
executable statements
[EXCEPTION
exception handlers]
END [name];

PL/SQL Function in Oracle

PL/SQL Function

There are two types of PL/SQL blocks: named block and an anonymous block.
There are two types of named blocks: Functions and Procedures

In PL/SQL a Function takes zero or more parameter values and returns one value.

Syntax of PL/SQL Procedure in Oracle

PROCEDURE name [(parameter[, parameter, …])] IS
[local declarations]
BEGIN
executable statements
[EXCEPTION
exception handlers]
END [name];

Example 1 of PL/SQL Procedure

create or replace procedure get_area
(Len in number, Wid in number, Area out number)
as
begin
Area := Len * Wid;
end;

SQL> variable area1 number;
SQL> execute get_area (10, 50, :area1);
PL/SQL procedure successfully completed.
SQL> print area1
AREA1
---------
500

Example 2 of PL/SQL Procedure

The following statement creates the procedure remove_emp in the schema hr. The PL/SQL is shown in italics:

CREATE PROCEDURE remove_emp (employee_id NUMBER) AS
tot_emps NUMBER;
BEGIN
DELETE FROM employees
WHERE employees.employee_id = remove_emp.employee_id;
tot_emps := tot_emps - 1;
END;
/


The remove_emp procedure removes a specified employee. When you call the procedure, you must specify the employee_id of the employee to be removed.

The procedure uses a DELETE statement to remove from the employees table the row of employee_id. [Source]

PL/SQL Procedures In Oracle

There are two types of PL/SQL blocks: named block and an anonymous block.
There are two types of named blocks: Functions and Procedures

A stored procedure is a PL/SQL block that accepts zero or more parameters as input (IN), output (OUT), or both (INOUT). PL/SQL Procedures do not return a value; instead the INOUT parameter or OUT parameter may be used to pass a value from the procedure. Procedures cannot be used in SQL statements; they are invoked using the EXECUTE command or called inside a PL/SQL block.

%TYPE and %ROWTYPE in Oracle

%TYPE is used to declare a variable that is of the same type as a specified table’s column.

Emp_number emp_name.emp_nameno%type;

%ROWTYPE is used to declare a record (variable that represents the entire row of a table).

Emp_record emp_name%rowtype;

Another example of declaring variable:

Declare
name varchar2(30);
Select emp_name_name into name from emp_name where emp_nameno = 203456;
Begin
Null;
End;

Any DML statements should be after Begin statement;

Begin
Delete from emp_name where emp_nameno = 24545459;
Commit;
End;

Declaring PL/SQL variables and constants in Oracle

Example of declaring Variableiables:

Variable1 varchar2(100);
Join_date Date;
Variable2 number default 5;
Variable3 number not null := 2;

Not Null means a value may change but it can never be assigned Null.

Variable4 varchar2(20) := Null;
Variable5 varchar2(20) default Null;

Example of declaring Constants:

Variable_constant constant number := 100;

Constants cannot be changed.

You must initialize constants at the time of declaration.

Oracle Syntax of a PL/SQL Block

DECLARE
Variable_declarations
BEGIN
Program_code
EXCEPTION
Exception_handlers
END;

Below is the basic structure of the PL/SQL program:

Set serveroutput on
Var1 varchar2(20);
Begin
Var1 := ‘welcome’;
Dbms_output.put_line(var1);
Exception
When others then
Dbms_output.put_line(‘It is an exception’);
End;
/
In the declaration section all the variables and constants are defined.
  1. In PL/SQL all the errors are handled in the Exception block.
  2. Begin and End are mandatory statements indicating begin and end of the PL/SQL Block.
  3. Variables and Constants must be declared first before they can be used.
  4. The declaration of variables and constants are alike, but constant definitions must contain the keyword CONSTANT and must be assigned a value as part of the definition. Later on any attempts to assign a value to a constant will result in an error message.
  5. Values can be assigned to variables directly using the “:=” assignment operator, by way of a SELECT ... INTO statement or When used as OUT or IN OUT parameter from a procedure.

Oracle PL/SQL Introduction |Oracle PL/SQL Tutorial

PL/SQL stands for Procedural Language/SQL. PL/SQL is Oracle's Procedural Language extension to SQL. PL/SQL expands SQL by adding constructs found in procedural languages, resulting in a structural language that is more powerful than SQL. Basically it runs on the database server, but a few Oracle products such as Developer/2000 also contain a PL/SQL engine that resides on the client. Thus, you can run your PL/SQL code on either the client or the server depending on which is more suitable for the task at hand.

Unlike SQL, PL/SQL is procedural, not declarative.

A declarative (non-procedural) programming language is a language that allows the programmer to state the task to be accomplished without specifying the procedures needed to carry it out.

A Procedural programming language is a language in which programs largely consist of a series of commands to assign values to objects.

The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be nested within each other. Typically, each block performs a logical action in the program. PL/SQL is Block Structured.

NavigableSet in Java 6.0

NavigableSet API is included in the SCJP 6.0 certification exam. This article explains few important methods with simple example program. NavigableSet is the subinterface of SortedSet. This interface defines methods for finding the element in a list. For example lower() method used for finding the element which is less than the given value. Look into the following example:

package NavigableTutorial.net;

import java.util.ArrayList;
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeSet;

public class NavigableSetTutorial1 {
    public static void main(String args[]){
        List list = new ArrayList();
        list.add(3);
        list.add(4);
        list.add(1);
        list.add(8);
        list.add(7);
        list.add(10);
       
        NavigableSet navigableSet = new TreeSet(list);
        System.out.println(navigableSet.lower(8));
        System.out.println(navigableSet.higher(8));
       
    }
}


Output:
7
10

In the above code, NavigableSet.lower() method is used for reteriving the value which is less than '8' in the list. Same way NavigableSet.higher() is used for reteriving the value greater than '8' in the list.

Java 6 - NavigableSet -headSet and tailSet Example Java Collections Framework

The below example explains the headSet and tailSet methods of the NavigableSet.

package examples;

import java.util.NavigableSet;
import java.util.TreeSet;
public class NavigableSetExample {

public static void main(String[] args) {
NavigableSet set = new TreeSet();
// Add elements in to the Navigable Set
set.add(1);
set.add(2);
set.add(3);
System.out.println(set);

// Head Set
System.out.println("Head Set :" + set.headSet(2));
System.out.println("Head Set including given integer: "+ set.headSet(2, true));

// Tail Set
System.out.println("Tail Set" + set.tailSet(2));
System.out.println("Tail Set including given integer: " + set.tailSet(2, false));
}

}

[1, 2, 3]
Head Set :[1]
Head Set including given integer: [1, 2]
Tail Set[2, 3]
Tail Set including given integer: [3]

NavigableSet - pollFirst and pollLast example Java Collections

pollFirst(), pollLast() methods of NavigableSet can be used to remove first and last element of the Set respectively. The below program explains the pollFirst() and pollLast()


package examples;

import java.util.NavigableSet;
import java.util.TreeSet;

public class NavigableSetExample {

public static void main(String args[]){
NavigableSet navigableSet = new TreeSet();

navigableSet.add(1);
navigableSet.add(2);

System.out.println("Set : " + navigableSet);

navigableSet.pollFirst();

System.out.println("Set After pollFirst " + navigableSet);

navigableSet.add(3);
navigableSet.add(4);

System.out.println("Set " + navigableSet);

navigableSet.pollLast();

System.out.println("Set after pollLast " +navigableSet);

}

}

Output:


Set : [1, 2]
Set After pollFirst [2]
Set [2, 3, 4]
Set after pollLast [2, 3]

Java Collections Tutorial Navigable Map Example

package JAVATUTORIAL;
import java.util.*;
import java.util.concurrent.*;

public class NavigableMapTutorial{
      public static void main(String[] args) {
        System.out.println("Navigable Map Example!\n");
        NavigableMap navMapObj = new
                           ConcurrentSkipListMap();
        navMapObj.put(1, "S");
        navMapObj.put(2, "February");
        navMapObj.put(3, "March");
        navMapObj.put(4, "April");
        navMapObj.put(5, "May");
        navMapObj.put(6, "June");
        navMapObj.put(7, "July");
        navMapObj.put(8, "August");
        navMapObj.put(9, "September");
        navMapObj.put(10, "October");
        navMapObj.put(11, "November");
        navMapObj.put(12, "December");
        //Displaying all data
        System.out.println("Data in Navigable Map is : " +
                                              navMapObj.descendingMap()+"\n");
        //Retrieving first data
        System.out.print("First data: " + navMapObj.firstEntry()+"\n");
        //Retrieving last data
        System.out.print("Last data: " + navMapObj.lastEntry()+"\n\n");
        //Retrieving the nreatest less than or equal to the given key
        System.out.print("Nearest less than or equal to the given key: "
                                + navMapObj.floorEntry(5)+"\n");
        //Retrieving the greatest key strictly less than the given key
        System.out.println("Retrieving the greatest key strictly less than the given key"+ navMapObj.lowerEntry(3));
        //Retrieving a key-value associated with the least key
                        //strictly greater than the given key
        System.out.println("Retriving data from navigable map greter than   the given key: " + navMapObj.higherEntry(5)+"\n");
        //Removing first
        System.out.println("Removing First: " + navMapObj.pollFirstEntry());
        //Removing last
        System.out.println("Removing Last: " + navMapObj.pollLastEntry()+"\n");
        //Displaying all data
        System.out.println("Now data: " + navMapObj.descendingMap());
      }
    }
     
Description of program:

The following program helps you in inserting, removing and retrieving the data from the NavigableMap. It uses the put() method to add the element. If you want to retrieve the data at first and last position from the NavigableMap, you use the firstEntry() and lastEntry() methods. The descendingMap() method represents all data to the NavigableMap in descending order.

You can retrieve the nearest less than or equal to the given number and the greatest key strictly less than the given number floorEntry() and lowerEntry() methods. And you retrieve a key-value associated with the least key strictly greater than the given key, you use the higherEntry() method. The pollFirstEntry() method removes the first data from the NavigableMap and pollLastEntry() method also removes the data at the last position from the NavigableMap.

JDK 6 Collections-related APIs & Developer Guides |Java 6.0 Collection Framework

Java 6.0 New Collection APIs an Overview
The following are the new collection APIs introduced in Java 6.0. I listes them as Interfaces and classes.
New Interfaces
  • Deque
  • BlockingDeque
  • NavigableSet
  • NavigableMap
New Classes
  • ArrayDeque
  • LinkedBlockingDeque
  • ConcurrentSkipListSet
  • ConcurrentSkipListMap
  • AbstractMap.SimpleEntry
  • AbstractMap.SimpleImmutableEntry
Updated Classes in Java 6.0
  • LinkedList
  • TreeSet
  • TreeMap
  • Collections

Advantages and Disadvantages of the Java Collection Framework

A collection is simply an object that groups multiple elements into a single unit. It is also called as a container sometimes. It is used to store, retrieve, manipulate, and communicate aggregate data. Typically, it represents data items that form a natural group and allows duplicate elements while others do not. It consists of both ordered and unordered elements. 

The primary advantages of a collections framework are that it:

Reduces programming effort by providing useful data structures and algorithms so you don't have to write them yourself.
Increases performance by providing high-performance implementations of useful data structures and algorithms. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations.
Provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth.
Reduces the effort required to learn APIs by eliminating the need to learn multiple ad hoc collection APIs.
Reduces the effort required to design and implement APIs by eliminating the need to produce ad hoc collections APIs.
Fosters software reuse by providing a standard interface for collections and algorithms to manipulate them.

Disadvantages of collections framework:

It must cast to correct type.
It can't be done compile-time type checking.

What is Collection Framework in Java?

A collection is an object that represents a group of objects (such as the familiar Vector class). A collections framework is a unified architecture for representing and manipulating collections, allowing them to be manipulated independently of the details of their representation.

collections is a group of objects known as its elements. Basically it is a package of data structures that includes ArrayLists, LinkedLists, HashSets, etc. A collection is simply an object that groups multiple elements into a single unit. It is also called as a container sometimes. It is used to store, retrieve, manipulate, and communicate aggregate data. Typically, it represents data items that form a natural group and allows duplicate elements while others do not. It consists of both ordered and unordered elements. There is no direct implementation of this interface however SDK provides implementations of more specific sub interfaces like Set and List. The manipulation and passing of collections is done by this interface.

How to configure AUTOTRACE in SQLPLUS for database user?

1. Change directory path and connect with SYSTEM user to database
C:\>cd c:\oracle\product\10.1.0\db_1\rdbms\admin

C:\Oracle\product\10.1.0\Db_1\RDBMS\ADMIN>sqlplus /nolog

SQL*Plus: Release 9.0.1.0.1 - Production on Tue Oct 16 17:08:20 2007

(c) Copyright 2001 Oracle Corporation. All rights reserved.

SQL> conn system/manager
Connected.

2. run UTLXPLAN.SQL script for plan table.
SQL> @utlxplan.sql

3. Create public synonym for plan table or grant all privilege.
SQL> create public synonym plan_table for plan_table;

SQL> grant all on plan_table to public;

Grant succeeded.

4. Exit and again change directory path and connect with SYS user to database
SQL> exit
Disconnected from Oracle9i Enterprise Edition Release 9.0.1.1.1 - Production
With the Partitioning option
JServer Release 9.0.1.1.1 - Production

C:\Oracle\product\10.1.0\Db_1\RDBMS\ADMIN>cd\

C:\>cd c:\oracle\product\10.1.0\db_1\sqlplus\admin

C:\Oracle\product\10.1.0\Db_1\sqlplus\admin>sqlplus /nolog

SQL*Plus: Release 9.0.1.0.1 - Production on Tue Oct 16 17:12:07 2007

(c) Copyright 2001 Oracle Corporation. All rights reserved.

SQL> conn sys as sysdba
Enter password:
Connected.

5. run plustrce script and script must be run with SYS user.
SQL> @plustrce
SQL>
SQL> drop role plustrace;

Role dropped.

SQL> create role plustrace;

Role created.

SQL>
SQL> grant select on v_$sesstat to plustrace;

Grant succeeded.

SQL> grant select on v_$statname to plustrace;

Grant succeeded.

SQL> grant select on v_$mystat to plustrace;

Grant succeeded.

SQL> grant plustrace to dba with admin option;

Grant succeeded.

SQL> set echo off

6. Grant plustrace role to public.
SQL> grant plustrace to public;

Grant succeeded.

Samba Configuration for Linux Directory access from windows|Linux In a Windows Network with SAMBA

Kindly go through the below mentioned site

http://www.computernetworkingnotes.com/rhce_certification/samba_server.htm

step
1. install rpm package for smb (samba)
2. edit smb.conf (path= /etc/samba/smb.conf)
and add the directory name and user which you want to share
3. create same user as windows who access the directory from windows.
for example: windows user is "admin" which will access the linux shared directory.
then we need to create the same user in linux server also with the same password.

4. add user to smb
$smbpasswd -a [username]

5. restart smb services
$service smb restart
or
$service /sbin/samba/smb restart

ORA-00020: maximum number of processes (%s) exceeded in Oracle 10g,Oracle 11g

ORA-20 "maximum number of processes (%s) exceeded"

Cause: An ORA-20 "maximum number of processes (%s) exceeded" occurs when the number of OS processes for the instance exceeds the PROCESSES parameter

and i am not able to connect to sys as sysdba user too.
C:\>sqlplus / as sysdba

SQL*Plus: Release 11.2.0.2.0 Production on Wed Jan 26 08:58:09 2011

Copyright (c) 1982, 2010, Oracle. All rights reserved.

ERROR:
ORA-00020: maximum number of processes (150) exceeded


but there is a alternative which we can use to connect to sys as sysdba user.

C:\>sqlplus -prelim / as sysdba

SQL*Plus: Release 11.2.0.2.0 Production on Wed Jan 26 08:58:54 2011

Copyright (c) 1982, 2010, Oracle. All rights reserved.


Solution:
1. Increase the processes parameter Or
2. Kill KBCOOK process at OS level.

$ ps -ef | grep KBCOOK

oracle 17555 1 0 04:48 ? 00:00:00 ora_pmon_KBCOOK
oracle 17557 1 0 04:48 ? 00:00:00 ora_vktm_KBCOOK
oracle 17561 1 0 04:48 ? 00:00:00 ora_diag_KBCOOK
oracle 17563 1 0 04:48 ? 00:00:00 ora_dbrm_KBCOOK
oracle 17565 1 0 04:48 ? 00:00:00 ora_psp0_KBCOOK
oracle 17569 1 0 04:48 ? 00:00:00 ora_dia0_KBCOOK
oracle 17571 1 0 04:48 ? 00:00:00 ora_mman_KBCOOK
oracle 17573 1 0 04:48 ? 00:00:00 ora_dbw0_KBCOOK
oracle 17575 1 0 04:48 ? 00:00:00 ora_lgwr_KBCOOK
oracle 17577 1 0 04:48 ? 00:00:00 ora_ckpt_KBCOOK
oracle 17579 1 0 04:48 ? 00:00:00 ora_smon_KBCOOK
oracle 17581 1 0 04:48 ? 00:00:00 ora_reco_KBCOOK
oracle 17583 1 0 04:48 ? 00:00:00 ora_mmon_KBCOOK
oracle 17585 1 0 04:48 ? 00:00:00 ora_mmnl_KBCOOK
oracle 17587 1 0 04:48 ? 00:00:00 ora_d000_KBCOOK
oracle 17589 1 0 04:48 ? 00:00:00 ora_s000_KBCOOK
oracle 17608 1 0 04:48 ? 00:00:00 ora_smco_KBCOOK
oracle 17610 1 0 04:48 ? 00:00:00 ora_fbda_KBCOOK
oracle 17612 1 0 04:48 ? 00:00:00 ora_qmnc_KBCOOK
oracle 17641 1 0 04:48 ? 00:00:00 ora_q000_KBCOOK
oracle 17671 1 0 04:49 ? 00:00:00 ora_q001_KBCOOK
oracle 17761 1 0 04:50 ? 00:00:00 oracleKBCOOK (LOCAL=NO)
oracle 18480 1 0 04:58 ? 00:00:00 ora_w000_KBCOOK
oracle 18608 17126 0 05:00 pts/1 00:00:00 grep KBCOOK

$ kill -9 17761

$ ps -ef | grep KBCOOK

oracle 17555 1 0 04:48 ? 00:00:00 ora_pmon_KBCOOK
oracle 17557 1 0 04:48 ? 00:00:00 ora_vktm_KBCOOK
oracle 17561 1 0 04:48 ? 00:00:00 ora_diag_KBCOOK
oracle 17563 1 0 04:48 ? 00:00:00 ora_dbrm_KBCOOK
oracle 17565 1 0 04:48 ? 00:00:00 ora_psp0_KBCOOK
oracle 17569 1 0 04:48 ? 00:00:00 ora_dia0_KBCOOK
oracle 17571 1 0 04:48 ? 00:00:00 ora_mman_KBCOOK
oracle 17573 1 0 04:48 ? 00:00:00 ora_dbw0_KBCOOK
oracle 17575 1 0 04:48 ? 00:00:00 ora_lgwr_KBCOOK
oracle 17577 1 0 04:48 ? 00:00:00 ora_ckpt_KBCOOK
oracle 17579 1 0 04:48 ? 00:00:00 ora_smon_KBCOOK
oracle 17581 1 0 04:48 ? 00:00:00 ora_reco_KBCOOK
oracle 17583 1 0 04:48 ? 00:00:00 ora_mmon_KBCOOK
oracle 17585 1 0 04:48 ? 00:00:00 ora_mmnl_KBCOOK


Refer Metalink Note: [ID 825045.1] for more details.

ORA-16006: audit_trail destination incompatible with database open mode on redhat 5.2 10gr2 (10.2.0.4)

 ORA-16006: audit_trail destination incompatible with database open mode
while i was trying to open standby database got below error message

ORA-16006: audit_trail destination incompatible with database open mode

at little search on metalink found below note: ID 835638.1

solution:

SQL>alter system set audit_trail=OS scope=spfile;
 

How to Create AWR Report in Oracle 10g?

he remaining procedures in the dbms_workload_repository package are awr_report_text and awr_report_html, which generate the AWR report for the specified snapshot range in text or HTML formats, respectively.  The following script segment shows how to retrieve the AWR text report for any snapshot range or duration:
SELECT
   output 
FROM    TABLE(dbms_workload_repository.awr_report_text (45634523,1,5600,5612 ));
The sample output below shows the typical report generated for AWR data.  The output displays shows the four arguments to the awr_report_text stored procedure:
§       The database ID is 37933856.
§       The instance number for RAC is 1.
§       The starting snapshot number is5600
§       The ending snapshot number is5612

AWR Reports |Workload Repository Reports in Oracle 10g

Oracle provide two scripts to produce workload repository reports (awrrpt.sql and awrrpti.sql). They are similar in format to the statspack reports and give the option of HTML or plain text formats. The two reports give essential the same output but the awrrpti.sql allows you to select a single instance. The reports can be generated as follows:
@$ORACLE_HOME/rdbms/admin/awrrpt.sql
@$ORACLE_HOME/rdbms/admin/awrrpti.sql
The scripts prompt you to enter the report format (html or text), the start snapshot id, the end snapshot id and the report filename. The resulting report can be opend in a browser or text editor accordingly.

What are the Workload Repository Views AWR Views in Oracle 10g?

Workload Repository Views

The following workload repository views are available:
  • V$ACTIVE_SESSION_HISTORY - Displays the active session history (ASH) sampled every second.
  • V$METRIC - Displays metric information.
  • V$METRICNAME - Displays the metrics associated with each metric group.
  • V$METRIC_HISTORY - Displays historical metrics.
  • V$METRICGROUP - Displays all metrics groups.
  • DBA_HIST_ACTIVE_SESS_HISTORY - Displays the history contents of the active session history.
  • DBA_HIST_BASELINE - Displays baseline information.
  • DBA_HIST_DATABASE_INSTANCE - Displays database environment information.
  • DBA_HIST_SNAPSHOT - Displays snapshot information.
  • DBA_HIST_SQL_PLAN - Displays SQL execution plans.
  • DBA_HIST_WR_CONTROL - Displays AWR settings.

What is AWR Report in Oracle 10g?

Automatic Workload Repository (AWR) in Oracle Database 10g

Oracle have provided many performance gathering and reporting tools over the years. Originally the UTLBSTAT/UTLESTAT scripts were used to monitor performance metrics. Oracle8i introduced the Statspack functionality which Oracle9i extended. In Oracle 10g statspack has evolved into the Automatic Workload Repository (AWR).

AWR Features

The AWR is used to collect performance statistics including:
  • Wait events used to identify performance problems.
  • Time model statistics indicating the amount of DB time associated with a process from the V$SESS_TIME_MODEL and V$SYS_TIME_MODEL views.
  • Active Session History (ASH) statistics from the V$ACTIVE_SESSION_HISTORY view.
  • Some system and session statistics from the V$SYSSTAT and V$SESSTAT views.
  • Object usage statistics.
  • Resource intensive SQL statements.
The repository is a source of information for several other Oracle 10g features including:
  • Automatic Database Diagnostic Monitor
  • SQL Tuning Advisor
  • Undo Advisor
  • Segment Advisora

Inheritance,Inheritance in Java,Java Inheritance

Q2) What is inheritance?
Ans) Inheritance is the property which allows a Child class to inherit some properties from its parent class. In Java this is achieved by using extends keyword. Only properties with access modifier public and protected can be accessed in child class.
public class Parent{
public String parentName;
public int parentage;
public String familyName;
}
public class Child extends Parent{
public String childName;
public int childAge;
public void printMyName(){
System.out.println(“ My name is “+ chidName+” “ +familyName)
}
}
In above example the child has inherit its family name from the parent class just by inheriting the class.

UNIX interview questions

  1. What are the main differences between Apache 1.x and 2.x?
  2. What does the “route” command do?
  3. What are the read/write/execute bits on a directory mean?
  4. What does iostat do?
  5. what does vmstat do?
  6. What does netstat do?
  7. What is the most graceful way to bring a system into single user mode?
  8. How do you determine disk usage?
  9. What is AWK?
  10. What is SED?
  11. What is the difference between binaries in /bin, and /usr/bin?
  12. What is a dynamically linked file?
  13. What is a statically linked file?

Java Polymorphism - OOPS |Java - Polymorphism

Q1) What is polymorphism?
Ans) Polymorphism gives us the ultimate flexibility in extensibility. The abiltiy to define more than one function with the same name is called Polymorphism. In java,c++ there are two type of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).

When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time. Overriding occurs when a class method has the same name and signature as a method in parent class.
Overloading occurs when several methods have same names with
  • Overloading is determined at the compile time.
  • Different method signature and different number or type of parameters.
  • Same method signature but different number of parameters.
  • Same method signature and same number of parameters but of different type

Example of Overloading
     int add(int a,int b)
     float add(float a,int b)
     float add(int a ,float b)
     void add(float a)
     int add(int a)
     void add(int a)                 //error conflict with the method int add(int a)
    Example: Overloading

Class BookDetails{
            String title;
            String publisher;
            float price;
setBook(String title){
}
setBook(String title, String publisher){
}
setBook(String title, String publisher,float price){
}

}

Example: Overriding
class BookDetails{
            String title;
setBook(String title){ }
}
class ScienceBook extends BookDetails{
            setBook(String title){}                                             //overriding
setBook(String title, String publisher,float price){ }  //overloading
}

Java interview questions & answers -Set 4

  1. What is the difference between an applet and a servlet?- a) Servlets are to servers what applets are to browsers. b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.
  2. What is the difference between doPost and doGet methods?- a) doGet() method is used to get information, while doPost() method is used for posting information. b) doGet() requests can’t send large amount of information and is limited to 240-255 characters. However, doPost()requests passes all of its data, of unlimited length. c) A doGet() request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.
  3. What is the life cycle of a servlet?- Each Servlet has the same life cycle: a) A server loads and initializes the servlet by init () method. b) The servlet handles zero or more client’s requests through service() method. c) The server removes the servlet through destroy() method.
  4. Who is loading the init() method of servlet?- Web server
  5. What are the different servers available for developing and deploying Servlets?- a) Java Web Server b) JRun g) Apache Server h) Netscape Information Server i) Web Logic
  6. How many ways can we track client and what are they?- The servlet API provides two ways to track client state and they are: a) Using Session tracking and b) Using Cookies.
  7. What is session tracking and how do you track a user session in servlets?- Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are: a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password. b) Hidden form fields - fields are added to an HTML form that are not displayed in the client’s browser. When the form containing the fields is submitted, the fields are sent back to the server. c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change. d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser. e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session. maxresidents property.
  8. What is Server-Side Includes (SSI)?- Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with an . shtml extension.
  9. What are cookies and how will you use them?- Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user. a) Create a cookie with the Cookie constructor: public Cookie(String name, String value) b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse: public void HttpServletResponse. addCookie(Cookie cookie) c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest: public Cookie[ ] HttpServletRequest. getCookie().
  10. Is it possible to communicate from an applet to servlet and how many ways and how?- Yes, there are three ways to communicate from an applet to servlet and they are: a) HTTP Communication(Text-based and object-based) b) Socket Communication c) RMI Communication
  11. What is connection pooling?- With servlets, opening a database connection is a major bottleneck because we are creating and tearing down a new connection for every page request and the time taken to create connection will be more. Creating a connection pool is an ideal approach for a complicated servlet. With a connection pool, we can duplicate only the resources we need to duplicate rather than the entire servlet. A connection pool can also intelligently manage the size of the pool and make sure each connection remains valid. A number of connection pool packages are currently available. Some like DbConnectionBroker are freely available from Java Exchange Works by creating an object that dispenses connections and connection Ids on request. The ConnectionPool class maintains a Hastable, using Connection objects as keys and Boolean values as stored values. The Boolean value indicates whether a connection is in use or not. A program calls getConnection() method of the ConnectionPool for getting Connection object it can use; it calls returnConnection() to give the connection back to the pool.
  12. Why should we go for interservlet communication?- Servlets running together in the same server communicate with each other in several ways. The three major reasons to use interservlet communication are: a) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object) b) Servlet reuse - allows the servlet to reuse the public methods of another servlet. c) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation)
  13. Is it possible to call servlet with parameters in the URL?- Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).
  14. What is Servlet chaining?- Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. In servlet chaining, one servlet’s output is piped to the next servlet’s input. This process continues until the last servlet is reached. Its output is then sent back to the client.
  15. How do servlets handle multiple simultaneous requests?- The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost() and service()) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.
  16. What is the difference between TCP/IP and UDP?- TCP/IP is a two-way communication between the client and the server and it is a reliable and there is a confirmation regarding reaching the message to the destination. It is like a phone call. UDP is a one-way communication only between the client and the server and it is not a reliable and there is no confirmation regarding reaching the message to the destination. It is like a postal mail.
  17. What is Inet address?- Every computer connected to a network has an IP address. An IP address is a number that uniquely identifies each computer on the Net. An IP address is a 32-bit number.
  18. What is Domain Naming Service(DNS)?- It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters. For example, www. mascom. com implies com is the domain name reserved for US commercial sites, moscom is the name of the company and www is the name of the specific computer, which is mascom’s server.
  19. What is URL?- URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL has four components: http://www. address. com:80/index.html, where http - protocol name, address - IP address or host name, 80 - port number and index.html - file path.
  20. What is RMI and steps involved in developing an RMI object?- Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are: a) Define the interfaces b) Implementing these interfaces c) Compile the interfaces and their implementations with the java compiler d) Compile the server implementation with RMI compiler e) Run the RMI registry f) Run the application
  21. What is RMI architecture?- RMI architecture consists of four layers and each layer performs specific functions: a) Application layer - contains the actual object definition. b) Proxy layer - consists of stub and skeleton. c) Remote Reference layer - gets the stream of bytes from the transport layer and sends it to the proxy layer. d) Transportation layer - responsible for handling the actual machine-to-machine communication.
  22. what is UnicastRemoteObject?- All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objects available from remote machines.
  23. Explain the methods, rebind() and lookup() in Naming class?- rebind() of the Naming class(found in java. rmi) is used to update the RMI registry on the server machine. Naming. rebind(”AddSever”, AddServerImpl); lookup() of the Naming class accepts one argument, the rmi URL and returns a reference to an object of type AddServerImpl.
  24. What is a Java Bean?- A Java Bean is a software component that has been designed to be reusable in a variety of different environments.
  25. What is a Jar file?- Jar file allows to efficiently deploying a set of classes and their associated resources. The elements in a jar file are compressed, which makes downloading a Jar file much faster than separately downloading several uncompressed files. The package java. util. zip contains classes that read and write jar files.
  26. What is BDK?- BDK, Bean Development Kit is a tool that enables to create, configure and connect a set of set of Beans and it can be used to test Beans without writing a code.
  27. What is JSP?- JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The suffix traditionally ends with .jsp to indicate to the web server that the file is a JSP files. JSP is a server side technology - you can’t do any client side validation with it. The advantages are: a) The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of HTML but it is a tedious process. b) It is easy to make a change and then let the JSP capability of the web server you are using deal with compiling it into a servlet and running it.
  28. What are JSP scripting elements?- JSP scripting elements lets to insert Java code into the servlet that will be generated from the current JSP page. There are three forms: a) Expressions of the form <%= expression %> that are evaluated and inserted into the output, b) Scriptlets of the form<% code %>that are inserted into the servlet’s service method, and c) Declarations of the form <%! Code %>that are inserted into the body of the servlet class, outside of any existing methods.
  29. What are JSP Directives?- A JSP directive affects the overall structure of the servlet class. It usually has the following form:<%@ directive attribute=”value” %> However, you can also combine multiple attribute settings for a single directive, as follows:<%@ directive attribute1=”value1″ attribute 2=”value2″ . . . attributeN =”valueN” %> There are two main types of directive: page, which lets to do things like import classes, customize the servlet superclass, and the like; and include, which lets to insert a file into the servlet class at the time the JSP file is translated into a servlet
  30. What are Predefined variables or implicit objects?- To simplify code in JSP expressions and scriptlets, we can use eight automatically defined variables, sometimes called implicit objects. They are request, response, out, session, application, config, pageContext, and page.
  31. What are JSP ACTIONS?- JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include: jsp:include - Include a file at the time the page is requested. jsp:useBean - Find or instantiate a JavaBean. jsp:setProperty - Set the property of a JavaBean. jsp:getProperty - Insert the property of a JavaBean into the output. jsp:forward - Forward the requester to a newpage. Jsp: plugin - Generate browser-specific code that makes an OBJECT or EMBED
  32. How do you pass data (including JavaBeans) to a JSP from a servlet?- (1) Request Lifetime: Using this technique to pass beans, a request dispatcher (using either “include” or forward”) can be called. This bean will disappear after processing this request has been completed. Servlet: request. setAttribute(”theBean”, myBean); RequestDispatcher rd = getServletContext(). getRequestDispatcher(”thepage. jsp”); rd. forward(request, response); JSP PAGE:(2) Session Lifetime: Using this technique to pass beans that are relevant to a particular session (such as in individual user login) over a number of requests. This bean will disappear when the session is invalidated or it times out, or when you remove it. Servlet: HttpSession session = request. getSession(true); session. putValue(”theBean”, myBean); /* You can do a request dispatcher here, or just let the bean be visible on the next request */ JSP Page: 3) Application Lifetime: Using this technique to pass beans that are relevant to all servlets and JSP pages in a particular app, for all users. For example, I use this to make a JDBC connection pool object available to the various servlets and JSP pages in my apps. This bean will disappear when the servlet engine is shut down, or when you remove it. Servlet: GetServletContext(). setAttribute(”theBean”, myBean); JSP PAGE:
  33. How can I set a cookie in JSP?- response. setHeader(”Set-Cookie”, “cookie string”); To give the response-object to a bean, write a method setResponse (HttpServletResponse response) - to the bean, and in jsp-file:<% bean. setResponse (response); %>
  34. How can I delete a cookie with JSP?- Say that I have a cookie called “foo, ” that I set a while ago & I want it to go away. I simply: <% Cookie killCookie = new Cookie(”foo”, null); KillCookie. setPath(”/”); killCookie. setMaxAge(0); response. addCookie(killCookie); %>
  35. How are Servlets and JSP Pages related?- JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.

Java interview questions & answers -Set 4

  • Which containers use a Border layout as their default layout?- Window, Frame and Dialog classes use a BorderLayout as their layout.
  • Which containers use a Flow layout as their default layout?- Panel and Applet classes use the FlowLayout as their default layout.
  • What are wrapper classes?- Wrapper classes are classes that allow primitive types to be accessed as objects.
  • What are Vector, Hashtable, LinkedList and Enumeration?- Vector : The Vector class provides the capability to implement a growable array of objects. Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexes and stores objects in a dictionary using hash codes as the object’s keys. Hash codes are integer values that identify objects. LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A LinkedList stores each object in a separate link whereas an array stores object references in consecutive locations. Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. It has two methods, namely hasMoreElements() and nextElement(). HasMoreElemnts() tests if this enumeration has more elements and nextElement method returns successive elements of the series.
  • What is the difference between set and list?- Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.
  • What is a stream and what are the types of Streams and classes of the Streams?- A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are: Byte Streams: Provide a convenient means for handling input and output of bytes. Character Streams: Provide a convenient means for handling input & output of characters. Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream. Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer.
  • What is the difference between Reader/Writer and InputStream/Output Stream?- The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented.
  • What is an I/O filter?- 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.
  • What is serialization and deserialization?- Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.
  • What is JDBC?- JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications.
  • What are drivers available?- a) JDBC-ODBC Bridge driver b) Native API Partly-Java driver c) JDBC-Net Pure Java driver d) Native-Protocol Pure Java driver
  • What is the difference between JDBC and ODBC?- a) OBDC is for Microsoft and JDBC is for Java applications. b) ODBC can’t be directly used with Java because it uses a C interface. c) ODBC makes use of pointers which have been removed totally from Java. d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required. e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms. f) JDBC API is a natural Java interface and is built on ODBC. JDBC retains some of the basic features of ODBC.
  • What are the types of JDBC Driver Models and explain them?- There are two types of JDBC Driver Models and they are: a) Two tier model and b) Three tier model Two tier model: In this model, Java applications interact directly with the database. A JDBC driver is required to communicate with the particular database management system that is being accessed. SQL statements are sent to the database and the results are given to user. This model is referred to as client/server configuration where user is the client and the machine that has the database is called as the server. Three tier model: A middle tier is introduced in this model. The functions of this model are: a) Collection of SQL statements from the client and handing it over to the database, b) Receiving results from database to the client and c) Maintaining control over accessing and updating of the above.
  • What are the steps involved for making a connection with a database or how do you connect to a database?a) Loading the driver : To load the driver, Class. forName() method is used. Class. forName(”sun. jdbc. odbc. JdbcOdbcDriver”); When the driver is loaded, it registers itself with the java. sql. DriverManager class as an available database driver. b) Making a connection with database: To open a connection to a given database, DriverManager. getConnection() method is used. Connection con = DriverManager. getConnection (”jdbc:odbc:somedb”, “user”, “password”); c) Executing SQL statements : To execute a SQL query, java. sql. statements class is used. createStatement() method of Connection to obtain a new Statement object. Statement stmt = con. createStatement(); A query that returns data can be executed using the executeQuery() method of Statement. This method executes the statement and returns a java. sql. ResultSet that encapsulates the retrieved data: ResultSet rs = stmt. executeQuery(”SELECT * FROM some table”); d) Process the results : ResultSet returns one row at a time. Next() method of ResultSet object can be called to move to the next row. The getString() and getObject() methods are used for retrieving column values: while(rs. next()) { String event = rs. getString(”event”); Object count = (Integer) rs. getObject(”count”);
  • What type of driver did you use in project?- JDBC-ODBC Bridge driver (is a driver that uses native(C language) libraries and makes calls to an existing ODBC driver to access a database engine).
  • What are the types of statements in JDBC?- Statement: to be used createStatement() method for executing single SQL statement PreparedStatement — To be used preparedStatement() method for executing same SQL statement over and over. CallableStatement — To be used prepareCall() method for multiple SQL statements over and over.
  • What is stored procedure?- Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.
  • How to create and call stored procedures?- To create stored procedures: Create procedure procedurename (specify in, out and in out parameters) BEGIN Any multiple SQL statement; END; To call stored procedures: CallableStatement csmt = con. prepareCall(”{call procedure name(?,?)}”); csmt. registerOutParameter(column no. , data type); csmt. setInt(column no. , column name) csmt. execute();
  • What is servlet?- Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.
  • What are the classes and interfaces for servlets?- There are two packages in servlets and they are javax. servlet