share

Saturday, 28 February 2015

How To Create Servlet

How to create Servlet or call servlet

step 1:

create a index.jsp file or index.html file and make a form.

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="Display" method="post">
first name:<input type="text" name="firstName"><br>
last name:<input type="text" name="lastName" ><br>
<input type="submit" value="submit">
</form>
</body>
</html>

Step 2:

Now create a servlet display.java

Display.java


package com.jsp.test;

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 Display extends HttpServlet{

   
   
    /**
     *
     */
    private static final long serialVersionUID = 5346650776384140650L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
          String firstNAme=request.getParameter("firstName");
          String lastName=request.getParameter("lastName");
          PrintWriter out=response.getWriter();
          out.print("Welcome"+"  "+firstNAme+"  "+lastName);
          out.close();
    }

}

Step 3:

configure web.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>JSP</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 
   <servlet>
    <servlet-name>Display</servlet-name>
    <servlet-class>com.jsp.test.Display</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Display</servlet-name>
    <url-pattern>/Display</url-pattern>
  </servlet-mapping>
 
</web-app>



Saturday, 14 February 2015

How To Read JSON In Java

 How to read json file in java
Step 1:
 Firstly download  json-simple-1.1.1.jar  .

Step2:
Add this jar in ellipse(this tutorial tells how to read json file in java using ellipse).


 Step 3:


Now you try with code


How To Read JSON In Java (Set 1)

How To Read JSON In Java (Set 3)

How To Read JSON In Java (Set 2)


Friday, 13 February 2015

How To Read JSON In Java (Set 3)

user.json

{"employees":[
    {"firstName":"Rahul", "lastName":"Dhiman"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"MS", "lastName":"Dhoni"}
]}


TestJson.java

import java.io.FileReader;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class TestJsonset1 {
    public static void main(String[] args) {
         String filePath = "D:\\json\\user.json";
        try {
            FileReader reader = new FileReader(filePath);
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
            JSONArray lang= (JSONArray) jsonObject.get("employees");
             Iterator i=lang.iterator();
             while (i.hasNext()) {
                 JSONObject jsonobject1=(JSONObject)i.next();
                System.out.println("first name="+jsonobject1.get("firstName")+"   last name="+jsonobject1.get("lastName"));  
            }
        }catch (Exception e) {
                System.out.println(e);
            }
        }
}

Output:

first name=Rahul   last name=Dhiman
first name=Anna   last name=Smith
first name=MS   last name=Dhoni


How To Read JSON In Java (Set 2)


user.json

{"employees":[
    {"firstName":"Rahul", "lastName":"Dhiman"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"MS", "lastName":"Dhoni"}
]}

TestJson.java
 
import java.io.FileReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class TestJson{
    public static void main(String[] args) {
         String filePath = "D:\\json\\user.json";
        try {
            FileReader reader = new FileReader(filePath);
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
            JSONArray lang= (JSONArray) jsonObject.get("employees");
            for (int i = 0; i < lang.size(); i++) {
             System.out.println(lang.get(i));
            }
        }catch (Exception e) {
                System.out.println(e);
            }
        }
}

Output:
{"firstName":"Rahul","lastName":"Dhiman"}
{"firstName":"Anna","lastName":"Smith"}
{"firstName":"MS","lastName":"Dhoni"}



How To Read JSON In Java (Set 1)



user.json

{"employees":[
    {"firstName":"Rahul", "lastName":"Dhiman"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"MS", "lastName":"Dhoni"}
]}

TestJson.java

import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class TestJson{
    public static void main(String[] args) {
         String filePath = "D:\\json\\user.json";
        try {
            FileReader reader = new FileReader(filePath);
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
            System.out.println(jsonObject);
        }catch (Exception e) {
                System.out.println(e);
            }
        }
}



Output:

{"employees":[{"firstName":"Rahul","lastName":"Dhiman"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"MS","lastName":"Dhoni"}]}

JSON Tutorial

Thursday, 12 February 2015

How To Change File Permission Using Java

In last tutorial we learn How To Check File Permissions In Java ,Now We learn how to change file permission using java code. now firstly we create a file and check its permission


Now we use this java code
 public class ChangeFilePermission {
  
      public static void main(String[] args) {
          String path="D:\\file\\read.txt";
        File file=new File(path);
        if (file.exists()) {
            System.out.println("read="+file.canRead());
            System.out.println("write="+file.canWrite());
            System.out.println("Execute="+file.canExecute());
            file.setReadOnly();
        }      
    }
    
}
Now we again check file permission.Definitely it will as ...

 


How To Check File Permissions In Java

In this program we learn how to know about file permission mode using java code.


Now we create a file in read only mode .


public class FilePermission
       public static void main(String[] args) {
           String path="D:\\file\\read.txt";
        File file=new File(path);
        if (file.exists()) {
            System.out.println("read="+file.canRead());
            System.out.println("write="+file.canWrite());
            System.out.println("Execute="+file.canExecute());
        }
       
    }


}

Wednesday, 11 February 2015

Read All Files From Any Directory(Folder)

Read a given directory(Folder). Filer its file and folder(directory).
and also show name of files and name of folder

import java.io.File;

public class ReadDirectory {
public static void main(String[] args) {
     String path="D:\\a";      
        try {
            File folder= new File(path);
            File[] listOfFiles= folder.listFiles();
        for (int i = 0; i < listOfFiles.length; i++) {
          if (listOfFiles[i].isFile()) {
                  System.out.println("File=" + listOfFiles[i].getName());        
          } else if (listOfFiles[i].isDirectory()) {
        System.out.println("Directory=" + listOfFiles[i].getName());
          }
          }
        } catch (Exception e) {
            System.out.println(e);
        }

}
}

Read One File And Write Other File

In this Program we two file and we copy data of first.txt file in second.txt file using java code

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyData {

    public static void main(String[] args) throws IOException {
    String pathInput="D:\\a\\first.txt";
    String pathOutput="D:\\a\\second.txt";
    FileInputStream in=null;
    FileOutputStream out=null;
    try {
        in=new FileInputStream(pathInput);
        out=new FileOutputStream(pathOutput);
        int c;
        while ((c=in.read())!=-1) {
            out.write(c);
        }
    } catch (Exception e) {
        System.out.println(e);
    }finally{
        if (!(in==null)) {
            in.close();
        }
        if (!(out==null)) {
            out.close();
        }
       
    }
    System.out.println("Copy Data");
}
   
}

delete file in java

Delete file in java

import java.io.File;

public class DeleteFile {
    public static void main(String[] args) {
          File f=null;
          String path="D:\\a\\hi.txt";
          try {
            f=new File(path);
            boolean b=f.delete();
            System.out.println("file delete="+b);
        } catch (Exception e) {
            System.out.println(e);
        }
    }   
}

Read File LIne By Line In Java

 In this program we read a file line by line using buffered reader

package filles;
import interview_set1.fileRead;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;

public class ReadFiles {
public static void main(String[] args) {
    String path="D:\\a\\hi.txt";
    BufferedReader br=null;
    try {
        FileReader fr=new FileReader(path);
        br=new BufferedReader(fr);
        String line;
        while ((line=br.readLine())!=null) {
            System.out.println(line);
        }
       
    } catch (Exception e) {
        System.out.println(e);
    }
}
}

File Create In Java

How To create file in java

Example:

package filles;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class CreateFiles {
 
    public static void main(String[] args) {
          try{
             // create new file
             String content = "This is the content to write into create file";
             String path="D:\\a\\hi.txt";
             File file = new File(path);
   
                // if file doesnt exists, then create it
                if (!file.exists()) {
                    file.createNewFile();
                }
   
                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                // write in file
                bw.write(content);
                // close connection
                bw.close();
          }catch(Exception e){
              System.out.println(e);
          }
         
    }
}


File Handling In Java

Monday, 9 February 2015

Multithreading in Java


What is Multithreading?
Life Cycle of a Thread
thread vs proccess.
Thread Scheduler
Creating Thread
Sleeping a thread
Start a thread twice
Calling run() method
Joining a thread
Naming a thread
Thread Priority
Daemon Thread
Thread Pool
Synchronization
Messaging
Thread Class
Runnable Interface .
IsAlive()
Join()

Sunday, 8 February 2015

Try And Finally Without Catch Block

1. We Can Use Finally after try block ,it will run gives message in finally block.But can not handle exception.
Syntax:

try{


}Finally{


}

public class ExceptionSample {
public static void main(String[] args) {
try {
int i=10/0;
}finally{
System.out.println("Finally Block");
}
System.out.println("You Are Come Back In Main");
}

}

Output:
Exception in thread "main" Finally Block
java.lang.ArithmeticException: / by zero
at exception_handling.ExceptionSample.main(ExceptionSample.java:6)

Finally Block In Java

Finally block always execute after try catch block.

1.
 package exception_handling;

public class FinallyBlock {
           
public static void main(String[] args) {
try {
int i=10/0;
} catch (Exception e) {
System.out.println(e);
}
finally{
System.out.println("You Are In Finally Block");
}
}
}


Output:
java.lang.ArithmeticException: / by zero
You Are In Finally Block

2.

package exception_handling;

public class FinallyBlock {
            
public static void main(String[] args) {
try {
int i=10/10;
} catch (Exception e) {
System.out.println(e);
}
finally{
System.out.println("You Are In Finally Block");
}
}
}

Output:
You Are In Finally Block

3. If You Use Return Statement in try /catch block then finally always execute  

package exception_handling;

public class FinallyReturn {
int display(){
try {
System.out.println("In display try"); 
return 2;
} catch (Exception e) {
System.out.println(e);
}finally{
System.out.println("Hi Finally Here");
}
return 1;
}
public static void main(String[] args) {
FinallyReturn finallyReturn=new FinallyReturn();
finallyReturn.display();
}
}

Output:
In display try
Hi Finally Here


4. If we use exit(0) in  try block then finally block will not execute.
package exception_handling;

public class FinallyExit {

public static void main(String[] args) {
try {
System.out.println("welcome Dear");
System.exit(0);
} catch (Exception e) {
System.out.println(e);
}finally{
System.out.println("Welcome In Finally Block");
}
}
}

Output:
welcome Dear

Nested Try Blocks In Java

We can use nested try block in java.

Syntax:1


       try {

            // some statement
try {

               // some statement
} catch (Exception e) {

}

} catch (Exception e) {

}

Syntax:2


try{

display();

}catch(){

}

void display(){

try{

}catch(){

}


}





1. 

public class NestedTry {


public static void main(String[] args) {


try {
 
System.out.println("Outer Try");
int []arr=new int[5];
arr[10]=100;
try {
System.out.println("Inner Try");
int i=100/0;
} catch (Exception e) {
System.out.println(e);
}

} catch (Exception e) {
System.out.println(e);
}


}



}

Output:

Outer Try
java.lang.ArrayIndexOutOfBoundsException: 10

Explanation: See This  Interesting Facts In Exception Handling In java

2.


package exception_handling;

public class NestedTry {

public static void main(String[] args) {

try {
 
System.out.println("Outer Try");
int []arr=new int[5];
try {
System.out.println("Inner Try");
int i=100/0;
} catch (Exception e) {
System.out.println(e);
}
} catch (Exception e) {
System.out.println(e);
}
}

}

Output:

Outer Try
Inner Try
java.lang.ArithmeticException: / by zero


3.

package exception_handling;

public class NestedTry {

void divideNumber(){
try {
System.out.println("In divide number");
int j=10/0;
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {

try {
 
System.out.println("Outer Try");
  int []arr=new int[5];
           NestedTry nestedtry=new NestedTry();
           nestedtry.divideNumber();
} catch (Exception e) {
System.out.println(e);
}
}

}

Output:

Outer Try
In divide number
java.lang.ArithmeticException: / by zero

Interesting Facts In Exception Handling In java

1. What will Output Of This Program:

public class MultipleCatch {
public static void main(String[] args) {
int []arr=new int[5];
try {
arr[10]=100;
int j=10/0;
}
catch (ArithmeticException e) {
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}


}
}

Explanation : when the statement arr[10]=100  encounter to compiler so exception occur and compiler check matching catch block and produce message  according it.

Output:

java.lang.ArrayIndexOutOfBoundsException: 10
 

2. What will Output Of This Program:

public class MultipleCatch {
public static void main(String[] args) {
int []arr=new int[5];
try {
arr[10]=100;
int j=10/0;
}
catch (ArithmeticException e) {
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}


}
}

Output:
java.lang.ArithmeticException: / by zero

3. What will Output Of This Program:


package exception_handling;

public class MultipleCatch {
public static void main(String[] args) {
int []arr=new int[5];
try {
arr[10]=100;
System.out.println("You Are In Catch Block");
catch (ArithmeticException e) {
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
System.out.println("You Are In Main Method");
}
}


Explanation : when the statement arr[10]=100  encounter to compiler so exception occur . Now compiler ignore remaining  try block and check matching catch block and produce message  according it and continue to flow of program. 

Output:
java.lang.ArrayIndexOutOfBoundsException: 10
You Are In Main Method              

Multiple Catch Block In Exception Handling In java

1.  We can use multiple catch block for exception handling.

Syntax:

try {
}
catch () {
}
catch () {
}
catch () {
}

Example :


public class MultipleCatch {
public static void main(String[] args) {
int []arr=new int[5];

try {
             
arr[10]=100;
}
catch (ArithmeticException e) {
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}

}
}



Output:

java.lang.ArrayIndexOutOfBoundsException: 10

2:     Remember that when we use multiple catch block , use catch block down to top hierarchy. 
   Because in java unreachable code gives error. 

  
  public static void main(String[] args) {
           int i=10;
           int j=0;
           try {
               System.out.println("i/j="+i/j);
        } catch (Exception e) {
            System.out.println(e);
        }
         catch (IndexOutOfBoundsException e) {
                System.out.println(e);
        } 
          
       }

Output:
Unreachable catch block for IndexOutOfBoundsException. It is already handled by the catch block for Exception 

3.  The right way of uses multiple catch block is use first specific catch handle then use  standard catch handle.(i.e. down  to top ).

Example:

public class simple_example {

        public static void main(String[] args) {
           int i=10;
           int j=0;
           try {
               System.out.println("i/j="+i/j);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("index out of bound"+e);
        }
         catch (ArithmeticException e) {
                System.out.println("Arithmetic="+e);
        } 
         catch (Exception e) {
             System.out.println(e);
        } 
           
       }
}

Output:

Arithmetic=java.lang.ArithmeticException: / by zero










Saturday, 7 February 2015

How to Handle Exception In Java


1.
public class simple_example {

        public static void main(String[] args) {
      int i=10;
      int j=0;
      try {
      System.out.println("i/j="+i/j);
} catch (Exception e) {
//System.out.println(e);
System.out.println("number divide by zero");
}
   
       }
}

Output:
 number divide by zero


How To Exception Interrupt Program In java


In this  program exception occur during  the execution ,statement i/j. Normal execution of this program interrupt and program goes terminate.

public class simple_example {

        public static void main(String[] args) {
      int i=10;
      int j=0;
      System.out.println("i/j="+i/j);
       }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at exception_handling.simple_example.main(simple_example.java:8)

Exception Handling In Java



  •    An exception is a event ,which interrupt the normal flow of the program.
  •     Throwable class is the super class of all errors and exceptions in java.
  •    We can explicitly throw an exception using 'throw' clause.















Sunday, 1 February 2015

Get Maximum Difference Of Two Element In Array

This program calculate maximum difference between two  element of array
Example:

5,6,9,4,12,8,10,3,11

In this set of number
 difference between 12 and 3 is maximum 9


public class max_diff_in_array {

    public static void main(String[] args) {

    int arr[]={5,6,9,4,12,8,10,3,11};
    int max=0;
    int x=0,y=0;
    for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
   
int diff= Math.abs(arr[i]-arr[j]);
//System.out.println(diff);
           if(max<diff)
           {
            max=diff;
              x=i;
              y=j;
           }
  }
}
   
     System.out.println("max="+max+"x="+arr[x]+"y="+arr[y]);
   
   
   
   
}
}