Wednesday, July 16, 2014

Simple example of SERVLET !

Below is the sample program of SERVLET which is taken from known J2EE book ! You can start this example by simply craeting new project in Netbeans and again do right click and select Servlet option and when you do next, make sure you tick on create XML file. 

Don't worry if you feeling tense after see this coding but I just want to inform the new guys who are new to the J2EE, the syntax of the coding is fixed and it's already ready for you by netbeans, you just have to do your part of coding in the middle of this.

In this example, this is just the simple small random number program that we see in core java but the difference is, this is ruining on web browser. Here, I have write the name of the servlet is GuessWhat but you can name it whatever you like so don't worry about that.




import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class GuessWhat extends HttpServlet {

  
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
           
            String d1=Integer.toString((int)((Math.random()*99)));
            String d2=Integer.toString((int)((Math.random()*99)));
            
            
            out.println("<html> <body> "+ "<h1 align=centre>Let's guess the number by pressing F5</h1>"+
                    "<h2> This time " + d1 + " and "+ d2 +" are the right answer, now time to guess another numbers !</h2>"+"</body>"+"</html>");
            
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    
    @Override
    public String getServletInfo() {
        return "Short description";
    }

}

Wednesday, December 18, 2013

Simple program of "Thread" !!!!!

In this program, we are creating two thread and give them different sleep time. With the help of "Thread.sleep()" you can write down the milliseconds so that thread can start run after defined seconds. And to start the thread, we simple write "t1.start()" in this program, to start the particular thread. And in the last, "t1.isAlive()" is the boolean method to check the thread, whether it is alive or not !

In below program, we give 5 to 1 to first thread and 6 to 1 to second. When both threads are start than it stops for the milliseconds that we wrote different for both of them so that you can identify that which thread is complete running and complete first. And for that, we also wrote the message that "Exit from xyz thread now........." for confirmation from thread ! 




class createThread extends Thread{

public void run(){
try{
for(int i=5;i>0;i--){
System.out.println(i);
Thread.sleep(500);
}
}catch(InterruptedException e){}
System.out.println("Exit from first thread now.....");
}
}

class createThread2 extends Thread{

public void run(){
try{
for(int j=6;j>0;j--){
System.out.println(j);
Thread.sleep(1000);
} }
catch(InterruptedException e){}
System.out.println("Exit from second thread............");
}

}


public class trythread {


public static void main(String[] args) {


createThread t1= new createThread();
createThread2 t2=new createThread2();
t1.start();
t2.start();
System.out.println("First thread is alive: "+t1.isAlive());
System.out.println("Second thread is alive: "+t2.isAlive());
}

}
____________________________________________________
Output:

First thread is alive: true
Second thread is alive: true
6
5
4
3
5
2
1
4
Exit from first thread now.....
3
2
1
Exit from second thread............



Tuesday, November 12, 2013

Using "super" keyword in example of inheritance

In below program we use method overriding, in method overriding if we haven;t use "super" keyword than you can not use it. In below program, we use "super" keyword in getdata and displaydata which we already used in first class and now when we inherit the second class than we are using method overriding that mean we using same method in second class, now to access the parent class member you can use "super" key word and we did same thing here. You can also use "super" keyword to call parent class constructor within child class constructor.


import java.io.*;

class empl{

int empno;
String name;
String position;
int ph;

void getdata()throws IOException
{

DataInputStream e = new DataInputStream(System.in);

System.out.println("Enter employee number: ");
empno = Integer.parseInt(e.readLine());

System.out.println("Enter your name: ");
name = e.readLine();

System.out.println("Enter the employee position: ");
position=e.readLine();

System.out.println("Enter the phone number: ");
ph = Integer.parseInt(e.readLine());

}



void displaydata() {

System.out.println(empno+"\t"+name+"\t"+position+"\t"+ph);

}

}

class manager extends empl{

int salary;
String secname;

void getdata() throws IOException{

super.getdata();

DataInputStream e= new DataInputStream(System.in);

System.out.println("Enter salary: ");
salary=Integer.parseInt(e.readLine());

System.out.println("Enter second name: ");
secname= e.readLine();

}

void displaydata(){
super.displaydata();
System.out.println(salary+"\t"+secname);
}
}
class inheritt{
public static void main(String []args) throws IOException{

manager e1= new manager();
manager e2= new manager();


e1.getdata();
e2.getdata();

e1.displaydata();
e2.displaydata();

}
}
____________________________________
Output:

Enter employee number:

Sunday, November 10, 2013

Use of "this" keyword with very simple example


class thiss{

int a,b;

thiss(){

a=1;
b=2;}

thiss(int c,int d){
this();
this.a=c;
this.b=d;

}

void displaydata(){

System.out.println("c= "+a);
System.out.println("d= "+b);
}

public static void main(String []arg){

thiss t1= new thiss();
t1.displaydata();

thiss t2= new thiss(3,4);
t2.displaydata();
}}

___________________
Output:

c= 1;
d=2;
c= 3;
d=4;

Saturday, October 26, 2013

Example program of geting data from user using Wrapper Class

In below program, we will convert instance variable into wrapper class!

If you want to get data from user, you must have to import the java class from library, you can do this by import weather "java.io", "java.util" or "java.scanner", you can use any one of this ! 


import java.io.*;

public class employee{

int empnumber;
String name;
String add;

private void getdata()throws IOException{

DataInputStream d = new DataInputStream(System.in);

System.out.println("Enter Employee Number: ");
empnumber= Integer.parseInt(d.readLine()); 

//here we convert integer into wrapper class


System.out.println("Enter Emplyee Name: ");
name = d.readLine(); 

//in both string value,we haven't convert because String is a class not variable so no need to convert in to wrapper class

System.out.println("Enter Employee Address: ");
add=d.readLine();
}

private void display()throws IOException {

System.out.println(empnumber+"\t"+name+"\t"+add);

}



public static void main(String args[])throws IOException{

employee e1 = new employee();
employee e2 = new employee();

e1.getdata();
e2.getdata();

e1.display();
e2.display();
}
}

Facts about Constructor with an example...............

Some facts that you should know about Constructor.....................


  • It has the same name as the classname.
  • It is used to initialize the object that means it is used to construct the object.
  • It does not have any return type.
  • It can have arguments.
  • The constructor without argument is called default constructor.
  • A class can have more than one constructor but they must be different from each other by  
     - Number of arguments or
     - Type of arguments or
     - Sequence of arguments
This concept is called constructor overloading.  

  • It is automatically called when an object is created.
Simple example to explain constructor in program.
___________________________________________


import java.io.*;
class cons
{
int a,b;
cons()//defulat constructer
{
a=10;
b=20;
System.out.println("default constructer");
}
cons(int p,int q)//parametrised constructer
{
a=p;
b=q;
System.out.println("parametrised constructer");
}
cons(int p)//one parametrised constructer
{
a=p;
b=25;
System.out.println("one parametrised constructer");
}
void show()
{
System.out.println("a = "+a);
System.out.println("b = "+b);
}

public static void main(String arg[])throws IOException
{
cons c1=new cons(); 
c1.show();
cons c2=new cons(10); 
c2.show();
cons c3=new cons(100,200); 
c3.show();
cons c4=new cons(); 
c4.show();
cons c5=new cons(); 
c5.show();
cons c6=new cons(1000,2000); 
c6.show();
cons c7=new cons(5000,10000); 
c7.show();
}
}

Tuesday, January 1, 2013

Searching value and Reverse code !!!!!!


public class FindandReverse {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

int i[] = {1,2,3,5,6};

int searchVal = 55;

boolean found = false;

for(int a = 0; a<i.length;a++){

if(i[a]==searchVal){

found = true;}
}

if(found){

System.out.println("We found the value "+ searchVal+ "! " );

}
else{

System.out.println("Can't find "+searchVal+ " in this array.");

}

// ********************************************************

int x= 123456;


int temp = 0;

int reverse = 0;

while(x>0){

temp = x%10; //get the value from right of x

reverse = reverse * 10 + temp; //add the value to the reverse
x = x/10; //remove the value from the x


} System.out.println("\n"+reverse);


}
}
_________________________________________________

Output:

Can't find 55 in this array.

654321


Wednesday, December 12, 2012

Multithreading in Java !!!!!


A multiprocessor system can actually do more than one thing at at time but with Java threads, it can appear that you are doing several things simultaneously. Execution can move back and forth between stacks so rapidly that you feel as though all stacks are executing at the same time. 

Thread t = new Thread(r);

Thread is a class in the java.lang package. And this package is imported by default even without package declaration.    A Thread object represents a thread of execution, you will create an instance of class Thread each time you want to start up a new thread of execution.


Three states of new thread


  • When thread is new !

A thread instance has been created but not started. In other words, there is a Thread object but no threa of execution.


  • When thread is in Runnable state !  (t.start();)

When you start the thread, it moves into the runnable state. This means the thread is ready to run and just waiting for its chance to be selected for execution. 


  • When thread is in Running state !
Only the JVM thread scheduler can make that decision. You can sometimes influence that decision but you can not force a thread to move from runnable to running. 


The thread scheduler can move a running thread into blocked state for a variety of reasons. The scheduler will move the thread out of the running state until something becomes available. It can put the thread in sleep by sleep(). You can force the currently running thread to leave the running state and give chance to another  thread to run. In the sleep() method, that's for sure that sleeping thread will not become the currently running thread before the length of sleeping time has expired. 

And how will you apply the sleep() method, that also simple, just write down Thread.sleep(1000); This mean the current thread will not be execute till 1 second. Everything we write down in this method is in milliseconds. 

When you pass a Runnable to a Thread constructor, you are really just giving the Thread a way to get to a run() method. You are giving the Thread its job to do.


___________________________________________

Here I am giving the example of Thread which is taken from Head First Java book for your reference : 

In this example we took two thread and give there name and also set small scenario like what happen if one of the thread sleep or wake up that is runnable and what happen if there is not enough money for them in bank account.



class BankAccount{

private int balance = 100;

public int getBAalance(){
return balance;
}
public void Withdraw (int amount){
balance = balance - amount;
}
}



public class RyanAndMonicaJob implements Runnable {

private BankAccount account = new BankAccount();

public static void main(String[] args) {


RyanAndMonicaJob theJob = new RyanAndMonicaJob();
Thread one = new Thread(theJob);
Thread two = new Thread(theJob);

one.setName("Ryan");
two.setName("Monica");
one.start();
two.start();

}

public void run(){
for(int x = 0; x<10;x++){
makeWithdrawl(10);
if(account.getBAalance() < 0){
System.out.println("Overdrawn!");
}
}
}

private void makeWithdrawl(int amount){

if(account.getBAalance() >=amount){
System.out.println(Thread.currentThread().getName()+" is about to withdrawl.");
try{
System.out.println(Thread.currentThread().getName()+ " is going to sleep.");
Thread.sleep(500);
}catch (InterruptedException ex){ex.printStackTrace();}
System.out.println(Thread.currentThread().getName()+" woke up.");
account.Withdraw(amount);
System.out.println(Thread.currentThread().getName()+" completes the withdrawl.");
}
else{
System.out.println("Sorry,not enough for " + Thread.currentThread().getName());
}
}
}


_____________________________________________

Output:


Ryan is about to withdrawl.
Monica is about to withdrawl.
Ryan is going to sleep.
Monica is going to sleep.
Ryan woke up.
Monica woke up.
Ryan completes the withdrawl.
Monica completes the withdrawl.
Ryan is about to withdrawl.
Monica is about to withdrawl.
Ryan is going to sleep.
Monica is going to sleep.
Ryan woke up.
Ryan completes the withdrawl.
Ryan is about to withdrawl.
Ryan is going to sleep.
Monica woke up.
Monica completes the withdrawl.
Monica is about to withdrawl.
Monica is going to sleep.
Ryan woke up.
Ryan completes the withdrawl.
Ryan is about to withdrawl.
Ryan is going to sleep.
Monica woke up.
Monica completes the withdrawl.
Monica is about to withdrawl.
Monica is going to sleep.
Ryan woke up.
Ryan completes the withdrawl.
Ryan is about to withdrawl.
Ryan is going to sleep.
Monica woke up.
Monica completes the withdrawl.
Monica is about to withdrawl.
Monica is going to sleep.
Ryan woke up.
Ryan completes the withdrawl.
Ryan is about to withdrawl.
Ryan is going to sleep.
Monica woke up.
Monica completes the withdrawl.
Sorry,not enough for Monica
Sorry,not enough for Monica
Sorry,not enough for Monica
Sorry,not enough for Monica
Sorry,not enough for Monica
Ryan woke up.
Ryan completes the withdrawl.
Overdrawn!
Sorry,not enough for Ryan
Overdrawn!
Sorry,not enough for Ryan
Overdrawn!
Sorry,not enough for Ryan
Overdrawn!
Sorry,not enough for Ryan
Overdrawn!

_____________________________________________

Monday, December 10, 2012

Understand Wrapper and parse !!!


Practically Wrapper mean wrap the primitive in different value, so that we can use it as per the situation. 

There is wrapper class for every primitive in java. The wrapper class for int is Int, float is Float, char is Character, byte is Byte, double is Double and so on.


                Integer int1 = new Integer("4");
Integer int2 = new Integer("1");
Double int3 = new Double(123.12);

i = int2 + int1;
System.out.println(i);        //5


When we convert the value of wrapped numeric to a primitive than we use following value() methods. That mean we put byteValue(), doubleValue() and so on. 

byte b = int1.byteValue();
System.out.println(b);           

short s = int3.shortValue();
System.out.println(s);

double d = int2.doubleValue();
System.out.println(d);


Following example show the created value of int4 is 5, cause when you convert binary of 101 than you will get 5. So int = 5 now. This is called valueOf() method.

Integer int4 = Integer.valueOf("101",2);
System.out.println(int4);  


Now we look on some parseXxx()  method, it is nearly like valueOf() method.
Following example is for converting string to other primitive what ever you like to apply.


               double d1 = Double.parseDouble("789.456");
System.out.println(d1);


               long l1 = Long.parseLong("101",2);
System.out.println(l1);

Now above example is same like we apply in valueOf() methos, we get same output but using different method.

        

Now when we use toXxxString() method than it convert the following:



                String s1 = Integer.toHexString(123);  
System.out.println(s1);                             // 7b

String s2 = Long.toOctalString(123);
System.out.println(s2);                              //173

String s3 = Double.toHexString(789);
System.out.println(s3);                             //0x1.8a8p9




Now toString(), in this method you can convert every primitive values to string:


               Long l = new Long("789456123");
System.out.println(l.toString());        //789456123

String l2 = Long.toString(789456123);


You can take different primitive value.





Tuesday, December 4, 2012

Understand Abstract class and Interface !!!


Abstract class and Methods



- An Abstract class can not be instantiated but they can be subclassed.

- An Abstract method is method that is declared without an implementation without braces and followed by semicolon.

Example:

public abstract class Animal{

        abstract void eat();

}

- All abstract methods must be implemented in the first concrete subclass    in the inheritance tree. 

- An abstract class can have both abstract and non abstract methods.

- When you don't want a class to be instantiated mark the class with abstract keyword.

- If a class has even one abstract method, the class must be marked abstract.


We have here AnimalObject in above image, might be all three sublcass that is Lion, cat and zebra behave totally different but other thing we find common is eat and roam. You can take advantage of similarities and declare all the animals to inherit from the same abstract object. Lion , Cat and Zebra inherit from Animal.

Example:

public abstract class Animal{
         
         abstract void eat();
         abstract void roam();
}


class Lion extends Animal{

        void eat();{
} 
       void roam();{

}

class Cat extends Animal{

        void eat();{
} 
       void roam();{

}


class Zebra extends Animal{

        void eat();{
} 
       void roam();{

}


Now all this above three non abstract subclass of Animal that is Lion, Cat and Zebra must provide implementation.



Interface 



- An interface is a reference type similar to a class that can certain only constants method signature and nested types. There are no method bodies. 

- Use interface when you want different behavior different classes.

- Interface can not be implemented by class or extended by other interfaces.

- Create an interface using the "interface" keyword instead of class.


Example:

public interface mainInterface extend Interface1, Interface2, Interface3{

               void doSomething (int a, float y);
               int doSomethingElse(String s);
} 


The public access specifier indicates that the interface that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface.

An interface can extend other interfaces just as a class can extend or subclass another class. As you know that the class can only extend other class but interface can extend any number of interfaces. And it declare by  comma as shown in above example. 



Thank you for your time..............