Wednesday, February 29, 2012

use jdk 1.6 to compile the java file as jdk1.3

assert is a keyword introduce at jdk 1.4,You cannot use it as an identifier in jdk1.4 +.
However if you have used it as an identifier,and you want to compile the class,then you need to go back to jdk 1.3.

But you have only jdk 1.6 with you.Still then you can compile your java class,as if you are using jdk 1.3

 Demo.java
 public class Demo
{
public static void main(String[] args) 
{
 boolean assert = true;
if(assert) System.out.println("if is true");
}
}



compile using jdk 1.4+ will give you these error

-------------------------------------------------
>javac Demo.java
Demo.java:5: as of release 1.4, 'assert' is a keyword, and may not be used as an
 identifier
(use -source 1.3 or lower to use 'assert' as an identifier)
                 boolean assert = true;
                         ^
Demo.java:6: as of release 1.4, 'assert' is a keyword, and may not be used as an
 identifier
(use -source 1.3 or lower to use 'assert' as an identifier)
                if(assert) System.out.println("if is true");

To compile as jdk1.3 although you are using jdk 1.4+
--------------------------------------------------------
>javac -source 1.3 Demo.java

Monday, February 27, 2012

Working with Trigger in Oracle

I want to implement autoincrement feature to my employee table.Built in facility is not available but we can write our own trigger concept to do so.

1. Create table in Oracle
------------

 create table Employee1
  (
    empid number primary key,
    empname varchar2(10),
    empsal number(10,2)
   );

2.Create a Sequence which will generate unique empid each time

SQL> CREATE SEQUENCE   EMPID_SEQ  MINVALUE 101 MAXVALUE 1000 INCREMENT BY 1 START WITH 101 NOCACHE   NOCYCLE  NOORDER;

3.Write a Trigger,which will insert the value from empid_seq to empid column of Employee1 table

SQL>
CREATE OR REPLACE TRIGGER EMPID_TRIG
before insert on EMPLOYEE1
for each row
begin
select EMPID_SEQ.nextval into :new.EMPID from dual;
end;
/
ALTER TRIGGER EMPID_TRIG ENABLE;

4.Insert record into table without EmpId.Notice that EmpId is autofilled by sequence value.
SQL>  insert into employee1(empname,empsal) values('suraj',1000);
SQL>   insert into employee1(empname,empsal) values('raj',200);




5>View Record to see the autoIncrement working
SQL> select * from employee1;

     EMPID EMPNAME        EMPSAL
---------- ---------- ----------
       101 suraj            1000
       102 raj               200


Friday, February 17, 2012

Running javaProgram without main() not possible in JDK1.7 latest Version

Running Java Program without main() has become an old story now.
So far we used to write the program like this
StaticDemo.java
public class StaticDemo
{
   static
    { 
        System.out.println("Hello");
        System.out.exit(0); 
     }
}
And then >javac *.java
>java StaticDemo

It compiles and runs successfully,printing Hello

This works well in JDK1.7 old versions(build 1.7.0-ea-b19)

But From jdk 1.7(build1.7.0-ea-b85),It gives run time Exception

Error: Main method not found in class StaticDemo, please define the main method
   public static void main(String[] args)


The latest version while writing this article was build  jdk 1.7(build 1.7.0_03-b05),which also doesnot allow running java program without main();

So the Concept is:
When we say
java StaticDemo
Compiler understands that we are trying to execute the program,so before executing the static block,it first checks whether main() is there or not.If not,throws Exception

Tuesday, February 14, 2012

Email Validation Using RegularExpression

We can validate Email using regularExpression support given by JDK

  EmailValidation.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidation{
     
    public static void main(String args[])
    {
      Pattern pattern;
      Matcher matcher;
String email="suraj20p@gmail.com";
      String EMAIL_PATTERN = "^[_A-Za-z0-9]+(\\.[_A-Za-z0-9]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

   
     //compile our pattern
     pattern = Pattern.compile(EMAIL_PATTERN);
     //pass our email to matcher,so that it can be checked whether pattern is matching or not
     matcher = pattern.matcher(email);
    
     //check whether string is matched or not
      boolean result= matcher.matches();

      if(result)
           System.out.println("Email Validated Successfully");
      else System.out.println("Invalid Email Address");
    }
}


  Download Source Here

Friday, February 10, 2012

Creating a Formatted XML using Java

Lets Assume we want to create an XML file,
Eg:-

CreatXMLFile.java
----------------------
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
public class CreatXMLFile
{  
public static void main(String[] args) throws Exception
 {   
    //creating factory
    DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();
    //creating a builder
    DocumentBuilder documentBuilder =documentBuilderFactory.newDocumentBuilder(); 
    //creating a document
    Document document = documentBuilder.newDocument();
   
    String root = "SMS";

    //adding root Element
    Element rootElement = document.createElement(root);
    rootElement.setAttribute("area", "hyderabad");

    document.appendChild(rootElement); //adds <SMS> as root element

    String element ="Number";    
    String data = "12345";
   
    Element em = document.createElement(element);
    em.appendChild(document.createTextNode(data));
    rootElement.appendChild(em);  //creates <Number>12345</Number> and adds to root element<SMS>
/*
<SMS>
<Number>12345</Number>
</SMS>
*/
  
    element ="message";   
    data= "hello";
  
    em = document.createElement(element);  
    em.appendChild(document.createTextNode(data));
    rootElement.appendChild(em); //creates <message>hello</message> and adds to root element<SMS>
/*
<SMS>
<Number>12345</Number>
<message>hello</message>
</SMS>
*/
  
  
    em=document.createElement("delivered");
    Element childElement = document.createElement("status");
    childElement.appendChild(document.createTextNode("failed"));
    em.appendChild(childElement);
    rootElement.appendChild(em);//creates <delivered><status> failed</status></delivered> and adds to root element<SMS>

 /*<SMS>
<Number>12345</Number>
<message>hello</message>
<delivered>
      <status> failed</status>
</delivered>
</SMS>
    */
   
    //Used to Write the generated xml structure to  file or system console
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");//arrange the xml in an idented format
    DOMSource source = new DOMSource(document);   
    File f=new File("d:/myfile.xml");
   
    StreamResult result =  new StreamResult(f);  //prints xml into file
    //StreamResult result =  new StreamResult(System.out);   
    transformer.transform(source, result);
 
 }
 }

Thursday, February 9, 2012

Adding column to Existing Table

Syntax
alter table <tableName> add  <New_Column> <datatype_with_size>;



SQL>alter table employee add  empsal number(5);

Wednesday, February 8, 2012

Creating Sequence

A sequence is a variable that can be used to generate unique value everytime


Creating Sequence
CREATE SEQUENCE EMPID_SEQ
 MINVALUE 1
 START WITH 1
 INCREMENT BY 1
 NOCACHE

Calling Sequence
 SELECT EMPID_SEQ.NEXTVAL FROM DUAL;



Dropping Sequence
DROP SEQUENCE EMPID_SEQ