Wednesday, July 31, 2013

How many ways are there to register JDBC driver with DriverManagerService

                                                JDBC is used for to interact java application with Data Base Software.By using JDBC API database vendors are develop JDBC drivers.This JDBC driver class names are vary from Database to Database. This JDBC driver class name contains static method which contains logic to object for JDBC driver class and register this object with DriverManager Service. Generally we are using this process to register Driver class with DriverManager Service.But we can register our Driver  class with DriverManager Service in so many ways.They are
1. 
    Sun.jdbc.odbc.JdbcOdbcDriver obj=new Sun.jdbc.odbc.JdbcOdbcDriver();
    DriverManager.registerDriver(obj);
           This above code register JDBC driver  twice with DriverManager Service.
 (i)To static block of driver class when driver class object is created.
 (ii) Explicitly when programmer calls DriverManager.registerDriver();

2.
     Sun.jdbc.odbc.JdbcOdbcDriver obj=new Sun.jdbc.odbc.JdbcOdbcDriver();
            Here JDBC driver will be register DriverManager Service only once but programmer creates one explicit unused object for driver class.

3. DriverManager.registerDriver(new Sun.jdbc.odbc.JdbcOdbcDriver());

    Limitations are same as approach 1

4. class.forName("Sun.jdbc.odbc.JdbcOdbcDriver");

static block of driver class registers jdbc driver with DriverManager service only once.

5. class.forName(args[0]);
   >java javaclassname Sun.jdbc.odbc.JdbcOdbcDriver

Same as approach 4 but allows to pass JDBC driver class  name from outside the application dynamically at runtime. 

6. We can pass input value to Java application as System property value by using java -D option.To read this value our application can use System.getProperty() method.

>java _Dmy.driver=Sun.jdbc.odbc.JdbcOdbcDriver() javaclassname

7. The DriverManager class attempts to load the Driver classes automatically which are referenced in the System property called "jdbc.driver"
             
  >java _Djdbc.drivers=Sun.jdbc.odbc.JdbcOdbcDriver() javaclassname   
8. In the process of loading subclass the JVM automatically loads superclass will be executed automatically .The below process is not recommended it makes our class not extending from other useful classes like Thread,Frame,Applet.

Log4j with XML file

                          For executing Log4j programs,we are using properties file for configuring details of Log4j. In this post, we will configure Log4j details with XML file.And we can keep this file under src folder. 

log4j.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

<appender name="myAppender" class="org.apache.log4j.ConsoleAppender">
<layout   class="org.apache.log4j.SimpleLayout"/>
</appender>
<root>
<priority     value = "debug"     />
<appender-ref ref   = "myAppender"/>
</root>

</log4j:configuration>

Log4JJava.java :

package com.log4j;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;


public class Log4JJava{ 

static Logger log = Logger.getLogger(Log4JJava.class.getName());

public static void main(String[] args) { 
                /* By using DOMConfigurator.configure() method and passing xml file as argument */
DOMConfigurator.configure("log4j.xml");
               /* call debug() method on log object and passing String message as argument */
log.debug("Debug");
log.info("Info"); 


}

Wednesday, July 17, 2013

Run Log4J program without Properties file

How run Log4j program without using Properties file?

We will write programs in two ways.

Type 1:
package com.log.appender;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.util.Properties;

public class Log4jPropr{
 static Logger log = Logger.getLogger(Log4jPropr.class);

 public static void main(String[] args) {

 Properties log4jProperties = new Properties();
 log4jProperties.setProperty("log4j.rootLogger", "INFO, myConsoleAppender");
 log4jProperties.setProperty("log4j.appender.myConsoleAppender", "org.apache.log4j.ConsoleAppender");
 log4jProperties.setProperty("log4j.appender.myConsoleAppender.layout", "org.apache.log4j.PatternLayout");
 log4jProperties.setProperty("log4j.appender.myConsoleAppender.layout.ConversionPattern", "%-5p %c %x - %m%n");
 PropertyConfigurator.configure(log4jProperties);
 log.setLevel(Level.DEBUG);

 log.debug("This is a debug message");
 log.info("This is an info message");
 }
}

Output:

DEBUG com.log.appender.Log4jPropr  - This is a debug message

INFO  com.log.appender.Log4jPropr  - This is an info message

Type-2:

package com.log.appender;

import java.io.IOException;

import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

public class Log
{
    public static Logger as_looger;
    public static void main(String[] args) {
    as_looger = Logger.getLogger("articles logging");
        as_looger = Logger.getLogger(Log.class.getName());
        FileAppender as_appender = null;
            try {
as_appender = new DailyRollingFileAppender(new PatternLayout("%d{dd-MM-yyyy HH:mm:ss} %C %L %-5p: %m%n"), "path of file where to write logs","'.'dd-MM-yyyy");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        as_looger.setLevel(Level.DEBUG);
        as_looger.addAppender(as_appender);
}

}





Tuesday, July 16, 2013

Prime Numbers in javascript

<HTML>
<HEAD>
<TITLE> Prime Number </TITLE>
</HEAD>
<script>
var inum=prompt("Enter a Value");
var a=new Array();
var val=0;
for(var ind = 1;ind<=inum;ind++){
count = 0;
for(i=2;i<=ind/2;i++){
if(ind%i==0){
count++;
break;
}
}
if(count==0 && ind!= 1){
a[val]=ind;
val++;
}
}
var indVal=9;
var inc=0;
while(inc<a.length)
{
inc++;
document.write("<font color='#"+ Math.floor(Math.random() * 16777215).toString(16)+"'>"+a[indVal]+"&nbsp&nbsp</font>");
indVal--;
if(inc%10==0)
{
document.write("<br>");
indVal=inc+9;
}
if(indVal>a.length)
{
var temp=indVal-a.length;
indVal=indVal-temp-1;
}
}
</script>
<body>
</body>
</html>

ImageSlideShow

Write a JavaScript program for ImageSlideShow?

Conditions:
a) Create a html page that has 10 images in it.
b) Create a slideshow that displays images with the gap of 2 seconds.
c) There should be counter on the screen that displays the total number of images, images already shown
and images left in the queue should also be shown as a status.
d) Display page content in the middle of the page in proper alignment
e) Try to prepare a good looking html page .
f) You are only allowed to use html for design the page and javascript for scripting logic.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Slide Show</title>
<script>
var ind=0;
var pre=0;
function valid(){
setTimeout(function(){slide()},1000);
}
function slide()
{
if(ind<8){
var imgArr=["Blue hills.jpg","Sunset.jpg","Water lilies.jpg","Winter.jpg","Bluei.jpg","Bluei1.jpg","Bluei2.jpg","Bluei3.jpg"];
var content="<img src='"+imgArr[ind]+"' width='200' height='200'>";
document.getElementById('pp').innerHTML=content;
    document.getElementById('pre').value=ind;
    document.getElementById('now').value=ind+1;
    document.getElementById('next').value=imgArr.length-ind-1;
    ind=ind+1;
    
    valid();
    }
}

</script>

</head>
<body>
<form><div><p id='pp'><br><input type='button' id='sta' value='Start' onclick='return valid()'></p><br>
Previous <input type='text' id='pre'>
Present:<input type='text' id='now'>
Remain:<input type='text' id='next'>

</div></form>

</body>
</html>

Monday, July 15, 2013

RegistrationForm


a. Design a HTML page as below fig. 
b. Validate above form field 
i. Name Field should not be empty. 
ii. Validate Name field for only characters and special symbols i.e.(A-Z a-z _ . ). 
iii. Validate Gender: At least choose one of Gender. 
iv. Above validation should happen on form submit, i.e. ‘Onclick’ on Submit Button 
c. Display form content in the middle of the page with proper alignment. 
d. Try to design a good looking html page. 
e. You are only allowed to use HTML for design the page and JavaScript for scripting logic.


<html>
<head>
</head>
<script>
function checkForm()
{
var reg=/^[a-zA-z._]+$/;
var user_name=document.getElementById("userName").value;
var gen=document.getElementsByName('gender');
var qualification=document.getElementsByName('qua');
if(user_name=='')
{
alert("Please Enter Your Name");
document.getElementById('userName').focus;
return false;
}
//checking userName withregularExpression
if(!user_name.match(reg))
{
alert("please enter alphabitical and symbols");
}
//checking options are selected or not
if (document.getElementById('male').checked == false && document.getElementById('female').checked == false)
{
alert("Please select gender");
}
for(var ind=0;ind<qualification.length;ind++)
{
if(qualification[ind].checked==true)
return true;
}
return false;
alert("Your name is "+user_name);
return true;
}
</script>
<body><center><form name="regForm" id="res" onsubmit="return checkForm()">
<div id="form" style="width:350px; background-color:green">
<fieldset>
<legend style="BackGround-color:blue;color:yellow;font-weight:bold;">RegistrationForm</legend>
<table>
<tr>
<td>Name:<span style="color:red; ">*</span> <input type="text" name="userName" value="" style="border: 5px; bordercolor:red"></td></tr>
<tr>
<td>Gender:<b style="color:red">*</b>&nbsp<td bgcolor="red"><input type="radio" name="gender" id="male" value="Male">Male <input type="radio" name="gender" id="female" value="Female">Female </td>
</tr>
<tr>
<td>Qualification:<b style="color:red">*</b></td><td bgcolor="yellow"><input type="radio" name="qua" id="bca" value="Male">BCA <input type="radio" name="qua" id="bsc" value="bsc">BSc</br><input type="radio" name="qua" id="bca" value="Mca">MCA <input type="radio" name="qua" id="mtech" value="mtech">Mtech </td>
</tr>
<tr>
<td colsapn="2" align="center"><input type="submit" name="reges" id="regist" value="Submit"></td>
</tr>
</table>
</fieldset>
</div></form>
</center></body>
</html>

Reverse String

a. Create a HTML page with a text box and a button. 
b. Take a string as input from user and count different types of characters in given string and print and also print the reverse of the string in same page. 
c. Validate for m fields for Empty - 
i. Above validation should happen on button click. 
ii. ON VALIDATION DISPLAY PROPER USER FRIENDLY MESSAGE TO USER. 
d. For example: “apple” would be 
a=1 
p=2 
l=1 and 
e=1 
Reverse: 
apple -> elppa 
e. Display page content in the middle of the page with proper alignment. 
f. Try to design a good looking html page. 

g. You are only allowed to use HTML for design the page and JavaScript for scripting logic. 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
</HEAD>
<script>
function strReverse()
{
var input=document.getElementById('text1').value.trim();
var content=document.getElementById('stringt');
var newTable="<tr><td>";
var cha=new Array();
var reverse=[];
var leng=input.length-1;
var stri='';
//reverse.length=input.length;
var reg=/^[a-zA-Z._]+$/;
if(!reg.test(input))
{
alert("Please enter String");
return false;
}
cha.length=input.length;
var count;
for(var index=0;index<input.length;index++)
{
count=1;
reverse[leng-index]=input[index];
for(var i=0;i<input.length;i++)
{
if(index!=i&&input[index]==input[i])
{
count++;
}
}
if(input[index]==input[index-1]){}
else{
cha[index]=input[index]+'='+count;
newTable=newTable+cha[index]+"</td></tr><tr><td>";
}
}
for(var c=0;c<leng+1;c++)
{
stri=stri+reverse[c];
}
newTable=newTable+"<tr><td>"+stri+"</td></td></table>";
content.innerHTML=newTable;
return true;
}
</script>
<BODY><center>
<form id='form' onsubmit='return strReverse()'>
<div id='con' style="width:250px; background-color:green">Enter Your Name:<input type='text' name='str' id='text1' value=''><br>
<input type='button' name='sbutton' id='strButton' value='submit' onclick='return strReverse()'><table id='stringt' style="width:250px; background-color:red; align:middle"></table>
</div>
</form></center>
</BODY>
</HTML>

Friday, July 12, 2013

Difference between ArrayList and Vector

                 ArrayList is Resizable-Array implementation of the List interface and introduced in 1.2 version. It allow all elements include null. ArrayList is unsynchronized and it is not thread safe.In this class size,isEmpty,get,set,Iterator and ListIterator operations run in constant time.The add operation run in amortized constant time,that is,adding n elements requires O(n) time. Each ArrayList instance has a capacity.The capacity is the size of the array used to store elements in the list.An application can increase  the capacity of  an ArrayList instance before adding a large number of elements using the ensureCapacity operation.
                   Vector class is implements a growable array of objects.The size of a vector can grow or shrink as needed to accommodate adding and removing items after the vector has been created.Each vector maintaining a capacity and a capacityIncrements.  

Difference between ArrayList and Vector:

1. ArrayList class methods are not Synchronized and Vector class methods are Synchronized.So Vector class is used in multi-threading and concurrent environment.

2. When Vector class reaches it's threshold limit,then it automatically increase itself by value specified in capacityIncrement. But ArrayList call ensureCapacity() method to increase its size.

3. ArrayList gives  better performance than Vector.Because ArrayList is not Thread-Safe but Vector is Thread-safe that's why it give low performance.

4. ArrayList is introduced in 1.2 version but Vector is introduced in 1.0 version and it is called as Legacy class.

5. Vector class is Legacy class,we use Enumeration class to print elements of Vector class.For ArrayList we use  Iterator for printing elements of ArrayList objects.

If your project requirement is Threadsafe use Vector class otherwise use ArrayList class.Because ArrayList not Thread-safe so it gives better performance than Vector class.

Can we get Synchronized ArrayList:

Yes,We can get by using Collections.synchronizedList(List l); method.

ArrayList arrayList=new ArrayList();
List l = collections.synchronizedList(arrayList);  


see also this link :
prime number
why array index start with zero
reverse string in different ways in java

Thursday, July 11, 2013

ButterFlyLogic

Write the Program for ButterFlyLogic in java?

5             5
44         44
333     333
2222  2222
111111111
2222  2222
333     333
44         44
5             5

For Logic click on THis link



Wednesday, July 10, 2013

HashMap Vs HashTable

                             HashMap is HashTable based implementation of Map Interface. It doesn't follow any order. This class makes no guarantees as to the order of the Map and it doesn't guarantee that the order will remain constant over time. HashMap allows null valuers and null key. An instance of HashMap has  two parameters that affect its performance: initial capacity and load factor. The default load factor of HashMap is 0.75.
                            HashTable is implemented based on Key-Value pair data-Structure in java. It extends Dictionary and implements Map. In this Key should be unique and allow value as duplicate. It also implement hashCode() and equals() methods for comparing duplicate key.

Difference between HashMap and HashTable:

1. HashMap using  HashTable for storing key-value pairs.but HashTable uses key-value pair data structure.

2. Iterator in HashMap is Fail-Fast but enumaretion in HashTable in not Fail-Fast.

3. HashMap is not Synchronized and HashTable is Synchronized.But we can get Synchronized HashMap by using Collections class method synchronizedMap() .

4.  HashMap is HashTable based implementation of Map Interface. HashTable extends Dictionary and implements Map.

5. HashMap allows one null key and any number of null values but HashTable doesn't allows null keys and null values.

6. HashTable is not Threadsafe and HashTable is  Threadsafe.

7. HashMap is faster than HashTable.

8. We can use ConcurrentHashMap for multi-thread environment.But HashTable doesn't contain this type of facility.
Can we create Synchronization for HashMap?

Yes,We can achieve this by using Collections.synchronizedMap();

HashMap hs=new  HashMap();
Map m=Collections.synchronizedMap(hs);