Sunday, October 11, 2015

Find matrix element in java

How to find Matrix index value using java

public
static int findElement(int x, int y) {
          int[][] matrix = { { 1, 2, 3 }, { 2, 3, 4 }, { 3, 4, 5 } };
          return matrix[x][y];}

Find sum of combination on given integer array

How to find the sum of combination on given integer array.



        int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 12, 15, 18, 20, 24, 25, 27, 28 };
        int sum = 0;
      
        String test = "";
        int tmp = 0;
        System.out.println(a.length);
        for (int j = 0; j <= a.length - 1; j++) {
            sum = sum + a[j];
            test = test + a[j] + ",";
            if (sum == valueToFind) {
                System.out.println("[" + test.substring(0, test.length() - 1)
                        + "]");
                j = tmp;
                sum = 0;
                test = "";
                tmp++;
            }
            if (sum > valueToFind) {
                j = tmp;
                sum = 0;
                test = "";
                tmp++;
            }
        }
    

Monday, March 2, 2015

Using == operator in Integer

== operator is working properly with in the integer range.(-128 to 127).

Integer.valueOf() create cache with in the range  (-128 to 127).

Example 1:

Integer i = 127;
Integer j = 127

if(i == j) {
System.out.pritnln("i and j is equal") ;
}else{
System.out.pritnln("i and j is not equal") ;
}
Output: i and j is equal

If integer value is out of this range == operator will not work properly(Its depends on JVM default integerCache).

Example 2:

Integer i = 128;
Integer j = 128

if(i == j) {
System.out.pritnln("i and j is equal") ;
}else{
System.out.pritnln("i and j is not equal") ;
}
Output: i and j is not equal

Sunday, September 21, 2014

Find power of given value without using any of Math method

private static void findPowerOfValue(int findValue, int powerValue) {
        int temp = 0;
        while (findValue > powerValue) {
            temp = findValue / powerValue;
            if ((temp % powerValue) != 0) {
                System.out.println("Given value : "+findValue+" is not power of "+powerValue);
                break;
            } else {
                System.out.println("Given value : "+findValue+" is power of "+powerValue);
            }
            findValue = findValue / powerValue;
        }
    }

Integer reverse without using String reverse()

private static void reverse(int value) {
        int temp = 0;
        int temp1 = 0;
        while (value != 0) {
            // Take the values length-1
            temp = value / 10;
            // Take the last value
            temp1 = value % 10;
            // assign last value removed integer
            value = temp;
            System.out.print(temp1);
        }
    }

Friday, September 12, 2014

Swap two number without using temp variable

Code:
        int X = 5;
        int Y = 6;
        System.out.println("Before swap X is : "+X+", Y is : "+Y);
        Y = X+Y;
        X = Y-X;
        Y = Y-X;
        System.out.println("After swap X is : "+X+", Y is : "+Y);

Output: 

Before swap X is : 5, Y is : 6
After swap X is : 6, Y is : 5

Wednesday, September 10, 2014

Insert dropdown value into database. Using JSP SERVLET




Create Dynamic project: File > New > Project....> Web > Dynamic Web Project.


























Create Servlet class with name SampleTest.java(it will automatically makes entry in web.xml)
Paste the following code into doPost()
System.out.println("Selected value is : "+(String)request.getParameter("gameName"));
            String gameName = (String)request.getParameter("gameName");
            DBConnection dbConnection = new DBConnection();
            dbConnection.insertQuery(gameName);
            System.out.println("Query insert successfully");


Create DBConnection.java file


     
     


      static Connection l_objConnection;


      public static Connection getConnetion() {


            try {


                  Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
                  // Your url -jdbc:oracle:thin:@localhost:1521:DBName
                  // your username - Test
                  // your password - Test
                  l_objConnection = DriverManager.getConnection(
                              "jdbc:oracle:thin:@localhost:1521:DBName", "username",
                              "password");


            } catch (InstantiationException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            } catch (IllegalAccessException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            } catch (ClassNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            } catch (SQLException e) {
                  // TODO Auto-generated catch block test
                  e.printStackTrace();
            }


            return l_objConnection;
      }


      public void insertQuery(String gameName) {
            try {
                  // Replace your table name instead of TABLENAME
                  // Replace GAMENAME into colounm name.
                  PreparedStatement preStatement = l_objConnection
                              .prepareStatement("INSERT INTO TABLENAME(GAMENAME) VALUES (?)");
                  preStatement.setString(1, gameName);
                  preStatement.execute();
            } catch (SQLException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
      }





Create index.jsp under WebContent folder.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<SCRIPT LANGUAGE="JavaScript">
            <!--
            function button1()
            {
              var value =   document.getElementById("gameName").value;
              alert(value);
              document.SampleTest.submit()
            }   
            
            // -->
        </SCRIPT>
<body>
<FORM NAME="SampleTest" METHOD="POST" action="./SampleTest">
<select id="gameName" name="gameName">
<option>Sports</option>
     <option>Corporate</option>
     <option>Religious</option>
     <option>Music</option>
</select>
<INPUT TYPE="submit" VALUE="Save" ONCLICK="button1()">
</FORM>
</body>
</html>


Web.xml
<servlet>
    <description></description>
    <display-name>SampleTest</display-name>
    <servlet-name>SampleTest</servlet-name>
    <servlet-class>com.test.SampleTest</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>SampleTest</servlet-name>
    <url-pattern>/SampleTest</url-pattern>
  </servlet-mapping>


Output:


 

Monday, January 28, 2013

copy,delete and rename a file

File oldfile =new File("C:/Users/Boomiraj/Desktop/palani.txt");
        File newfile =new File(oldfile.getAbsoluteFile()+".tmp");

        /*if(oldfile.renameTo(newfile)){
            System.out.println("Rename succesful");
        }else{
            System.out.println("Rename failed");
        }*/
        try {
            FileUtils.copyFile(oldfile, newfile);
           
            if(oldfile.delete()){
                System.out.println("File deleted");
            }
            if(newfile.renameTo(oldfile)){
                System.out.println("File rename");
            }
            } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Friday, January 18, 2013

Pagination test code

check.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
<form action="./CSVLoginServlet" method="post">
<input type="submit" value="Submit">
</form>
</body>
</html>


result.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.util.*"%>
<!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>Insert title here</title>
</head>
<body>
    <%
        ArrayList array = (ArrayList) session.getAttribute("array");
        String pages = (String) session.getAttribute("pages");
        int i = 0;
        while (i < array.size()) {

            out.print(array.get(i));
            i++;
        }
        int j = 1;

        while (j <= Integer.parseInt(pages) + 1) {

            out.println("<a href=result.jsp?id=" + j + ">" + j
                    + "</a>");

            j++;
        }
    %>
</body>
</html>


csvfile.java
/**
 *
 */
package doa;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author Boomiraj
 *
 */
public class CSVFile {
    public static ArrayList<String> getArrayList(ArrayList list) throws IOException{
        //FileWriter fw = new FileWriter("C:/Users/Boomiraj/Desktop/Boomiraj.csv");
       //fw.close();
       File file = new File("C:/Users/Boomiraj/Desktop/test.csv");
       FileReader fr = new FileReader(file);
       BufferedReader pr =new BufferedReader(fr);
       String dataRow = pr.readLine();
      //System.out.println(dataRow);
      // ArrayList array = new ArrayList();
       if(file.isFile()){
       System.out.println(dataRow);
       while (dataRow != null){
        String[] dataArray = dataRow.split(",");
        for (String item:dataArray) {
            //System.out.println(item);
          // pr.re(item+",");
            list.add(item);
           // System.out.println(list);
        }
       // System.out.println("test"); // Print the data line.
        dataRow = pr.readLine();
       fr.read();
     //  System.out.println(list);
       }}
       return list;
   }
    public static void main(String[] args) throws IOException {
        ArrayList list = new ArrayList();
        new CSVFile().getArrayList(list);
        /*FileWriter fw = new FileWriter("C:/Users/Boomiraj/Desktop/Boomiraj.csv");
           fw.close();*/
         /*  File file = new File("C:/Users/Boomiraj/Desktop/test.csv");
           FileReader fr = new FileReader(file);
           BufferedReader pr =new BufferedReader(fr);
           String dataRow = pr.readLine();
          // System.out.println(dataRow);
          ArrayList array = new ArrayList();
           if(file.isFile()){
           //System.out.println(dataRow);
           while (dataRow != null){
            String[] dataArray = dataRow.split(",");
            for (String item:dataArray) {
                //System.out.println(item);
              // pr.re(item+",");
                array.add(item);
               // System.out.println(array);
            }
           // System.out.println();
            //System.out.println("test"); // Print the data line.
            dataRow = pr.readLine();
           fr.read();
           System.out.println(array);
           }}*/
    }

}



csvservlet.java
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.CSVBean;
import doa.CSVFile;
import doa.CSVFileReadWrite;

/**
 * Servlet implementation class CSVLoginServlet
 */
public class CSVLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CSVLoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        /*PrintWriter out = response.getWriter();
        CSVBean csvBean = new CSVBean();
        csvBean.setFirstName(request.getParameter("firstname"));
        csvBean.setLastName(request.getParameter("lastname"));
        csvBean.setPhoneNumber(request.getParameter("phonenumber"));
       
        CSVFileReadWrite.writeFile(csvBean);
        out.println("Write Finished");
        */
       
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
        CSVFile csv = new CSVFile();
        //csv.getArrayList();
        ArrayList array = new ArrayList();
        HttpSession session = request.getSession(true);
        String pageNo = request.getParameter("id");
        //System.out.println(csv.getArrayList(array));
        if(pageNo==null){
            pageNo="1";
        }
        final int offSet = 2;

        int pageNumber = Integer.parseInt(pageNo);
        if(pageNumber != 0){
        //System.out.println("67"+array.add(csv.getArrayList(array)));
        int numberOfData = array.size();
        //System.out.println(array);
        int totalPages = numberOfData/offSet;
        String noPages = Integer.toString(totalPages);
        System.out.println(noPages + 1);
        int nodata = offSet*pageNumber;

        int fistNo = nodata - offSet;
        //System.out.println("NO Of Data"+nodata);
        //System.out.println("From"+fistNo+"To"+nodata);

        if(nodata>array.size()){
            nodata = array.size();
        }
        ArrayList onlyData = new ArrayList();
        while (fistNo<nodata ){
            //StudentBean student = (StudentBean) arrayList.get(fistNo);
            //System.out.println(student.getName_Strudet());

            array.get(fistNo);
           
            fistNo ++;
        }
        }
        System.out.println("servlet 88"+array);
        session.setAttribute("array", array);
        session.setAttribute("pages", pageNo);
        response.sendRedirect("result.jsp");
    }

}

Tuesday, January 15, 2013

get the arraylist value from servlet to jsp

Servlet:
PrintWriter out = response.getWriter();
        out.println("test");
        BufferedReader buffer = new BufferedReader(new FileReader(new File("C:/Users/boomiraj/Desktop/Boomiraj1.csv")));
        String readline = buffer.readLine();
        ArrayList<String> array = new ArrayList<String>();
       
        while(readline != null){
            String[] read = readline.split(" ");
            //out.println(read);
        array.add(read[0]);
        array.add(read[1]);
        array.add(read[2]);
        //array.add("sekar");
        Iterator<String> i = array.iterator();
        while(i.hasNext()){
            i.next();
        }
        readline = buffer.readLine();
        }
        HttpSession session = request.getSession(true);
        session.setAttribute("test", array);
        RequestDispatcher rd;
        rd = request.getRequestDispatcher("checkout.jsp");
        rd.forward(request,response);
        //response.sendRedirect("");



JSP file checkout.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.util.*"%>
<!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>Insert title here</title>
</head>
<body>
<%
ArrayList<String> array =(ArrayList)session.getAttribute("test");
if(!array.isEmpty()){
    for(int i = 0; i<array.size(); i++){
        %>
        <td><%= array.get(i)%></td>
       
       
<%}%><br>
    <%}%>       
</body>
</html>

Monday, January 7, 2013

date

public static void noOfDaysInMonth(){
       
        System.out.println("Enter the month");
        Scanner scanner = new Scanner(System.in);
        String month = scanner.next();
        System.out.println("Enter the year");
        int year = scanner.nextInt();
        String[] months = {"january","febrary","march","april","may","june","july","aguest","septemper","october","november","december"};
        for(int i = 0; i<months.length;i++){
        if(month.equals(months[i])){
        switch(i){
        case 0:
            System.out.println("no of days 31");
            break;
        case 1:
            System.out.println("no of days 29");
            break;
        case 2:
            System.out.println("no of days 31");
            break;
        case 3:
            System.out.println("no of days 30");
            break;
        case 4:
            System.out.println("no of days 31");
            break;
        case 5:
            System.out.println("no of days 30");
            break;
        case 6:
            System.out.println("no of days 31");
            break;
        case 7:
            System.out.println("no of days 31");
            break;
        case 8:
            System.out.println("no of days 30");
            break;
        case 9:
            System.out.println("no of days 31");
            break;
        case 10:
            System.out.println("no of days 30");
            break;
        case 11:
            System.out.println("no of days 31");
            break;
           
        }
       
        }
        }
       
       
    }
    public static void listOfHolidays(){
        String[] JANUARY = {"New Year","Pongal","Republicday"};
        String[] FEBRARY = {"No Holiday in this month"};
        String[] MARCH = {"No Holiday in this month"};
        String[] APRIL = {"No Holiday in this month"};
        String[] MAY = {"LaboursDay"};
        String[] JUNE = {"No Holiday in this month"};
        String[] JULY = {"No Holiday in this month"};
        String[] AUGEST = {"Independents days"};
        String[] SEPDEMBER = {"Diwali"};
        String[] OCTOBER = {"No Holiday in this month"};
        String[] NOVEMBER = {"Ramjan"};
        String[] DECEMBER = {"Christmas"};
       
        System.out.println("enter the month");
        Scanner scanner = new Scanner(System.in);
        String month = scanner.next();
        if(month.equalsIgnoreCase("JANUARY")){
            for(int i = 0; i<JANUARY.length;i++)
            System.out.println(JANUARY[i]);
           
        }
    }

Tuesday, December 18, 2012

count character for number

/**
 *
 */
package com;

/**
 * @author Boomiraj
 *
 */
public class CountChar {

    /**
     * @param args
     */
    static int count = 0;
    public static void main(String[] args) {
        onecountCharacter();
    }
    public static void onecountCharacter(){
        String[] ones = {"zero","one","two","three","four","five","six","seven","eight","nine"};
        String[] ten = {"ten","eleven","twelve","thriteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
        String[] tens = {"twenty","thirty","fourty","fifty","sixty","seventy","eighty","nighty"};
      
 for(int i = 0; i < 100; i++){
//            Check whether the number is not greater then ten
            if(i<10){
                count = count + ones[i].length();
                System.out.println(ones[i] + " : " + i + " : " + count);
            }
//            Check whether the number is not greater than 9 and less than 20
            if(i>9 && i<20){
                int j = 10;
                j = i - j; //
                count = count + ten[j].length();
                System.out.println(ten[j] + ":" + i + " : " + count);
                j++;
            }
//            Check whether then number is greater then 20
            if(i>19){
                int k = i/10-2;
                int j = i % 10;
               
                if(j == 0){
                    count = count + tens[k].length();
                    System.out.println(tens[k] + " : "  + count);
                } else{
                    count = count + tens[k].length() + ones[j].length();
                    System.out.println(tens[k] + ones[j] + ":" + i + " :" + count);
                   
                }
                   
               
            }
           
        }
        System.out.println(count);
       
    }

}

Saturday, December 15, 2012

print the sentence from paragraph

public static String printSentance(String str) {
        StringBuffer strBuffer = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) != '.' ) {
                strBuffer.append(str.charAt(i));

            } else {
                System.out.println(strBuffer);
                strBuffer = new StringBuffer();
            }
        }
        return strBuffer.toString();
    }

count number of sentence in paragraph(sentence end with '.' or '?')

public static int countNoOfSentance(String str){
        StringBuffer strBuffer = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) != '.' && str.charAt(i) != '?') {
                strBuffer.append(str.charAt(i));

            } else {
                ++count;
                strBuffer = new StringBuffer();
            }
        }
        count++;
        System.out.println(count);
        return count;
    }


split the sentance when capital letter occur

//split the sentence manually 

public static String getSplit(String str){
        char[] str_1 = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        StringBuffer sbuffer = new StringBuffer();
        for(int i = 0; i<str.length();i++){
            for(int j = 0; j<str_1.length; j++){
               
                if(str.charAt(i) == str_1[j]){
                    sbuffer.append(" ");
                }
            }
            sbuffer.append(str.charAt(i));
        }
        return sbuffer;
    }

//split the sentence using API method
public static String getSplitByMethod(String str){
        StringBuffer sbuffer = new StringBuffer();
        for(int i = 0;i<str.length();i++){
            if(Character.isUpperCase(str.charAt(i))){
                sbuffer.append(" ").append(str.charAt(i));
            }else{
                sbuffer.append(str.charAt(i));
            }
        }
        return sbuffer.toString();
    }

Thursday, December 13, 2012

sendRedirect() vs include() vs forward()

sendRedirect(myUrl1) : you are sending back a response to the client and asking the browser to make a new request with the provided url, here myUrl1

include() : Say in servletA you call include(/path/to/myView.jsp) : you are asking the web container to include in the response of servletA the response of myView.jsp.
ServletA is in control, I mean responsible for generating the response to the client and you just include as well the response of another web component (e.g jsp)

forward() : say in servletA you call forward(path/to/myView.jsp): here servletA passes the control to myView.jsp to generated the response to the client. The client will see only the content from myView.jsp nothing from servletA. 


Original source from coderanch 

Application server vs Web server

Application Server:
          •  It provide the software application with services
          •  It serve both http protocol and RMI protocol
          • Most of the application server have web server as internal part of them. So application server can do all the web server work.
          • Application server used dynamic content.

Web Server :
          •  It used to response the http request
          • It serve only with http protocol
          • Web server used static content 

    • Examples of WebServer:
              • Apache HTTP Server is Web Server

Thursday, December 6, 2012

getter and setter method for username password

/**
 *
 */
package dao;

/**
 * @author Boomiraj
 *
 */
public class LoginBean {
   
    private String username;
    private String password;
    private String firstname;
    private String lastname;
    private boolean valid;
    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }
    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }
    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }
    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }
    /**
     * @return the firstname
     */
    public String getFirstname() {
        return firstname;
    }
    /**
     * @param firstname the firstname to set
     */
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    /**
     * @return the lastname
     */
    public String getLastname() {
        return lastname;
    }
    /**
     * @param lastname the lastname to set
     */
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    /**
     * @return the valid
     */
    public boolean isValid() {
        return valid;
    }
    /**
     * @param valid the valid to set
     */
    public void setValid(boolean valid) {
        this.valid = valid;
    }

}

Valid username and password

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="dao.LoginBean"%>
<!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>Insert title here</title>
</head>
<body>
    <center>
    <% LoginBean lb =  (LoginBean)session.getAttribute("currentSessionUser"); %>
    Welcome :<%= lb.getFirstname() %>
    FirstName :<%= lb.getFirstname() %>
    LastName  :<%= lb.getLastname() %>
    Password  :<%= lb.getPassword() %>
    </center>
</body>
</html>

Invalid usename password message using jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
 <center> Sorry, you are not a registered user! Please sign up first </center>
</body>
</html>