Friday, June 30, 2017

How to Compare Two Objects with the equals Method in Java? What is the differents between == and equals()?

Difference between == and equals() in java.

  •  == check object reference are same or not.It check only the objects are same, not equality of object.
  • equals() check reference values are same are not.Its checks the equality of the object fields. If you want to check the object equality we need to override the equals(). 
Example:

    //Value stored in String Pool
   String l_sValue = "Equals";

    //Reference stored in heap memory.
    String l_sSecValue = new String("Equals");

   //Both objects having same value. The values are equals.So its returns true.
    if(l.equals(k)) Output: return true;

   //Both are addressing different object, returns false.
    if((l == k)) Output: return false;

/**
 * @author palrajb
 *
 */
public class Test {

    private String name;
    private int age;
    private int marks;

    public Test() {
    }

    public Test(String name, int age, int marks) {
        this.name = name;
        this.age = age;
        this.marks = marks;
    }

    public void setMarks(int marks) {
        this.marks = marks;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {


        Test t = new Test("1", 1, 1);// Create the object t with three parameter constructor.

        Test t1 = (Test) t;
// Addressing same reference.

        t1.setMarks(2);
// Changes on t1 directly affect t. Because t1 is addressing t reference.                      
// Here t and new object having same values, but we are not override the equals() to equals the fields of Test class. So passing reference are different. 

       System.out.println(t.equals(new Test("1", 1, 1)));Output : false
// Here we are t and t1 are addressing single object t.So their address  and fields are same, returns  true.
      System.out.println(t.equals(t1)); Output : true
// Here we are t and t1 are addressing single object t. As per state check only the objects are same, return true.
      System.out.println(t == t1);Output : true


} 

if you want to make t.equals(new Test("1",1,1)) true, we need to override the equals()

@Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Test other = (Test) obj;
        if (age != other.age)
//Here checking the age of t and new Test("1",1,1) object age is not same.
            return false;
        if (name == null) {
//Null check for name, because we have setter method for name variable.
            if (other.name != null)
//Same null check for new Test("1",1,1).
                return false;
        } else if (!name.equals(other.name))
//Here checking the name of t and new Test("1",1,1) object name is not same.
            return false;
        return true;
    }


After the equals() implementation, now execute the

System.out.println(t.equals(new Test("1", 1, 1)));//Output: true. Because we customized the equals method as we want. We just compare the age and name variable only, we are not consider the marks variable for equals() implementation so changes the value by using
t1.setMarks(2); not affect anything on the equality.


Meanwhile we know that if we override the equals() then we need to override hashCode().

@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }


Do you feel we would missed any variable in equals() and hashCode().
    Yes, the marks variable is missing. Key to override the equals() and hashCode() is the filed used in equals() must be used hashCode implementation.





Thursday, June 29, 2017

Java is pass-by-value or pass-by-reference?

Java is strictly pass-by-value. 

Then the next question is how it is pass-by-value ?
   
 Here the explanation from SCJP.


"Java is actually pass-by-value for all variables running within a single VM. Pass-by-value means pass-by-variable-value. And that means, pass-by-copy-ofthe-variable,which means pass-by-copy-of-the-bits-in-the-variable"


Here we have example for passing variable and passing reference.


package com.test.java;

/**
 * @author palrajb
 *
 */
public class Test {

    private String name;
    private int age;
    private int marks;

    public Test() {
    }

    public Test(String name, int age, int marks) {
        this.name = name;
        this.age = age;
        this.marks = marks;
    }

    public void setMarks(int marks) {
        this.marks = marks;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        Test l_objTest = new Test("A", 1, 12);
        int l_iIntValue = 1;
        System.out.println("Mark Before invoke : " + l_objTest.marks + " IntValue :" + l_iIntValue);
      
  //Output:Mark Before invoke : 12 IntValue :1
        doTest(l_objTest, l_iIntValue);
//Here we are passing reference and variable as parameter.
        System.out.println("Mark After invoke : " + l_objTest.marks    + " IntValue :" + l_iIntValue);
       
//Output:Mark After invoke : 14 IntValue :1
    }





Here we got the copy of calling method reference variable. We change the p_iIntValue +1, but the called method can't change the caller's variable.So when we print this from main method its still 1. For p_objTest.setMarks(14) will change the caller l_objTest object marks to 14,because the called method can change the object the variable referred.

     static void doTest(Test p_objTest, int p_iIntValue)
    {
        p_iIntValue = p_iIntValue + 1;
//Using same reference but in different address.So increment happens only on newly created address not on old one.The called method can't change the caller's variable
        p_objTest.setMarks(14);
//called method can change the object the variable referred.
        p_objTest = new Test("B", 2, 13);
//we using same reference but in different address. So the caller reference not going to change anyway.
        p_objTest.setMarks(15);//
change the mark value in newly referenced object.
    }

}

Tuesday, June 27, 2017

What happen when you are not print or throw the exception in catch block?

try block-- Here the actual logic and implementation. 
catch block--If try block may have come error in the logic or implementation we can catch the error.Here we can catch the try block error.Catching error is just do print the stack trace of the what error is occurred.

Now consider we are trying below condition, its just do create exception in try block,do not bother about implementation in try block.

package com.test.java;

import java.util.Scanner;

/**
 * @author boomiraj
 *
 */
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner l_objInput = new Scanner(System.in);
        System.out.println("Please Enter the value : ");
        convertStringToInt(l_objInput.next());
    }

    private static void convertStringToInt(String p_sValue) {
        int i = 0;
        try {

            i = Integer.parseInt(p_sValue);
            if (i < 100) {
                i = i + 1;
            } else {
                i = i - 1;
            }

        } catch (NumberFormatException e) {
         }
        System.out.println("Converted into interger from string : " + i);
    }

}


In public method we are calling convertStringToInt(String) to convert given String Value to Int.
   
    We are getting input from user, so user can enter any possible combination of input like
    Alphabet
    Alphanumeric
    Number
    Special character
   
    If user enters only Number, its not problem we can get the output without error.
    But if he tries any other combination then there is possibility to have an error.
    In this scenario we are catch the exception, but in the catch block we don't have any print stack trace or print log.
    then the user does not know that the entered values are not able to convert into Int. But he always get some output.

    This may cause the some blocker issue in your project.

  catch (NumberFormatException e) {
            System.err.println("Cannot convert the value '" + p_sValue
                    + "' to integer");
        }


So always print something into your catch block.

Monday, June 19, 2017

Change the execution value by the time of debug in eclipse.

If you want to change the value of the primitive instance we can change by using variables tab.
or else we can change the value by using "Display" window.

In Variable tab we can see the all the object and instance of the current thread.
Press (Cntl+f) and type the variable name you want to change the value.
Then click on the right side of the variable and change the value.
Note : By this way we can only change the value of primitive data type. We cannot change the object reference.


In Display window you can write the value to be change and select the line and press (ctrl+u).
If I have the String l_sValue = "World"; if i want to change the String l_sValue = "Change the World";
l_sValue = "Change the World"; copy this line and press (ctrl+u)
Note : By this we can do change both primitive and object reference.

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