RSS

Managing REDO LOGFILES

  • Every Oracle database must have at least 2 redo logfile groups.
  • Oracle writes all statements except, SELECT statement, to the logfiles.
  • If a user updates a row, Oracle will change the row in db_buffer_cache and records the statement in the logfile and give the message to the user that  row is updated.
  • Actually the row is not yet written back to the datafile but still it give the message to the user that row is updated.
  • After 3 seconds the row is actually written to the datafile. This is known asdeferred batch writes.

Viewing Information About Logfiles

To See how many logfile groups are there and their status type the following query.

SQL>SELECT * FROM V$LOG;

GROUP#  THREAD#   SEQ   BYTES         MEMBERS  ARC    STATUS         FIRST_CHANGE#    FIRST_TIM

——          ——-           —–     ——-             ——-           —         ———           ————-                  ———

1          1                20605 1048576        1               YES      ACTIVE         61515628                 21-JUN-07

2          1                20606 1048576        1               NO        CURRENT     41517595                 21-JUN-07

3          1                20603 1048576        1               YES      INACTIVE      31511666                 21-JUN-07

4          1                20604 1048576        1               YES      INACTIVE      21513647                 21-JUN-07

To See how many members are there and where they are located give the following query

SQL>SELECT * FROM V$LOGFILE;

GROUP#   STATUS                                              MEMBER

——           ——-                                                    ———————————-

1              ONLINE                                                /U01/ORACLE/ICA/LOG1.ORA

2              ONLINE                                                /U01/ORACLE/ICA/LOG2.ORA

Adding a New Redo Logfile Group

To add a new Redo Logfile group to the database give the following command

SQL>alter database add logfile group 3 
‘/u01/oracle/ica/log3.ora’ size 10M;

Note: You can add groups to a database up to the MAXLOGFILES setting you have specified at the time of creating the database. If you want to change MAXLOGFILE setting you have to create a new controlfile.

Adding Members to an existing group

To add new member to an existing group give the following command

SQL>alter database add logfile member 
‘/u01/oracle/ica/log11.ora’ to group 1;

Note: You can add members to a group up to the MAXLOGMEMBERS setting you have specified at the time of creating the database. If you want to change MAXLOGMEMBERS setting you have create a new controlfile

Important: Is it strongly recommended that you multiplex logfiles i.e. have at least two log members, one member in one disk and another in second disk, in a database.

Dropping Members from a group

You can drop member from a log group only if the group is having more than one member and if it is not the current group. If you want to drop members from the current group, force a log switch or wait so that log switch occurs and another group becomes current. To force a log switch give the following command

SQL>alter system switch logfile;

The following command can be used to drop a logfile member

SQL>alter database drop logfile member ‘/u01/oracle/ica/log11.ora’;

Note: When you drop logfiles the files are not deleted from the disk. You have to use O/S command to delete the files from disk.

Dropping Logfile Group

Similarly, you can also drop logfile group only if the database is having more than two groups and if it is not the current group.

SQL>alter database drop logfile group 3;

Note: When you drop logfiles the files are not deleted from the disk. You have to use O/S command to delete the files from disk.

Resizing Logfiles

You cannot resize logfiles. If you want to resize a logfile create a new logfile group with the new size and subsequently drop the old logfile group.

Renaming or Relocating Logfiles

To Rename or Relocate Logfiles perform the following steps

For Example, suppose you want to move a logfile from ‘/u01/oracle/ica/log1.ora’ to ‘/u02/oracle/ica/log1.ora’, then do the following

Steps:-

  1. Shutdown the database

SQL>shutdown immediate;

  1. Move the logfile from Old location to new location using operating system command

$mv/u01/oracle/ica/log1.ora  /u02/oracle/ica/log1.ora

  1. Start and mount the database

SQL>startup mount

  1. Now give the following command to change the location in controlfile

SQL>alter database rename file ‘/u01/oracle/ica/log1.ora’ to ‘/u02/oracle/ica/log2.ora’;

  1. Open the database

SQL>alter database open;

Clearing REDO LOGFILES

A redo log file might become corrupted while the database is open, and ultimately stop database activity because archiving cannot continue. In this situation the ALTER DATABASE CLEAR LOGFILE statement can be used reinitialize the file without shutting down the database.

The following statement clears the log files in redo log group number 3:

ALTER DATABASE CLEAR LOGFILE GROUP 3;

This statement overcomes two situations where dropping redo logs is not possible:

  • If there are only two log groups
  • The corrupt redo log file belongs to the current group

If the corrupt redo log file has not been archived, use the UNARCHIVED keyword in the statement.

ALTER DATABASE CLEAR UNARCHIVED LOGFILE GROUP 3;

This statement clears the corrupted redo logs and avoids archiving them. The cleared redo logs are available for use even though they were not archived.

If you clear a log file that is needed for recovery of a backup, then you can no longer recover from that backup. The database writes a message in the alert log describing the backups from which you cannot recover

 
Leave a comment

Posted by on October 28, 2015 in Uncategorized

 

When to use an interface instead of an abstract class and vice versa?

Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.

  • If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created in that way. If a new version of an interface is required, you must create a whole new interface.
  • If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
  • If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
  • If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
 
Leave a comment

Posted by on January 28, 2015 in JAVA

 

Oracle Auto Increment Column – Sequence as Default Value

Solution 1: Prior to Oracle 11g, sequence assignment to a number variable could be done through a SELECT statement only in trigger, which requires context switching from PL/SQL engine to SQL engine. So we need to create before insert trigger for each row, and assign sequence new value to the column using select into clause.

create table test_tab
(
    id number primary key
);

create sequence test_seq start with 1 increment by 1 nocycle;

create or replace trigger test_trg 
before insert on test_tab 
for each row 
begin
    select test_seq.nextval into :new.id
    from dual;
end;
/

Solution 2: From Oracle 11g, we can directly assign a sequence value to a pl/sql variable in trigger, So we can create before insert trigger for each row, and assign sequence nextval to the column directly.

create table test_tab
(
    id number primary key
);

create sequence test_seq start with 1 increment by 1 nocycle;

create or replace trigger test_trg 
before insert on test_tab 
for each row 
begin
    :new.id := test_seq.nextval;
end;
/

Solution 3: With Oracle 12c, we can directly assign sequence nextval as a default value for a column, So you no longer need to create a trigger to populate the column with the next value of sequence, you just need to declare it with table definition.

create sequence test_seq start with 1 increment by 1 nocycle;

create table test_tab
(
    id number default test_seq.nextval primary key
);

ref: http://nimishgarg.blogspot.in/2013/07/oracle-auto-increment-column-sequence.html

 
Leave a comment

Posted by on May 22, 2014 in SQL

 

How will I know if my database is using a PFILE or SPFILE?

Execute the following query to see if your database was started with a PFILE or SPFILE:

SQL> SELECT DECODE(value, NULL, ‘PFILE’, ‘SPFILE’) “Init File Type”
FROM sys.v_$parameter WHERE name = ‘spfile’;

You can also use the V$SPPARAMETER view to check if you are using a PFILE or not: if the “value” column is NULL for all parameters, you are using a PFILE.

 
Leave a comment

Posted by on April 28, 2014 in Administration

 

JSP

JavaServer Pages, also known as JSPs, are a simple but powerful technology used to generate dynamic HTML on the server side. They are a direct extension of Java servlets. The JSP engine is just another servlet that is mapped to the extension *.jsp.

Steps of jsp Request

Untitled

Steps : 

  1. User requesting a JSP page through internet via web browser.
  2. The JSP request is sent to the Web Server.
  3. Web server accepts the requested .jsp file and passes the JSP file to the JSP Servlet Engine.
  4. If the JSP file has been called the first time then the JSP file is parsed otherwise servlet is instantiated.
  5. The next step is to generate a servlet from the JSP file. In that servlet file, all the HTML code is converted in println statements.
  6. Now, The servlet source code file is compiled into a class file (bytecode file).
  7. The servlet is instantiated by calling the init and service methods of the servlet’s life cycle.
  8. Now, the generated servlet output is sent via the Internet form web server to user’s web browser.
  9. Now in last step, HTML results are displayed on the user’s web browser.

JSP Life Cycle:

The lifecycle of JSP is controlled by three methods which are automatically called when a JSP is requested and when the JSP terminates normally.

These are:

jspInit () , 

_jspService() , 

jspDestroy().

jspInit() method is identical to the init() method in a Java Servlet and in applet.

It is called first when the JSP is requested and is used to initialize objects and variables that are used throughout the life of the JSP.

_jspService() method is automatically called and retrieves a connection to HTTP.

It will call doGet or doPost() method of servlet created.

jspDestroy() method is identical to the destroy() method in Servlet.

The destroy() method is automatically called when the JSP terminates normally.

NB: It isn’t called by JSP when it terminates abruptly.

It is used for cleanup where resources used during the execution of the JSP ate released, such as disconnecting form database.

Untitled2

A JSP page can have two types of data:

  • Template Data: It is the static part of a jsp page. Anything that is copied as it is directly to the response by the JSP server is known as template data.
  • JSP Elements: It is the dynamic part of a jsp page. Anything that is translated and executed by the JSP server is known as JSP element.

There are three types of JSP elements:

Directive Elements:

A JSP directive gives special information about the page to JSP Engine.

Each JSP goes through two phases:

(1) The first phase is known as translation time, during which the JSP engine turns the file into a servlet. (The step following from 1 to 5 in JSP Architecture)

(2)The second phase is known as request time, during which the resulting servlet is run to actually generate the page. (The step following from 6 to 9 in JSP Architecture)

The JSP engine handles the directives at translation time because the JSP engine will translate a particular directive into a servlet only for the first time so the developer can get more speed for the process of loading a JSP file in a future.

<%@ directive {attribute=”value“} %>

This states that, for this page directive, assign these values for these attributes. A directive can contain n

number of optional attribute/value pairs.

If we use our previous example for indicating the JSP language, the following line of code would indicate

that the JSP language to use would be Java:

<%@ page language=”java” %>

There are three possible directives currently defined by the JSP specification:

  1. page,
  2. include, and
  3. taglib.

 

The page Directive

The page directive defines information that will be globally available for that JavaServer Page. These

page level settings will directly affect the compilation of the JSP.

The page directive is used to specify attributes for the JSP page as a whole.

The page directive does not produce any visible output when the page is requested but change the way the JSP Engine processes the page.

e.g., you can make session data unavailable to a page by setting a session to FALSE.

The table given below describes the possible attributes for the page directive.

Untitled3

<%@ page language="java"

import="java.util.*,java.io.*"

extends="com.Connect"

autoFlush="true"

errorPage="error.jsp"

info="This is a simple jsp file created by Java2all team on 22 Feb 2011"

isELIgnored="false"

isErrorPage="false"

session="true"

buffer="8kb"

contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"

isThreadSafe="true"

%>

Note Because the mandatory attributes are defaulted, you are not required to specify any page directives.

The include Directive:

 

The include directive is used to insert text and code at JSP translation time. The syntax of the include directive is as follows:

<%@ include file=”relativeURLspec” %>

The file that the file attributes points to can reference a normal text HTML file or it can reference a JSP file, which will be evaluated at translation time.


<%@ page language="java" import="java.util.*,java.io.*" pageEncoding="ISO-8859-1"%>

<html>

<head>

<title> IncludeDemo.jsp </title>

</head>

<body>

This is a JSP page. <br>

<%@ include file="/HTMLFILE/“Included.html"%>

</body>

</html>

The taglib Directive

The most recent version of the JSP specification defines a mechanism for extending the current set of JSP tags. It does this by creating a custom set of tags called a tag library. That is what the taglib points to.

The taglib directive declares that the page uses custom tags, uniquely names the tag library defining them, and associates a tag prefix that will distinguish usage of those tags. The syntax of the taglib directive is as follows:

<%@ taglib uri=”tagLibraryURI” prefix=”tagPrefix” %>

The taglib attributes are described in

Untitled4

Action Element:

Action elements generally performs some action depending on the information required at when the JSP page is requested by a browser. An action can access parameters sent with the request in order to lookup the database.

<jsp:useBean>

<jsp:setProperty>

<jsp:getProperty>

<jsp:include>

The general syntax for the action elements is:

<action_name attribute=value …>action_body</action_name>

<action_name attribute=value …/>

<jsp:useBean id=”obj” />

<jsp:setProperty name=”obj” property=”*” />

Welcome, <jsp:getProperty name=”obj” property=”name” />

Implicit Objects

As a JSP author, you have access to certain implicit objects that are available for use in JSP documents,

without being declared first. Each of these implicit objects has a class or interface type defined in a core Java Development Kit (JDK) or Java Servlet Development Kit (JSDK).

 

JSP Scripting elements: 

There are four types of tag in jsp scripting elements.

a) JSP Declaration tag.

b) JSP scriptlet tag.

c) JSP Expression tag.

d) Comment tag.

Now we describe each tag in detail.

a) JSP Declaration tag :

A JSP declaration lets you declare or define variables and methods (fields) that use into the jsp page.

Declaration tag Start with  <%! And End with %>

The Code placed inside this tag must end with a semicolon (;).

Syntax:    <%! Java Code; %>


<%! private int i = 10; %>

<%! private int squre(int i)

{
i = i * i ;
return i;
}

%>

You can also put these codes in a single syntax block of declaration like,

<%! private int i = 10;
private int squre(int i)
{
i = i * i ;
return i;
}
%>

Note :  The XML authors can use an alternative syntax for JSP declaration tag:

<jsp:declaration>

Java code;

</jsp:declaration>

<jsp:declaration> private int i = 1; </jsp:declaration>
<jsp:declaration>
{
private int squre(int i)
i = i * i ;
return i;
}
</jsp:declaration>

You can also put these codes in a single syntax block of declaration like,

<jsp:declaration>
private int i = 1;
private int squre(int i)
{
i = i * i ;
return i;
}
</jsp:declaration>

Remember that XML elements, unlike HTML ones, are case sensitive. So be sure to use lowercase.

Declarations do not generate any output so the developer uses declaration tag with JSP expression tag or JSP scriptlet tag for generating an appropriate output for display it in the appropriate browser.

b) JSP scriptlet tag :

A JSP scriptlet lets you declare or define any java code that use into the jsp page.

scriptlet tag Start with  <% and End with %>

The Code placed inside this tag must end with a semicolon (;).

Syntax:    <% Java Code; %>

<%
int a = 10;
out.print("a ="+a);
%>

Note :  The XML authors can use an alternative syntax for JSP scriptlet tag.

<jsp:scriptlet>

Java code;

</jsp:scriptlet>

c) JSP Expression tag :

A JSP expression is used to insert Java values directly into the output.

JSP Expression tag is use for evaluating any expression and directly displays the output in appropriate web browser.

Expression tag Start with <%= and End with %>

The Code placed inside this tag not end with a semicolon (;).

Syntax:     <%= Java Code %>

For example. the following shows the date/time that the page was requested:

Current time: <%= new java.util.Date() %>

Note :  The XML authors can use an alternative syntax for JSP expressions:

<jsp:expression>

Java Expression

</jsp:expression>

 
Leave a comment

Posted by on September 26, 2013 in JAVA

 

Framework

Framework is set of reusable software program that forms the basis for an application. Frameworks help the programmers to build the application quickly. Earlier it was very hard to develop complex web applications. Now it’s very easy to develop such application using different kinds of frameworks such as
Struts,
Struts 2,
Hibernate,
JSF,
Tapestry,
JUnit,
Log4j,
Spring.

Pros And Cons Of Using Frameworks

Pros

Efficiency

Tasks that usually would take you hours and hundreds of lines of code to write, can now be done in minutes with pre-built functions. Development becomes a lot easier, so if it’s easier it’s faster, and consequently efficient.

Security

A widely used framework has big security implementations. The big advantage is the community behind it, where users become long-term testers. If you find a vulnerability or a security hole, you can go to the framework’s website and let the team know so they can fix it.

Cost

Most popular frameworks are free, and since it also helps the developer to code faster, the cost for the final client will be smaller.

Support

As any other distributed tool, a framework usually comes with documentation, a support team, or big community forums where you can obtain quick answers.

 

Cons

You learn the framework, not the language

I believe this to be the major problem. If you’re using a framework and you know very little about the language behind it, you will learn the framework and not the language itself. The way you code jQuery is different from the way you code javascript. Simple put, if you know jQuery, it doesn’t mean you know javascript.

Limitation

The framework’s core behaviour can’t be modified, meaning that when you use a framework, you are forced to respect its limits and work the way it is required. Make sure you choose a framework that suits your needs.

Code is public

Since the framework is available to everyone, it is also available to people with bad intentions. It can be studied in order to know how things work and to find flaws that can be used against you.

 

Spring Framework:

Spring is the most popular application development framework for enterprise Java. Millions of developers around the world use Spring Framework to create high performing, easily testable, reusable code.

Spring framework is an open source Java platform and it was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.

Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.

The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.

 

Benefits of Using Spring Framework:

Following is the list of few of the great benefits of using Spring Framework:

  • Spring enables developers to develop enterprise-class applications using POJOs. The benefit of using only POJOs is that you do not need an EJB container product such as an application server but you have the option of using only a robust servlet container such as Tomcat or some commercial product.
  • Spring is organized in a modular fashion. Even though the number of packages and classes are substantial, you have to worry only about ones you need and ignore the rest.
  • Spring does not reinvent the wheel instead, it truly makes use of some of the existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, other view technologies.
  • Testing an application written with Spring is simple because environment-dependent code is moved into this framework. Furthermore, by using JavaBean-style POJOs, it becomes easier to use dependency injection for injecting test data.

Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.

 

 

 
Leave a comment

Posted by on September 26, 2013 in JAVA

 

The Basic Steps to Connect Oracle and Java Program

Here, I will show you what the steps to make a connection between Oracle database and your Java program. To do this work, you need the JDBC (Java DataBase Connectivity) driver. The file name of Oracle’s JDBC driver is classes12.zip or classes12.jar. By default, Oracle have included this driver at the software installation process. Its location is in the ORACLE_HOME\jdbc\lib directory. For example, if our ORACLE_HOME is C:\Oracle\Ora90 then the JDBC driver will be placed in C:\Oracle\Ora90\jdbc\lib directory.

Make sure to set the Java CLASSPATH correctly. Here is the command line to do it.
(Note: Assume the ORACLE_HOME is C:\Oracle\Ora90)

set CLASSPATH=.;C:\Oracle\Ora90\jdbc\lib\classes12.jar

or

set CLASSPATH=.;C:\Oracle\Ora90\jdbc\lib\classes12.zip

In addition, you can also set the CLASSPATH in your autoexec.bat file on your Windows operating system.

Now, just follow these steps:

STEP 1. Import the java.sql package into your program.
——————————————————

import java.sql.*;

The syntax above will import all classes in the java.sql package. If you want to import a few of them, you can write the syntax like this

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.Connection;

It only imports the Driver, DriverManager, and Connection class into your Java program.

STEP 2. Load the Oracle’s JDBC driver.
————————————–

There are two ways to load your JDBC driver. The first, use the forName() method of java.lang.Class class.

Class.forName("oracle.jdbc.driver.OracleDriver");

And the second way is use the registerDriver() method of DriverManager class.

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

STEP 3. Create a Connection object.
———————————–

To create a Connection object, use the getConnection() method of DriverManager class. This method takes three parameters: URL, username, and password.

Connection conn = 
DriverManager.getConnection(
"jdbc:oracle:thin:@mylaptop:1521:ORADB",       // URL
"diu",       // username
"diu123"        // password
);

STEP 4. Create a Statement object.
———————————-

A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send.

Statement mystat = conn.createStatement();

STEP 5. Execute your SQL statement.
———————————–

After you create a Statement object successfully, you can execute a query (SELECT statement) from your Java program using the executeQuery() method of Statement class and executeUpdate() method to create or modify tables. The result of execution process will be stored in ResultSet object, so you need to declare an object of ResultSet first. Here is the code.

ResultSet rs = mystat.executeQuery("select custno, custname from customer");

STEP 6. Display your data.
————————–

The next step is display your data using the looping control.

while (rs.next()) {
System.out.println(
rs.getInt(1) +      // first column
"\t" +              // the horizontal tab
rs.getString(2)     // second column
);
}

STEP 7. Close your statement and connection.
——————————————–

mystat.close();
conn.close();

Here is the complete code.

import java.sql.*;

class SimpleOraJava {
  public static void main(String args[]) throws SQLException {
    DriverManager.registerDriver(
      new oracle.jdbc.driver.OracleDriver()
    );
    String serverName = "mylaptop";
    int port = 1521;
    String user = "scott";
    String password = "tiger";
    String SID = "ORCL";
    String URL = "jdbc:oracle:thin:@" + serverName + ":" + port + ":" + SID;
    Connection conn = DriverManager.getConnection(URL, user, password);
    String SQL = "SELECT EMPNO, ENAME FROM EMP";
    Statement stat = conn.createStatement();
    ResultSet rs = stat.executeQuery(SQL);
    while (rs.next()) {
      System.out.println(
        rs.getInt(1) + 
        "\t" +
        rs.getString(2) 
      );
    }
    stat.close();
    conn.close();   
  }
}
 
Leave a comment

Posted by on July 11, 2013 in JAVA

 

Array

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables.

Each item in an array is called an element, and each element is accessed by its numerical index.

Using and array in your program is a 3 step process –
1) declaring an Array
2) constructing an Array
3) initializing an Array

Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable:

dataType[] arrayRefVar;   // preferred way.

or

dataType arrayRefVar[];  //  works but not preferred way.

Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.

Example:
The following code snippets are examples of this syntax:

double[] myList;         // preferred way.

or

double myList[];         //  works but not preferred way.

Constructing an Array:
You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];

The above statement does two things:
• It creates an array using new dataType[arraySize];
• It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.

Example:
Following statement declares an array variable, myList, creates an array of 10 elements of double type, and assigns its reference to myList.:

double[] myList = new double[10];

or

double[] myList = {5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 111.23};

Initializing an Array

intArray[0]=1; // Assigns an integer value 1 to the first element 0 of the array

intArray[1]=2; // Assigns an integer value 2 to the second element 1 of the aray

Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.

Example:
Here is a complete example of showing how to create, initialize and process arrays:

public class TestArray {  

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (int i = 0; i < myList.length; i++) {
         System.out.println(myList[i]);
      }
      // Summing all elements
      double total = 0;
      for (int i = 0; i < myList.length; i++) {
         total += myList[i];
      }
      System.out.println("Total is " + total);
      // Finding the largest element
      double max = myList[0];
      for (int i = 1; i < myList.length; i++) {
         if (myList[i] > max) max = myList[i];
      }
      System.out.println("Max is " + max);
   }
}

This would produce following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

The foreach Loops:
JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.

Example:
The following code displays all the elements in the array myList:

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (double element: myList) {
         System.out.println(element);
      }
   }
}

This would produce following result:

1.9
2.9
3.4
3.5

Passing Arrays to Methods:
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array:

public static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
    System.out.print(array[i] + " ");
  }
}

You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2:

printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a Method:
A method may also return an array. For example, the method shown below returns an array that is the reversal of another array:

public static int[] reverse(int[] list) {
  int[] result = new int[list.length];

  for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
    result[j] = list[i];
  }
  return result;
}

Arrays are passed by reference:
Arrays are passed to functions by reference, or as a pointer to the original. This means anything you do to the Array inside the function affects the original.

class ArrayDemo {

   public static void passByReference(String a[]){
     a[0] = "Changed";
   }

   public static void main(String args[]){
      String []b={"Apple","Mango","Orange"};
      System.out.println("Before Function Call    "+b[0]);
      ArrayDemo.passByReference(b);
      System.out.println("After Function Call    "+b[0]);
   }
}

Problem & Solution:

1. How to sort an array and search an element inside it?

Solution:

Following example shows how to use sort () and binarySearch () method to accomplish the task. The user defined method printArray () is used to display the output:

import java.util.Arrays;

public class MainClass {
   public static void main(String args[]) throws Exception {
      int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
      Arrays.sort(array);
      printArray("Sorted array", array);
      int index = Arrays.binarySearch(array, 2);
      System.out.println("Found 2 @ " + index);
   }
   private static void printArray(String message, int array[]) {
      System.out.println(message
      + ": [length: " + array.length + "]");
      for (int i = 0; i < array.length; i++) {
         if(i != 0){
            System.out.print(", ");
         }
         System.out.print(array[i]);                     
      }
      System.out.println();
   }
}

Result:

The above code sample will produce the following result.

Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Found 2 @ 5

2. How to sort an array and insert an element inside it?
Solution:

Following example shows how to use sort () method and user defined method insertElement ()to accomplish the task.

import java.util.Arrays;

public class MainClass {
   public static void main(String args[]) throws Exception {
      int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
      Arrays.sort(array);
      printArray("Sorted array", array);
      int index = Arrays.binarySearch(array, 1);
      System.out.println("Didn't find 1 @ "
      + index);
      int newIndex = -index - 1;
      array = insertElement(array, 1, newIndex);
      printArray("With 1 added", array);
   }
   private static void printArray(String message, int array[]) {
      System.out.println(message
      + ": [length: " + array.length + "]");
      for (int i = 0; i < array.length; i++) {
         if (i != 0){
            System.out.print(", ");
         }
         System.out.print(array[i]);         
      }
      System.out.println();
   }
   private static int[] insertElement(int original[],
   int element, int index) {
      int length = original.length;
      int destination[] = new int[length + 1];
      System.arraycopy(original, 0, destination, 0, index);
      destination[index] = element;
      System.arraycopy(original, index, destination, index
      + 1, length - index);
      return destination;
   }
}

Result:

The above code sample will produce the following result.

Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Didn't find 1 @ -6
With 1 added: [length: 11]
-9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8

3. How to reverse an array list ?

Solution:

Following example reverses an array list by using Collections.reverse(ArrayList)method.

import java.util.ArrayList;
import java.util.Collections;

public class Main {
   public static void main(String[] args) {
      ArrayList arrayList = new ArrayList();
      arrayList.add("A");
      arrayList.add("B");
      arrayList.add("C");
      arrayList.add("D");
      arrayList.add("E");
      System.out.println("Before Reverse Order: " + arrayList);
      Collections.reverse(arrayList);
      System.out.println("After Reverse Order: " + arrayList);
   }
}

Result:

The above code sample will produce the following result.

Before Reverse Order: [A, B, C, D, E]
After Reverse Order: [E, D, C, B, A]

4. How to write an array of strings to the output console ?

Solution:

Following example demonstrates writing elements of an array to the output console through looping.

public class Welcome {
   public static void main(String[] args){
      String[] greeting = new String[3];
      greeting[0] = "This is the greeting";
      greeting[1] = "for all the readers from";
      greeting[2] = "Java Source .";
      for (int i = 0; i < greeting.length; i++){
         System.out.println(greeting[i]);
      }
   }
}

Result:

The above code sample will produce the following result.

This is the greeting
For all the readers From
Java source .

5. How to search the minimum and the maximum element in an array ?

Solution:

This example shows how to search the minimum and maximum element in an array by using Collection.max() and Collection.min() methods of Collection class .

import java.util.Arrays;
import java.util.Collections;

public class Main {
   public static void main(String[] args) {
      Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};
      int min = (int) Collections.min(Arrays.asList(numbers));
      int max = (int) Collections.max(Arrays.asList(numbers));
      System.out.println("Min number: " + min);
      System.out.println("Max number: " + max);
   }
}

Result:

The above code sample will produce the following result.

Min number: 1
Max number: 9

6. How to merge two arrays ?

Solution:

This example shows how to merge two arrays into a single array by the use of list.Addall(array1.asList(array2) method of List class and Arrays.toString () method of Array class.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
   public static void main(String args[]) {
      String a[] = { "A", "E", "I" };
      String b[] = { "O", "U" };
      List list = new ArrayList(Arrays.asList(a));
      list.addAll(Arrays.asList(b));
      Object[] c = list.toArray();
      System.out.println(Arrays.toString(c));
   }
}

Result:

The above code sample will produce the following result.

[A, E, I, O, U]

7. How to fill (initialize at once) an array ?

Solution:

This example fill (initialize all the elements of the array in one short) an array by using Array.fill(arrayname,value) method and Array.fill(arrayname ,starting index ,ending index ,value) method of Java Util class.

import java.util.*;

public class FillTest {
   public static void main(String args[]) {
      int array[] = new int[6];
      Arrays.fill(array, 100);
      for (int i=0, n=array.length; i < n; i++) {
         System.out.println(array[i]);
      }
      System.out.println();
      Arrays.fill(array, 3, 6, 50);
      for (int i=0, n=array.length; i< n; i++) {
         System.out.println(array[i]);
      }
   }
}

Result:

The above code sample will produce the following result.

100
100
100
100
100
100

100
100
100
50
50
50

8. How to extend an array after initialisation?

Solution:

Following example shows how to extend an array after initialization by creating an new array.

public class Main {
   public static void main(String[] args) {
      String[] names = new String[] { "A", "B", "C" };
      String[] extended = new String[5];
      extended[3] = "D";
      extended[4] = "E";
      System.arraycopy(names, 0, extended, 0, names.length);
      for (String str : extended){
         System.out.println(str);
      }
   }
}

Result:

The above code sample will produce the following result.

A
B
C
D
E

9. How to remove an element of array?

Solution:

Following example shows how to remove an element from array.

import java.util.ArrayList;

public class Main {
   public static void main(String[] args)  {
      ArrayList objArray = new ArrayList();
      objArray.clear();
      objArray.add(0,"0th element");
      objArray.add(1,"1st element");
      objArray.add(2,"2nd element");
      System.out.println("Array before removing an 
      element"+objArray);
      objArray.remove(1);
      objArray.remove("0th element");
      System.out.println("Array after removing an 
      element"+objArray);
   }
}

Result:

The above code sample will produce the following result.

Array before removing an element[0th element, 
1st element, 2nd element]
Array after removing an element[2nd element]

10. How to remove one array from another array?

Solution:

Following example uses Removeall method to remove one array from another.

import java.util.ArrayList;

public class Main {
   public static void main(String[] args)  {
      ArrayList objArray = new ArrayList();
      ArrayList objArray2 = new ArrayList();
      objArray2.add(0,"common1");
      objArray2.add(1,"common2");
      objArray2.add(2,"notcommon");
      objArray2.add(3,"notcommon1");
      objArray.add(0,"common1");
      objArray.add(1,"common2");
      objArray.add(2,"notcommon2");
      System.out.println("Array elements of array1" +objArray);
      System.out.println("Array elements of array2" +objArray2);
      objArray.removeAll(objArray2);
      System.out.println("Array1 after removing 
      array2 from array1"+objArray);
   }
}

Result:

The above code sample will produce the following result.

Array elements of array1[common1, common2, notcommon2]
Array elements of array2[common1, common2, notcommon, 
notcommon1]
Array1 after removing array2 from array1[notcommon2]

11. How to find common elements from arrays?
Solution:

Following example shows how to find common elements from two arrays and store them in an array.

import java.util.ArrayList;

public class Main {
   public static void main(String[] args)  {
      ArrayList objArray = new ArrayList();
      ArrayList objArray2 = new ArrayList();
      objArray2.add(0,"common1");
      objArray2.add(1,"common2");
      objArray2.add(2,"notcommon");
      objArray2.add(3,"notcommon1");
      objArray.add(0,"common1");
      objArray.add(1,"common2");
      objArray.add(2,"notcommon2");
      System.out.println("Array elements of array1"+objArray);
      System.out.println("Array elements of array2"+objArray2);
      objArray.retainAll(objArray2);
      System.out.println("Array1 after retaining common 
      elements of array2 & array1"+objArray);
   }
}

Result:

The above code sample will produce the following result.

Array elements of array1[common1, common2, notcommon2]
Array elements of array2[common1, common2, notcommon,
notcommon1]
Array1 after retaining common elements of array2 & array1
[common1, common2]

12. How to find an object or a string in an Array?
Solution:

Following example uses Contains method to search a String in the Array.

import java.util.ArrayList;

public class Main {
   public static void main(String[] args)  {
      ArrayList objArray = new ArrayList();
      ArrayList objArray2 = new ArrayList();
      objArray2.add(0,"common1");
      objArray2.add(1,"common2");
      objArray2.add(2,"notcommon");
      objArray2.add(3,"notcommon1");
      objArray.add(0,"common1");
      objArray.add(1,"common2");
      System.out.println("Array elements of array1"+objArray);
      System.out.println("Array elements of array2"+objArray2);
      System.out.println("Array 1 contains String common2?? "
      +objArray.contains("common1"));
      System.out.println("Array 2 contains Array1?? "
      +objArray2.contains(objArray) );
   }
}

Result:

The above code sample will produce the following result.

Array elements of array1[common1, common2]
Array elements of array2[common1, common2, notcommon, notcommon1]
Array 1 contains String common2?? true
Array 2 contains Array1?? false

13. How to check if two arrays are equal or not?
Solution:

Following example shows how to use equals () method of Arrays to check if two arrays are equal or not.

import java.util.Arrays;

public class Main {
   public static void main(String[] args) throws Exception {
      int[] ary = {1,2,3,4,5,6};
      int[] ary1 = {1,2,3,4,5,6};
      int[] ary2 = {1,2,3,4};
      System.out.println("Is array 1 equal to array 2?? "
      +Arrays.equals(ary, ary1));
      System.out.println("Is array 1 equal to array 3?? "
      +Arrays.equals(ary, ary2));
   }
}

Result:

The above code sample will produce the following result.

Is array 1 equal to array 2?? true
Is array 1 equal to array 3?? false

14. How to compare two arrays?
Solution:

Following example uses equals method to check whether two arrays are or not.

import java.util.Arrays;

public class Main {
   public static void main(String[] args) throws Exception {
      int[] ary = {1,2,3,4,5,6};
      int[] ary1 = {1,2,3,4,5,6};
      int[] ary2 = {1,2,3,4};
      System.out.println("Is array 1 equal to array 2?? "
      +Arrays.equals(ary, ary1));
      System.out.println("Is array 1 equal to array 3?? "
      +Arrays.equals(ary, ary2));
   }
}

Result:

The above code sample will produce the following result.

Is array 1 equal to array 2?? true
Is array 1 equal to array 3?? false
 
Leave a comment

Posted by on June 29, 2013 in JAVA

 

Oracle DBWR Process

DBWn
Database Writer process. DBWn has two responsibilities: 1. Scan the buffer cache for dirty buffers to write and 2. write the dirty buffers to disk.

The database writer process (DBWn) writes modified (dirty) buffers of database buffer cache to datafiles and only to the datafiles. Because Oracle uses write-ahead logging, DBWn does not need to write blocks when a transaction is commited. Instead, DBWn is designed to perform batched writes with high efficiency. In the most common case, DBWn writes only when more data needs to be read into the database buffer cache and too few database buffers are free. The least recently used (LRU) data is written to the datafiles first. DBWn also performs writes for other functions, such as a checkpoint (CKPT).

DBWnflushes buffers when:

A DBWn timeout occurs (every 3 seconds).
A normal or incremental checkpoint occurs.
The number of dirty buffers reaches a threshold value. ( Typically, 1/2 of _db_block_write_batch ) <<– don’t know about this.
Number of used buffers = db_block_max_scan <<– don’t know about this. A process scans a specified number of blocks when scanning free buffers and cannot find any.
A ping request in RAC environment.
A normal or temporary tablespace is placed offline.
A tablespace is put into read-only mode.
A tablespace is dropped or truncated.
ALTER TABLESPACE tablespace_name BEGIN BACKUP

db_writer_processes specifies the maximum number of DBWn processes. If not specified at STARTUP, Oracle calculates db_writer_processes based on the number of CPUs and processor groups. Although one db_writer_processes (DBW0) is adequate for most systems, up to 20 additional processes (DBW1 through DBW9 and DBWa through DBWj) can be configured. Additional DBWn processes are not useful on uniprocessor systems, however multiple db_writer_processes are recommended for systems with multiple CPUs (at least one DBWn for every 8 CPUs) or multiple processor groups (at least as many DBWn as processor groups). dbwr_io_slaves is intended for scenarios where multiple db_writer_processes cannot be used. If db_block_checksum is enabled, each database block is compared with data in the database. Set for troubleshooting only.

Related Views:  
V$DB_CACHE_ADVICE  
V$WAITSTAT  
DBA_OBJECTS  
http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96533/memory.htm#34169
http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96524/c08memor.htm#11256
http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96524/c09procs.htm#6162

Write Request Queue Average write request queue length notes: Summed_Dirty_Queue_Length – Value for summed dirty queue length (total) Write_Requests – Value for write requests (total) Write_Request_Queue_Length – Average request queue length select sum(decode(NAME,’summed dirty queue length’,VALUE,0)) summed_dirty_queue_length, sum(decode(NAME,’write requests’,VALUE,0)) write_requests,sum(decode(NAME,’summed dirty queue length’,VALUE,0)) / sum(decode(NAME,’write requests’,VALUE)) write_request_queue_length from V$SYSSTAT where NAME in (‘summed dirty queue length’,’write requests’) and VALUE > 0;Lazy DBWR Indicators Dirty Buffers Inspected – Value for dirty buffers inspected (total) Free Buffers Inspected – Value for free buffers inspected (total) select sum(decode (NAME, ‘dirty buffers inspected’, VALUE)) dirty_buffers_inspected, sum(decode (NAME, ‘free buffer inspected’, VALUE)) free_buffers_inspected from V$SYSSTAT where NAME in ( ‘dirty buffers inspected’,’free buffer inspected’) and VALUE > 0;QuickSQL:To identify currently running processes select c.name,b.spid,a.sid from V$SESSION a, V$PROCESS b, V$BGPROCESS c where c.paddr <> ’00’ and c.paddr = b.addr and b.addr = a.paddr order by 1;Determine if the data cache is set right select (1-(sum(decode(name, ‘physical reads’, value,0))/(sum(decode(name, ‘db block gets’, value,0)) + (sum(decode(name, ‘consistent gets’, value,0)))))) * 100 “Read Hit Ratio” from V$SYSSTAT; Read Hit Ratio 98.415926Read hit ratios below 90-95% are usually a sign of poor indexing, BUT Distortion of the hit ratio numbers is possible.Data dictionary cache miss ratio. The ratio below is in the ‘good’ range. select sum(gets) Gets, sum(getmisses) Misses, (1 – (sum(getmisses) / (sum(gets) + sum(getmisses))))*100 HitRate from V$ROWCACHE; Gets Misses HitRate 10233 508 95.27045Determine library cache hit ratio select sum(pins) Executions, sum(pinhits) “Execution Hits”, ((sum(pinhits) / sum(pins)) * 100) phitrat, sum(reloads) Misses,((sum(pins) / (sum(pins) + sum(reloads))) * 100) hitrat from V$LIBRARYCACHE; EXECUTIONS Execution Hits PHITRAT MISSES HITRAT ———- ————– ———- ———- ———- 1616509538 1576652644 97.5343855 7293581 99.5508334Find number of running DBWR’s SELECT s.sid, bgp.name FROM V$SESSION s, V$BGPROCESS bgp WHERE bgp.name LIKE ‘%DBW%’ AND bgp.paddr = s.paddr; SID NAME ———- —————————————- 2 DBW0 3 DBW1Dont know yet col event for a25 SELECT event, total_waits waits, total_timeouts timeouts,time_waited total_time, average_wait avg FROM V$SESSION_EVENT WHERE sid = 3 ORDER BY time_waited DESC; EVENT WAITS TIMEOUTS TOTAL_TIME AVG ————————- ———- ———- ———- ———- rdbms ipc message 258044 207259 61899637 240 db file parallel write 180052 0 533871 3 log buffer space 11132 1533 506603 46 latch free 187 89 598 3In previous versions of Oracle (till Oracle 7) the db_files parameter used to be a tuning parameter. The DBWR internal write batch size (kcbdcw) was a function of # of db_files. So high values in db_files will inflate the dbwr write chunk and this will make DBWR overactive. Starting from Oracle 8 the parameter db_files have no control in DBWR and thus the restriction is lifted (I think) Query X$KVII for this info. SELECT KVIIDSC,KVIIVAL from X$KVII where KVIITAG=’kcbscw’; KVIIDSC KVIIVAL —————————————————————- ———- DBWR write chunk 204

 
Leave a comment

Posted by on June 27, 2013 in Administration

 

Abstraction

Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class.
If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclassed. This is typically how abstract classes come about during the design phase. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own.

Abstract Class:
Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration somewhere before the class keyword.

public abstract class Employee
{
   private String name;
   private String address;
   private int number;
   public Employee(String name, String address, int number)
   {
      System.out.println("Constructing an Employee");
      this.name = name;
      this.address = address;
      this.number = number;
   }
   public double computePay()
   {
     System.out.println("Inside Employee computePay");
     return 0.0;
   }
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + this.name
       + " " + this.address);
   }
   public String toString()
   {
      return name + " " + address + " " + number;
   }
   public String getName()
   {
      return name;
   }
   public String getAddress()
   {
      return address;
   }
   public void setAddress(String newAddress)
   {
      address = newAddress;
   }
   public int getNumber()
   {
     return number;
   }
}

Notice that nothing is different in this Employee class. The class is now abstract, but it still has three fields, seven methods, and one constructor.
Now if you would try as follows:

public class AbstractDemo
{
   public static void main(String [] args)
   {
      /* Following is not allowed and would raise error */
      Employee e = new Employee("George W.", "Houston, TX", 43);

      System.out.println("\n Call mailCheck using 
                                   Employee reference--");
      e.mailCheck();
    }
}

When you would compile above class then you would get following error:

Employee.java:46: Employee is abstract; cannot be instantiated
      Employee e = new Employee("George W.", "Houston, TX", 43);
                   ^
1 error

Extending Abstract Class:
We can extend Employee class in normal way as follows:

public class Salary extends Employee
{
   private double salary; //Annual salary
   public Salary(String name, String address, int number, double
      salary)
   {
       super(name, address, number);
       setSalary(salary);
   }
   public void mailCheck()
   {
       System.out.println("Within mailCheck of Salary class ");
       System.out.println("Mailing check to " + getName()
       + " with salary " + salary);
   }
   public double getSalary()
   {
       return salary;
   }
   public void setSalary(double newSalary)
   {
       if(newSalary &gt;= 0.0)
       {
          salary = newSalary;
       }
   }
   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
}

Here we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salary object will inherit the three fields and seven methods from Employee.

public class AbstractDemo
{
   public static void main(String [] args)
   {
      Salary s = new Salary("Mohd Mohtashim", "Ambehta,  UP",
                                 3, 3600.00);
      Salary e = new Salary("John Adams", "Boston, MA",
                                 2, 2400.00);

      System.out.println("Call mailCheck using
                                   Salary reference --");
      s.mailCheck();
      System.out.println("\n Call mailCheck using
                                   Employee reference--");
      e.mailCheck();
    }
}

This would produce following result:
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference —
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference–
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.
Abstract Methods:
If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract.
The abstract keyword is also used to declare a method as abstract.An abstract methods consist of a method signature, but no method body.
Abstract method would have no definition, and its signature is followed by a semicolon, not curly braces as follows:

public abstract class Employee
{
   private String name;
   private String address;
   private int number;
   
   public abstract double computePay();
   
   //Remainder of class definition
}

Declaring a method as abstract has two results:
• The class must also be declared abstract. If a class contains an abstract method, the class must be abstract as well.
• Any child class must either override the abstract method or declare itself abstract.
A child class that inherits an abstract method must override it. If they do not, they must be abstract,and any of their children must override it.
Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated.
If Salary is extending Employee class then it is required to implement computePay() method as follows:

public class Salary extends Employee
{
   private double salary; // Annual salary
  
   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }

   //Remainder of class definition
}
 
Leave a comment

Posted by on June 27, 2013 in JAVA