Read XML Taglib and JSTL in JSP


samle.xml

 <?xml version="1.0" encoding="ISO-8859-1"?>
 <weather ver="2.0">
   <loc id="INXX0096">
     <dnam>New Delhi, India </dnam>
     <tm>3:30 PM </tm>
   </loc>
   <cc>
     <tmp>75 </tmp>
     <bar>
       <r>29.94 </r>
       <d>steady </d>
     </bar>
   </cc>
 </weather>

--------------------------------
xml_read.jsp

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<c:import url="http://localhost:8080/XML/samle.xml" var="xml"/>
<x:parse xml="${xml}" varDom="dom"/>
<html>
<head>
<title>Read XML through taglib JSTL</title>
</head>

<body>
      <x:forEach select="$dom/weather/cc/tmp" var="tmp">
        <x:out select="$tmp" />
    </x:forEach>

    <br>

    <x:forEach select="$dom/weather/cc/bar/d" var="d">
        <x:out select="$d" />
    </x:forEach>
</body>
</html>
READ MORE - Read XML Taglib and JSTL in JSP

How to read XML file in java



books.xml

<?xml version="1.0" encoding="iso-8859-1"?>
<library>
 <book>
   <name>Head First Java, 2nd Edition</name>
   <author>Kathy Sierra and Bert Bates</author>
   <publication-date>09-Feb-2005</publication-date>
 </book>
 <book>
   <name>Effective Java</name>
   <author>Joshua Bloch</author>
   <publication-date>28-May-2008</publication-date>
 </book>
 <book>
   <name>Java How to Program, 7th Edition</name>
   <author>Harvey M. Deitel and Paul J. Deitel</author>
   <publication-date>6-Jan-2007</publication-date>
 </book>
</library>

------------------------------------------------------------
readDOMXML.jsp

<%@ page language="java" %>
<%@ page import="org.w3c.dom.*" %>
<%@ page import="javax.xml.parsers.DocumentBuilder" %>
<%@ page import="javax.xml.parsers.DocumentBuilderFactory" %>
<%
    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
    DocumentBuilder db =dbf.newDocumentBuilder();
    Document doc=db.parse("c:\\books.xml");
   
   
    NodeList nl = doc.getElementsByTagName("book");
   
%>
<html>
<head>
<title>How to read XML file in JAVA</title>
</head>
<body>
<%

for(int i=0;i<nl.getLength();i++)
{
  NodeList nameNlc=    doc.getElementsByTagName("name");
  Element nameElements=(Element)nameNlc.item(i);
  String nameTagValue=nameElements.getChildNodes().item(0).getNodeValue();
 
 
  NodeList authorNlc=    doc.getElementsByTagName("author");
  Element authorElements=(Element)authorNlc.item(i);
  String authorTagValue=authorElements.getChildNodes().item(0).getNodeValue();
 
  NodeList dateNlc=    doc.getElementsByTagName("publication-date");
  Element dateElements=(Element)dateNlc.item(i);
  String dateTagValue=dateElements.getChildNodes().item(0).getNodeValue();
 
  out.println("name :"+nameTagValue+"<br>");  
  out.println("author :"+authorTagValue+"<br>");  
  out.println("publication-date :"+dateTagValue+"<br><br>");  
}

%>

</body>
</html>
READ MORE - How to read XML file in java

getElementsByTagName in javascript


<html>
<head>
<title>getElementsByTagName Javascript</title>
<script>
function getElementFtn()
{
 alert(document.getElementsByTagName("p").item(0).innerHTML)
}
</script>
</head>

<body>
<p>this is first tag</p>

<p>this is second</p>

<p id="pID">this is third tag</p>

<p>this is forth tag</p>

<p>this is fifth tag</p>

<a href="javascript:getElementFtn()">check this element</a>
</body>
</html>
READ MORE - getElementsByTagName in javascript

Form parameter validation using javascript(username,password,email,number,alphanumeric))



UserName Password validation

<html>
<head>
<title>Required Validation</title>
<script>
function validate()
{
  var vUser=trim(document.frm.sUser.value);
  var vPwd=trim(document.frm.sPwd.value);

  if(vUser=="")
  {
    alert("User Name Field is Empty");
    document.frm.sUser.focus();
    return false;
  }
  else if(vPwd=="")
  {
   alert("Password Field is Empty");
   document.frm.sPwd.focus();
   return false;
  }
}

function trim(s) {
    return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}

</script>
</head>

<body>
<form name="frm" onSubmit="return validate();">
User Name <input type="text" name="sUser" /><br>
Password <input type="password" name="sPwd" /><br>
<input type="submit" name="goTo" value="Submit"/>
</form>
</body>
</html>


----------------------------------------------------------------
Number or Integer Validation

<html>
<head>
<title>Number Integer Validation</title>
<script>

function validate()
{
  var dValidate=document.frm.numberValidate.value;
  if(dValidate=="")
  {
    alert("Number Field is empty")
    return false;
  }
  else if(isDigits(dValidate)==false)
  {
   alert("Field is not numeric")
   return false;
  }
}

function isDigits(argvalue) {
    argvalue = argvalue.toString();
    var validChars = "0123456789";
    var startFrom = 0;
    if (argvalue.substring(0, 2) == "0x") {
       validChars = "0123456789abcdefABCDEF";
       startFrom = 2;
    } else if (argvalue.charAt(0) == "0") {
       validChars = "01234567";
       startFrom = 1;
    }
    for (var n = 0; n < argvalue.length; n++) {
        if (validChars.indexOf(argvalue.substring(n, n+1)) == -1) return false;
    }
  return true;
}
</script>
</head>

<body>
<form name="frm" onSubmit="return validate();">
Number <input type="text" name="numberValidate" />
<input type="submit" name="goTo" value="Number Validate" />
</form>
</body>
</html>


------------------------------------------------------------------
Date Validation

<html>
<head>
<title>Date Validation</title>
<script>
function validate()
{
  var dValidate=document.frm.dateValidate.value;
  if(dValidate!="")
  {
    var arDValidate=dValidate.split("/");
    if(arDValidate.length==3)
    {
      if(arDValidate[0].length!=2 || (arDValidate[0]>32))
      {
         alert("Wrong Date format");
         return false;
      }
      else if(arDValidate[1].length!=2 || (arDValidate[1]>13))
      {
         alert("Wrong Month format");
         return false;
      }
      else if(arDValidate[2].length!=4 || (arDValidate[2]<1900))
      {
         alert("Wrong Year format");
         return false;
      }
      else
      {
        var dateDate=new Date(arDValidate[2],arDValidate[1]-1,arDValidate[0]);
        if((arDValidate[0]!=dateDate.getDate()))
        {
          alert("Wrong Date Enter e.g date month year is not correct 31 feb 2009");
          return false;
        }
      }
    }
    else
    {
    alert("Wrong Format");
    return false;
    }
  }
  else
  {
   alert("Date is blank");
   return false;
  }
}

</script>
</head>

<body>
<form name="frm" onSubmit="return validate();">
mm/dd/yyyy <input type="text" name="dateValidate" />
<input type="submit" name="goTo" value="Date Validate" />
</form>
</body>
</html>


-------------------------------------------------------------------
Email Validation

<html>
<head>
<title>Email Validation</title>
<script>
function validate()
{
  var dValidate=document.frm.emailValidate.value;
  if(dValidate=="")
  {
    alert("Email Field is empty")
    return false;
  }
  else if(checkEmail(dValidate)==false)
  {
   alert("Email Format is not correct")
   return false;
  }
}

function checkEmail(emailStr) {
       if (emailStr.length == 0) {
           return true;
       }
       var emailPat=/^(.+)@(.+)$/;
       var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
       var validChars="\[^\\s" + specialChars + "\]";
       var quotedUser="(\"[^\"]*\")";
       var ipDomainPat=/^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/;
       var atom=validChars + "+";
       var word="(" + atom + "|" + quotedUser + ")";
       var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
       var domainPat=new RegExp("^" + atom + "(\\." + atom + ")*$");
       var matchArray=emailStr.match(emailPat);
       if (matchArray == null) {
           return false;
       }
       var user=matchArray[1];
       var domain=matchArray[2];
       if (user.match(userPat) == null) {
           return false;
       }
       var IPArray = domain.match(ipDomainPat);
       if (IPArray != null) {
           for (var i = 1; i <= 4; i++) {
              if (IPArray[i] > 255) {
                 return false;
              }
           }
           return true;
       }
       var domainArray=domain.match(domainPat);
       if (domainArray == null) {
           return false;
       }
       var atomPat=new RegExp(atom,"g");
       var domArr=domain.match(atomPat);
       var len=domArr.length;
       if ((domArr[domArr.length-1].length < 2) ||
           (domArr[domArr.length-1].length > 3)) {
           return false;
       }
       if (len < 2) {
           return false;
       }
       return true;
}
</script>
</head>

<body>
<form name="frm" onSubmit="return validate();">
Email <input type="text" name="emailValidate" />
<input type="submit" name="goTo" value="Email Validate" />
</form>
</body>
</html>

------------------------------------------------------------------
Alpha Character Validation

<html>
<head>
<title>Alpha number Validation</title>
<script>

function validate()
{
  var dValidate=document.frm.alphaValidate.value;
  if(dValidate=="")
  {
    alert("Alpha Field is empty")
    return false;
  }
  else if(isAlpha(dValidate)==false)
  {
   alert("Field is not alpha character")
   return false;
  }
}

function isAlpha(argvalue) {
  argvalue = argvalue.toString();
  var validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    for (var n = 0; n < argvalue.length; n++) {
        if (validChars.indexOf(argvalue.substring(n, n+1)) == -1)
         return false;
    }
  return true;
}
</script>
</head>

<body>
<form name="frm" onSubmit="return validate();">
Alpha Character <input type="text" name="alphaValidate" />
<input type="submit" name="goTo" value="Alpha Validate" />
</form>

</body>
</html>

READ MORE - Form parameter validation using javascript(username,password,email,number,alphanumeric))

Enable Disable Radio button Text box in JavaScript


<html>
<head>
<title>Enable Disable Radio button Text box in javascript</title>
</head>
<script>
 function chMd()
 {
  // initialize form with empty field
  document.forms[0].sTextBox.disabled=false;
  document.forms[0].sTextBox.value="";

  document.forms[0].eTextBox.disabled=false;
  document.forms[0].eTextBox.value="";

  document.forms[0].goServer.disabled=false;

  for(var i=0;i<document.forms[0].elements.length;i++)
  {
    if(document.forms[0].elements[i].name=="dOption")
    {
     if(document.forms[0].elements[i].value=="N")
     {
       if(document.forms[0].elements[i].checked==true){

        document.forms[0].sTextBox.disabled=true;
        document.forms[0].eTextBox.disabled=true;

        document.forms[0].sRadio[0].disabled=true;
        document.forms[0].sRadio[1].disabled=true;
        document.forms[0].sRadio[2].disabled=true;

        document.forms[0].goServer.disabled=true;
       }
     }
     else if(document.forms[0].elements[i].value=="T")
     {
       if(document.forms[0].elements[i].checked==true){
        document.forms[0].sTextBox.disabled=false;
        document.forms[0].eTextBox.disabled=false;

        document.forms[0].sRadio[0].disabled=true;
        document.forms[0].sRadio[1].disabled=true;
        document.forms[0].sRadio[2].disabled=true;

        document.forms[0].goServer.disabled=false;
       }
     }
     else if(document.forms[0].elements[i].value=="R")
     {
       if(document.forms[0].elements[i].checked==true){
        document.forms[0].sTextBox.disabled=true;
        document.forms[0].eTextBox.disabled=true;

        document.forms[0].sRadio[0].disabled=false;
        document.forms[0].sRadio[1].disabled=false;
        document.forms[0].sRadio[2].disabled=false;

        document.forms[0].goServer.disabled=false;
       }
     }
    }
  }
 }
</script>

<body>
<form name="fRadio">
  <input name="dOption" value="N" checked="checked" onClick="chMd()" type="radio">
   No Constraints <br />

    <input name="dOption" value="T" onClick="chMd()" type="radio"> Text Box

    <input name="sTextBox" size="10"  disabled="disabled" type="text">
    <input name="eTextBox" size="10"  disabled="disabled" type="text"> <br/>

    <input name="dOption" value="R" onClick="chMd()" type="radio">  Radio Button
    Radio A  <input name="sRadio" value="A" disabled="disabled" type="radio">
    Radio B  <input name="sRadio" value="B" disabled="disabled" type="radio">
    Radio C  <input name="sRadio" value="C" disabled="disabled" type="radio"> <br/>
  <input name="goServer" value="Go" disabled="disabled" type="button">
  </form>
</body>
</html>
READ MORE - Enable Disable Radio button Text box in JavaScript

Selecting all checkboxes using javascript


<html>
<head>
<title>JavaScript - Select All checkbox in form</title>
<script>
var fieldName='chkName';

function selectall(){
  var i=document.frm.elements.length;
  var e=document.frm.elements;
  var name=new Array();
  var value=new Array();
  var j=0;
  for(var k=0;k<i;k++)
  {
    if(document.frm.elements[k].name==fieldName)
    {
      if(document.frm.elements[k].checked==true){
        value[j]=document.frm.elements[k].value;
        j++;
      }
    }
  }
  checkSelect();
}
function selectCheck(obj)
{
 var i=document.frm.elements.length;
  for(var k=0;k<i;k++)
  {
    if(document.frm.elements[k].name==fieldName)
    {
      document.frm.elements[k].checked=obj;
    }
  }
  selectall();
}

function selectallMe()
{
  if(document.frm.allCheck.checked==true)
  {
   selectCheck(true);
  }
  else
  {
    selectCheck(false);
  }
}
function checkSelect()
{
 var i=document.frm.elements.length;
 var berror=true;
  for(var k=0;k<i;k++)
  {
    if(document.frm.elements[k].name==fieldName)
    {
      if(document.frm.elements[k].checked==false)
      {
        berror=false;
        break;
      }
    }
  }
  if(berror==false)
  {
    document.frm.allCheck.checked=false;
  }
  else
  {
    document.frm.allCheck.checked=true;
  }
}
</script>
</head>

<body>
<form name="frm">
select all :<input type="checkbox" name="allCheck" onClick="selectallMe()">
<hr><br>
1  :<input type="checkbox" name="chkName" onClick="selectall()"><br>
2  :<input type="checkbox" name="chkName" onClick="selectall()"><br>
3  :<input type="checkbox" name="chkName" onClick="selectall()"><br>
4  :<input type="checkbox" name="chkName" onClick="selectall()"><br>
5  :<input type="checkbox" name="chkName" onClick="selectall()"><br>
6  :<input type="checkbox" name="chkName" onClick="selectall()"><br>
7  :<input type="checkbox" name="chkName" onClick="selectall()"><br>
8  :<input type="checkbox" name="chkName" onClick="selectall()"><br>
9  :<input type="checkbox" name="chkName" onClick="selectall()"><br>
10 :<input type="checkbox" name="chkName" onClick="selectall()"><br>
</form>
</body>
</html>
READ MORE - Selecting all checkboxes using javascript

Get Checkbox Value using javascript


<html>
<head>
<title>JavaScript select checkbox</title>
<script>
function selectCheckBox()
{
  var e= document.frm.elements.length;
  var cnt=0;

  for(cnt=0;cnt<e;cnt++)
  {
    if(document.frm.elements[cnt].name=="id"){
     alert(document.frm.elements[cnt].value)
    }
  }
}
</script>
</head>

<body>
<form name="frm">
<input type="checkbox" name="id" value="1">
<input type="checkbox" name="id" value="2">
<input type="checkbox" name="id" value="3">
<input type="checkbox" name="id" value="4">
<input type="checkbox" name="id" value="5">
<input type="button" name="goto" onClick="selectCheckBox()" value="Check">
</form>
</body>
</html>

The example is showing how to get value from separate name checkbox in JavaScript.

<html>
<head>
<title>JavaScript select checkbox</title>
<script>
function selectCheckBox()
{
     alert(document.frm.id1.value)
     alert(document.frm.id2.value)
     alert(document.frm.id3.value)
}
</script>
</head>

<body>
<form name="frm">
<input type="checkbox" name="id1" value="1">
<input type="checkbox" name="id2" value="2">
<input type="checkbox" name="id3" value="3">

<input type="button" name="goto" onClick="selectCheckBox()" value="Check">
</form>
</body>
</html>
READ MORE - Get Checkbox Value using javascript

More than one form in HTML page


<html>
<head>
<title>Use more than one form in html page</title>
</head>

<body>
<form name="frm1" action="actionPage1.jsp">

<input type="text" name="txtName">
<input type="submit" name="goSubmit" value="Submit">

</form>

<form name="frm2" action="actionPage2.jsp">

<input type="text" name="txtName">
<input type="submit" name="goSubmit" value="Submit">

</form>

<form name="frm3" action="actionPage3.jsp">

<input type="text" name="txtName">
<input type="submit" name="goSubmit" value="Submit">

</form>
</body>
</html>
READ MORE - More than one form in HTML page

Confirm function in Javascript


<html>
<head>
<title>Confirm javascript</title>
<script>
    function validate()
    {
      var confirmMessage="Are you sure to move Yahoo home page!";

      if(confirm(confirmMessage)==false)
      {
          return false;
      }
    }
</script>
</head>

<body>
    <form name="frm" action="http://yahoo.com" onSubmit="return validate()">
       <input type="submit" name="goSubmit" value="Submit" />
    </form>
</body>
</html>
READ MORE - Confirm function in Javascript

Calling href using JavaScript


<html>
<head>
<title>Calling JavaScript Href</title>
<script>
function callHref()
{
  alert("Function is called from Href");
}
</script>
</head>

<body>
<a href="javascript:callHref()">Calling JavaScript Href </a>
</body>
</html>
READ MORE - Calling href using JavaScript

How to Submit a Form Using JavaScript


<html>
<head>
<title>Submit form using javascript</title>
<script>
function goSubmit()
{
  document.frm.submit();
}
</script>
</head>

<body>
<form name="frm">
 <a href="javascript:goSubmit()">Submit form </a>
 <br>
 <input type="button" name="btn" value="Submit" onClick="goSubmit()">
</form>
</body>
</html>
READ MORE - How to Submit a Form Using JavaScript

How to get day month year in date


import java.util.Calendar;

public class GetDate {
    public static void main(String[] args) {

        Calendar ca1 = Calendar.getInstance();

        /// get day month year from set date
        ca1.set(2009, 05, 15); // dont set this date if current date is required

        int iDay=ca1.get(Calendar.DATE);
        int iMonth=ca1.get(Calendar.MONTH); // In Current date Add 1 in month
        int iYear=ca1.get(Calendar.YEAR);

        System.out.println("Day :"+iDay);
        System.out.println("Month :"+iMonth);
        System.out.println("Year :"+iYear);
    }
}
READ MORE - How to get day month year in date

How to find Week of Year


import java.util.Calendar;

public class WeekOfYear {

    public static void main(String[] args) {

        Calendar ca1 = Calendar.getInstance();

        /*
        set(int year, int month, int date)
        Jan=0,Feb=1,Mar=2...
        */
        ca1.set(2009,4,22);

        int WEEK_OF_YEAR=ca1.get(Calendar.WEEK_OF_YEAR);

        System.out.println("WEEK OF YEAR :"+WEEK_OF_YEAR);
    }
}
READ MORE - How to find Week of Year

How to get Day of Week in Month


import java.util.Calendar;

public class DayOfWeekInMonth {

    public static void main(String[] args) {

        Calendar ca1 = Calendar.getInstance();

        ca1.set(2009, 6, 22);

        int DAY_OF_WEEK_IN_MONTH=ca1.get(Calendar.DAY_OF_WEEK_IN_MONTH);

        // More Calendar Date option can check
        /*
        int DAY_OF_MONTH=ca1.get(Calendar.DAY_OF_MONTH);
        int DAY_OF_WEEK=ca1.get(Calendar.DAY_OF_WEEK);
        int DAY_OF_YEAR=ca1.get(Calendar.DAY_OF_YEAR);
        int WEEK_OF_MONTH=ca1.get(Calendar.WEEK_OF_MONTH);
        int WEEK_OF_YEAR=ca1.get(Calendar.WEEK_OF_YEAR);
         */

        System.out.println("DAY OF WEEK IN MONTH :"+DAY_OF_WEEK_IN_MONTH);
    }
}
READ MORE - How to get Day of Week in Month

How to Add or Subtract Date


import java.util.Calendar;

public class AddDate {

    public static void main(String[] args) {

    Calendar ca1 = Calendar.getInstance();
    ca1.set(2009,05,25);

    // Addition of date in java        
    ca1.add(Calendar.DATE, 23); // Add 23 days in Dates in Calendar
    //ca1.add(Calendar.MONTH, 2); // Add 2 Month in Date in Calendar
    //ca1.add(Calendar.YEAR, 4); // Add 4 Year in Date in Calendar

    /*
     *  Subtracting Date in Calendar
     *  
     *  ca1.add(Calendar.DATE, -23); // Subtracting 23 days from date
     *  //ca1.add(Calendar.MONTH, -2); // Subtracting 2 Month in Date in Calendar
     *  //ca1.add(Calendar.YEAR, -4); // Subtracting 4 Year in Date in Calendar
     */

    System.out.println("Date :"+ca1.get(Calendar.DATE));
    System.out.println("Month :"+ca1.get(Calendar.MONTH));
    System.out.println("Year :"+ca1.get(Calendar.YEAR));
    }
}
READ MORE - How to Add or Subtract Date

find Week of Month in java


import java.util.Calendar;

public class WeekOfMonth {

    public static void main(String[] args) {
        Calendar ca1 = Calendar.getInstance();

        /*
        set(int year, int month, int date)
        Jan=0,Feb=1,Mar=2...
        */
        ca1.set(2009,4,22);

        int WEEK_OF_MONTH=ca1.get(Calendar.WEEK_OF_MONTH);
        System.out.println("Week of Month :"+WEEK_OF_MONTH);

        // More Calendar Date option can check
        /*
        int DAY_OF_MONTH=ca1.get(Calendar.DAY_OF_MONTH);
        int DAY_OF_WEEK=ca1.get(Calendar.DAY_OF_WEEK);
        int DAY_OF_YEAR=ca1.get(Calendar.DAY_OF_YEAR);
        int WEEK_OF_YEAR=ca1.get(Calendar.WEEK_OF_YEAR);
        */
    }
}
READ MORE - find Week of Month in java

find Day of Year in Java


import java.util.Calendar;

public class DayOfYear {

    public static void main(String[] args) {
        Calendar ca1 = Calendar.getInstance();

        /*
        set(int year, int month, int date)
        Jan=0,Feb=1,Mar=2...
        */
        ca1.set(2009,4,22);

        /*
        2 Feb 2009, Day of Year, Jan 31 + 2 Feb =33 day of year
        */

        int DAY_OF_YEAR=ca1.get(Calendar.DAY_OF_YEAR);
        System.out.println("Day of Year :"+DAY_OF_YEAR);

        // More Calendar Date option can check
        /*
        int DAY_OF_MONTH=ca1.get(Calendar.DAY_OF_MONTH);
        int DAY_OF_WEEK=ca1.get(Calendar.DAY_OF_WEEK);
        int WEEK_OF_MONTH=ca1.get(Calendar.WEEK_OF_MONTH);
        int WEEK_OF_YEAR=ca1.get(Calendar.WEEK_OF_YEAR);
         */
    }
}
READ MORE - find Day of Year in Java

How to Create file in Java


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

public class JavaIOWriteFileExample {

    public static void main(String[] args) {

        File f=new File("c:\\createNewfile.txt");

        try{
            FileWriter fstreamCopy = new FileWriter(f);
            BufferedWriter outobjCopy = new BufferedWriter(fstreamCopy);
            outobjCopy.write("The content write to inside the file");
            outobjCopy.close();
         }
        catch (Exception e){
              e.printStackTrace();
         }
    }
}
READ MORE - How to Create file in Java

SortedSet Example


import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

public class SortedSetExample {

    public static void main(String[] args) {

        SortedSet<String> ss=new TreeSet<String>();

        ss.add("a");
        ss.add("e");
        ss.add("g");
        ss.add("b");
        ss.add("c");

        Iterator it=ss.iterator();

        while(it.hasNext())
        {
          String value=(String)it.next();

          System.out.println("Value :"+value);
        }
    }
}
READ MORE - SortedSet Example

Remove elements from SortedMap


import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class SortedMapRemoveExample {

    public static void main(String[] args) {

        SortedMap<Integer,String> sm=new TreeMap<Integer, String>();

        sm.put(new Integer(2), "Two");
        sm.put(new Integer(1), "One");
        sm.put(new Integer(4), "Four");
        sm.put(new Integer(3), "Three");
        sm.put(new Integer(5), "Five");

        // SortedMap remove object
        sm.remove(new Integer(4));

        Set s=sm.entrySet();

        Iterator i=s.iterator();

        while(i.hasNext())
        {
            Map.Entry m =(Map.Entry)i.next();

            int key = (Integer)m.getKey();
            String value=(String)m.getValue();

            System.out.println("Key :"+key+"  value :"+value);
        }
    }
}
READ MORE - Remove elements from SortedMap

Remove elements from SortedSet


import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

public class SortedSetRemoveExample {

    public static void main(String[] args) {

        SortedSet<String> ss=new TreeSet<String>();

        ss.add("a");
        ss.add("e");
        ss.add("g");
        ss.add("b");
        ss.add("c");

        // remove SortedSet object
        ss.remove("g");

        Iterator it=ss.iterator();

        while(it.hasNext())
        {
          String value=(String)it.next();

          System.out.println("Value :"+value);
        }
    }
}
READ MORE - Remove elements from SortedSet

Remove elements from Set


import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class SetRemoveExample {

    public static void main(String[] args) {

        Set<String> s=new TreeSet<String>();

        s.add("b");
        s.add("a");
        s.add("d");
        s.add("c");

        // Set remove object
        s.remove("d");

        Iterator it=s.iterator();

        while(it.hasNext())
        {
          String value=(String)it.next();

          System.out.println("Value :"+value);
        }
    }
}
READ MORE - Remove elements from Set

Remove elements from Map


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapRemoveExample {

    public static void main(String[] args) {

        Map<Object,String> mp=new HashMap<Object, String>();

        mp.put(new Integer(2), "Two");
        mp.put(new Integer(1), "One");
        mp.put(new Integer(3), "Three");
        mp.put(new Integer(4), "Four");

        // remove map object
        mp.remove(new Integer(3)); // remove map by object

        Set s=mp.entrySet();

        Iterator it=s.iterator();

        while(it.hasNext())
        {
            Map.Entry m =(Map.Entry)it.next();

            int key=(Integer)m.getKey();

            String value=(String)m.getValue();

            System.out.println("Key :"+key+"  Value :"+value);
        }
    }
}
READ MORE - Remove elements from Map

Remove Element from ArrayList


import java.util.ArrayList;

public class RemoveArrayListElement {

    public static void main(String[] args) {

        ArrayList<String> arlist=new ArrayList<String>();

        //<E> it is return type of ArrayList

        arlist.add("First Element"); // adding element in ArrayList
        arlist.add("Second Element");
        arlist.add("Third Element");
        arlist.add("forth Element");
        arlist.add("fifth Element");

        // remove array list element by index number
        arlist.remove(3);

        // remove ArrayList element by Object value
        arlist.remove("fifth Element");

        // get elements of ArrayList
        for(int i=0;i<arlist.size();i++)
        {
            System.out.println("ArrayList Element "+i+" :"+arlist.get(i));
        }
    }
}
READ MORE - Remove Element from ArrayList

Remove elements from List


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListRemoveExample {

    public static void main(String[] args) {

        List<String> ls=new ArrayList<String>();

        ls.add("one");
        ls.add("Three");
        ls.add("two");
        ls.add("four");

        // remove list object
        ls.remove(2); // remove by index number

        ls.remove("four"); // remove by object

        Iterator it=ls.iterator();

        while(it.hasNext())
        {
          String value=(String)it.next();

          System.out.println("Value :"+value);
        }
    }
}
READ MORE - Remove elements from List

List Example in java


import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

public class ListExample {

    public static void main(String[] args) {

        // List Example implement with ArrayList
        List<String> ls=new ArrayList<String>();

        ls.add("one");
        ls.add("Three");
        ls.add("two");
        ls.add("four");

        Iterator it=ls.iterator();

        while(it.hasNext())
        {
          String value=(String)it.next();

          System.out.println("Value :"+value);
        }
    }
}
READ MORE - List Example in java

Greatest Common Divisor or GCD using Recursion in java


public class GCD
{
    public static int gcd(int num1, int num2)
    {
        if(num2 == 0)
        {
            return num1;
        }
        else
        {
            return gcd(num2, num1%num2);
        }
    }

}

//main class


import java.util.Scanner;

public class Main
{

    public static void main(String[] args)
    {
       Scanner input = new Scanner(System.in);

      System.out.print("Enter the first number: ");
      int num1 = input.nextInt();

      System.out.print("Enter the second power: ");
      int num2 = input.nextInt();

      GCD access = new GCD();

      System.out.print("The GCD of 2 numbers is: " + access.gcd(num1, num2));

    }

}
READ MORE - Greatest Common Divisor or GCD using Recursion in java

Recursive function for X to the power Y


public class Power
{
    public static double power(double base, double basePow)
    {
        
        if(basePow==0)
        {
            return 1;
        }
        else if(basePow==1)
        {
            return base;
        }
        else if(basePow>1)
        {
            return base*power(base,basePow-1);
        }
        else
        {

              return 1/power(base, -1 * basePow);
        }
       
       
    }
    
}

//main class

import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
      Scanner input = new Scanner(System.in);

      System.out.print("Enter the base number: ");
      double base = input.nextInt();

      System.out.print("Enter the base power: ");
      double basePow = input.nextInt();

      
      Power access = new Power();
      
      System.out.print(base + " to the power of " + basePow + " is: " + access.power(base, basePow));

    }

}
READ MORE - Recursive function for X to the power Y

Recursive Koch Snow Flakes in java


import java.awt.*;

import javax.swing.*;

public class recursiveKochSnowFlakes extends JApplet{
 int level = 0;

 public void init(){
  String levelStr = JOptionPane.showInputDialog("Enter the depth of recursion");

  level = Integer.parseInt(levelStr);
 }

 public void paint(Graphics g){

  drawSnow(g,level,20,280,280,280);
  drawSnow(g,level,280,280,150,20);
  drawSnow(g,level,150,20,20,280);

 }

 private void drawSnow (Graphics g, int lev, int x1, int y1, int x5, int y5){
       int deltaX, deltaY, x2, y2, x3, y3, x4, y4;

       if (lev == 0){

        g.drawLine(x1, y1, x5, y5);
       }
       else{
         deltaX = x5 - x1;
         deltaY = y5 - y1;

         x2 = x1 + deltaX / 3;
         y2 = y1 + deltaY / 3;

         x3 = (int) (0.5 * (x1+x5) + Math.sqrt(3) * (y1-y5)/6);
         y3 = (int) (0.5 * (y1+y5) + Math.sqrt(3) * (x5-x1)/6);

         x4 = x1 + 2 * deltaX /3;
         y4 = y1 + 2 * deltaY /3;

         drawSnow (g,lev-1, x1, y1, x2, y2);
         drawSnow (g,lev-1, x2, y2, x3, y3);
         drawSnow (g,lev-1, x3, y3, x4, y4);
         drawSnow (g,lev-1, x4, y4, x5, y5);
        }
    }
}
READ MORE - Recursive Koch Snow Flakes in java

Program that will Determine the Person's Salutation and Current Age


public class Person
{
    private String fName;
    private String lName;
    private String sex;
    
    private int year;
    private int month;
    private int day;
    

    public Person()
    {
        fName="";
        lName="";
        sex="";
        
        year=0;
        month=0;
        day=0;
    }
    public Person(String fName1, String lName1, String gender)
    {
        fName=fName1;
        lName=lName1;
        sex=gender;
       
    }
    public String getFName()
    {
        return fName;
    }
    public void setFName(String fName1)
    {
        fName=fName1;
    }
    public String getLName()
    {
        return lName;
    }
    public void setLName(String lName1)
    {
        lName=lName1;
    }
    public String getSex()
    {
        return sex;
    }
    public void setSex(String gender)
    {
        sex=gender;
    }
    public int getYear()
    {
        return year;
    }
    public void setYear(int year1)
    {
        year=year1;
    }
    public int getMonth()
    {
        return month;
    }
    public void setMonth(int month1)
    {
        month=month1;
    }
    public int getDay()
    {
        return day;
    }
    public void setDat(int day1)
    {
        day=day1;
    }
    public String getFullName()
    {
        if(sex.equals("f"))
        {
            return "Ms. "+ fName + " "+lName;
         
        }
        else
        {
           return "Mr. "+ fName +" "+lName;
        }
    }
    public String getAge(int cYear, int cMonth, int cDay, int bYear, int bMonth, int bDay)
    {
        
        String result="";
        int tYear;
        if((cYear>bYear) && (cMonth==bMonth))
        {
            if(cDay==bDay)
            {
               tYear=cYear-bYear;
               result= "Happy " + tYear + "th birthday!";
            }
            else if(cDay>bDay)
            {
               tYear=cYear-bYear;
               result= "Current Age: " + tYear + " years old.";
            }
            else if(cDay<bDay)
            {
                tYear=(cYear-1)-bYear;
               result= "Current Age: " + tYear + " years old.";
            }
        }
        else if((cYear > bYear) && (cMonth > bMonth))
        {
            tYear=cYear-bYear;
            result= "Current Age: " + tYear + " years old.";
        }
        else if((cYear > bYear) && (cMonth < bMonth))
        {
            tYear=(cYear-1)-bYear;
            result= "Current Age: " + tYear + " years old.";
        }
        else if(cYear<bYear)
        {
            result= "Wrong Input. Age Calculation Failed.";
        }
        return result;

    }
            
}


//main class


import java.util.Scanner;


public class Main
{

    
    public static void main(String[] args)
    {

        Scanner input = new Scanner(System.in);

        String fName, lName, gender;
        int cYear, cMonth, cDay;
        int bYear, bMonth, bDay;


        System.out.print("Enter you first name: ");
        fName= input.nextLine();

        System.out.print("Enter you last name: ");
        lName= input.nextLine();

        System.out.print("Enter you Gender: ");
        gender= input.nextLine();


        System.out.print("Please Enter current Date: ");
        cDay= input.nextInt();

        System.out.print("Please Enter current Month: ");
        cMonth= input.nextInt();

        System.out.print("Please Enter current Year: ");
        cYear= input.nextInt();

        System.out.println("-----BIRTHDAY INFORMATION-----");
        System.out.print("Please Enter your Birth Date: ");
        bDay= input.nextInt();

        System.out.print("Please Enter your Birth Month: ");
        bMonth= input.nextInt();

        System.out.print("Please Enter your Birth Year: ");
        bYear= input.nextInt();

        Person access = new Person(fName, lName, gender);
        System.out.println("Name: "+access.getFullName());
        System.out.println(access.getAge(cYear, cMonth, cDay, bYear, bMonth, bDay));
        

    }

}
-----------------------------------
Sample Output 1:
Enter you first name: Johny
Enter you last name: Smith
Enter you Gender: M
Please Enter current Date: 3
Please Enter current Month: 02
Please Enter current Year: 2012
-----BIRTHDAY INFORMATION-----
Please Enter your Birth Date: 3
Please Enter your Birth Month: 02
Please Enter your Birth Year: 1989
READ MORE - Program that will Determine the Person's Salutation and Current Age

Binary Search Using Recursion in java


public class binarySearch
{

    public int binSearch(int[] arr, int fIndex, int lIndex,int search)
    {

int middle = (fIndex + (lIndex - fIndex) / 2);

  if(fIndex<lIndex ){

   if (search == arr[middle]){

    return middle;
   }

   else if(search < arr[middle]){
    if(search == arr[0])
     return 0;
    return binSearch(arr, fIndex, middle, search);
   }

   else if(search > arr[middle]){
    if(search == arr[middle+1])
     return middle + 1;
    return binSearch(arr, middle+1, lIndex, search);
   }

  }
    return -1;
    }

 public void sort(int[] arr)
{
       for(int i=0; i<arr.length; i++)
        {
            for(int j=i+1; j<arr.length; j++ )
            {
                if(arr[i] > arr[j])
                {
                    int temp = arr[j];
                    arr[j]=arr[i];
                    arr[i]= temp;
                }
            }
        }

       for(int i=0; i<arr.length; i++)
       {
           System.out.print(arr[i] + " ");
       }
}

}

//main class


import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
         Scanner input = new Scanner(System.in);

        System.out.print("Enter the size of the array: ");
        int n = input.nextInt();
        int[] x = new int[n];

        System.out.print("Enter "+ n +" numbers: ");
        int middle;
        for(int i=0; i<n; i++)
        {
            x[i] = input.nextInt();
        }

        binarySearch access = new binarySearch();
        System.out.println("The sorted numbers are: ");
        access.sort(x);
        System.out.println();
        
        System.out.print("Enter the number you want to search: ");
        int value = input.nextInt();

        System.out.print("The search number is on the index ");
        System.out.print(access.binSearch(x, 0, x.length-1, value));
    }

}
READ MORE - Binary Search Using Recursion in java

Recursive Linear Search in java


public class Linear_Search

{

public void linSearch2(int[] arr, int fIndex, int lIndex, int searchNum)

{

if(fIndex == lIndex)

{

System.out.print("-1");

}

else

{

if(arr[fIndex] == searchNum)

{

System.out.print(fIndex);

}

else

{

linSearch2(arr, fIndex+1, lIndex, searchNum);

}

}

}

//main class


import java.util.Scanner;

public class Main {


    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the size of the array: ");
        int size = input.nextInt();
        System.out.print("Enter an array of numbers: ");

        int[] arr = new int[size];

        for(int i=0; i<arr.length; i++)
        {
            arr[i]=input.nextInt();
        }

        System.out.print("Enter the number you want to search: ");
        int search = input.nextInt();

       

        Linear_Search access = new Linear_Search();

        System.out.print("The position of the search item is at array index ");
        access.linSearch2(arr, 0, arr.length, search);
    }

}

READ MORE - Recursive Linear Search in java

How to sort numbers in Bubble Sort


public class BubbleSort
{

 public void bubbleSort(int[] arr){
     for(int i=0; i<arr.length; i++){
        for(int j=1; j<arr.length; j++){
            if(arr[j]< arr[j-1] ){
                int temp = arr[j];
                arr[j] = arr[j-1];
                arr[j-1] = temp;            
            }
        }
     }

     for(int i=0; i<arr.length; i++)
     {
         System.out.print(arr[i] + " ");
     }
}

}

//main class

import java.util.Scanner;

public class Main
{

   
    public static void main(String[] args)
    {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter the size of the array: ");
        int n = input.nextInt();
        int[] x = new int[n];

        System.out.print("Enter "+ n +" numbers: ");
        for(int i=0; i<n; i++)
        {
            x[i] = input.nextInt();
        }
        
        BubbleSort access = new  BubbleSort();
 System.out.print("The Sorted numbers: ");
        access.bubbleSort(x);
    }

}
READ MORE - How to sort numbers in Bubble Sort

Reverse string Or Print String Backward using Recursion


public class StringBackward
{
    public static void reverseString(String word, int size)
    {
       if(size==0)
       {
           return;
       }
       else
       {
          System.out.print(word.charAt(size-1));
          reverseString(word, size-1);
       }
    }

}

//main class

import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
      Scanner input = new Scanner(System.in);

       String word;
       System.out.print("Enter a word: ");
       word = input.next();

        StringBackward access = new  StringBackward();
        System.out.print("The reverse word is: ");
        access.reverseString(word, word.length());
        System.out.println();

    }

}
READ MORE - Reverse string Or Print String Backward using Recursion

How to Sort Numbers using Selection Sort


public class SelectionSort
{

     public void SelectionSort(int[] arr){
     for(int i=0; i<arr.length; i++)
     {
        for(int j=i+1; j<arr.length; j++)
        {
            if(arr[i] > arr[j] )
            {
                int temp = arr[j];
                arr[j] = arr[i];
                arr[i] = temp;
            }
        }
     }

     for(int i=0; i<arr.length; i++)
     {
         System.out.print(arr[i] + " ");
     }
}

//main class


import java.util.Scanner;

public class Main
{

    public static void main(String[] args)
    {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter the size of the array: ");
        int n = input.nextInt();
        int[] x = new int[n];

        System.out.print("Enter "+ n +" numbers: ");
        for(int i=0; i<n; i++)
        {
            x[i] = input.nextInt();
        }

        SelectionSort access = new  SelectionSort();
        System.out.print("The Sorted numbers: ");
        access.SelectionSort(x);
    }

}
READ MORE - How to Sort Numbers using Selection Sort

Add Numbers inside an Array Using Recursion


public class Array
{
    public static int array( int[] arr, int first, int last)
    {
      //  int sum = 0;
        if(arr[first] == arr[last])/* must be if(first == last),but try this one too, study the code, it is interesting */
        {
           return arr[first];
        }
        else
        {  
           return arr[first] + array(arr, first+1, last);
             
        }
       
    }
   

}

//main class


import java.util.Scanner;

public class Main
{

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the size of the input you want to enter: ");
        int size = input.nextInt();
        int[] numArr = new int[size];

        System.out.print("Enter "+ size +" numbers: ");
        for(int i=0; i<numArr.length; i++)
        {
          numArr[i]=input.nextInt();
        }

        System.out.print("The sum of the numbers is: "+   Array.array(numArr, 0 , size-1) );
            

    }
}
READ MORE - Add Numbers inside an Array Using Recursion

Add Numbers inside an Array using For Loop


import java.util.Scanner;

public class Main
{

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the size of the input you want to enter: ");
        int size = input.nextInt();
        int[] numArr = new int[size];
        int sum=0;
        
 System.out.print("Enter "+ size +" numbers: ");
        
 for(int i=0; i<numArr.length; i++)
        {
          numArr[i]=input.nextInt();
          sum = sum + numArr[i];
        }
    
        System.out.print("The sum of the numbers is: " + sum);
    }
}
Sample Output:
Enter the size of the input you want to enter: 5
Enter 5 numbers: 34 2 5 3 6
The sum of the numbers is: 50
If you want to make a method and segregate the implementation of sum for the sake of practice in Object Oriented Programming, just simply code it this way.
//java class

public class ArraySum
{
    public int sumOfArray(int[] array)
    {
        int sum = 0;
        for(int i=0; i<array.length; i++)
        {
            sum = sum + array[i];
        }

        return sum;
    }
}

//main class


import java.util.Scanner;

public class Main
{

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the size of the input you want to enter: ");
        int size = input.nextInt();
        int[] numArr = new int[size];
        
        System.out.print("Enter "+ size +" numbers: ");
        for(int i=0; i<numArr.length; i++)
        {
          numArr[i]=input.nextInt();
         
        }

        ArraySum access = new ArraySum();
        System.out.print("The sum of the numbers is:" + access.sumOfArray(numArr));        

    }
}
READ MORE - Add Numbers inside an Array using For Loop

print/draw Diamond Shape using Asterisk in java


public class Diamond
{
    public String Diamond_Asterisk(int num)
    {
        if(num>0)
        {
            return "*-" + Diamond_Asterisk(num-1);
        }
        else
        {
            return "-";
        }
    }
     public String Diamond_Asterisk2(int num)
    {
        if(num>0)
        {
            return "-*-" + Diamond_Asterisk(num-1);
        }
        else
        {
            return "-";
        }
    }

    public String Space(int num)
    {
        if(num>0)
        {
            return "-" + Space(num-1);
        }
        else
        {
            return "-";
        }
    }
    public void DiamondResult(int num)
    {
        for(int i=1; i<num; i++)
        {
            System.out.print(Space(num-i));
             System.out.println(Diamond_Asterisk(i));
            
        }
         for(int i=0; i<num; i++)
        {
            System.out.println(Diamond_Asterisk2(num-i));
            System.out.print(Space(i));

        }
     
    }
    

}


//main class


import java.util.Scanner;

public class Main {

    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int num = input.nextInt();

        Diamond access = new Diamond();
        System.out.println("The shape for this is: ");
        access.DiamondResult(num);
        
    }

}
===================================
Sample Output 1: Enter a number: 3 The shape for this is: ---*-- --*-*-- -*-*-*-- --*-*-- ---*-- Sample Output 2: Enter a number: 4 The shape for this is: ----*-- ---*-*-- --*-*-*-- -*-*-*-*-- --*-*-*-- ---*-*-- ----*--
READ MORE - print/draw Diamond Shape using Asterisk in java

Print Different Asterisk Shapes in java


//main method
public class Main{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
Asterisk1 access = new Asterisk1();
access.asterisk2(n);
}
}
//java class
public class Asterisk1 {
private int count = 0;
public void asterisk1(int n) {
if(n==0) {
System.out.println();
}
else {
System.out.print("*");
asterisk1(n-1); } }
public void asterisk2( int n) {
if(n==0){
return; }
else {
asterisk1(n);
asterisk2(n-1);
}
}
}
This program will output the asterisk in this form. If the number 4 is entered the form will be like this.
****
***
**
*
2. A Java source code for another Asterisk Form
/*The following code will have the same method as the first but different in implementation*/ //main method
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
Asterisk1 access = new Asterisk1();
access.asterisk2(n,1);
}
}
// java class
public class Asterisk1 {
private int count = 0;
public void asterisk1(int n) {
if(n==0) {
System.out.println();
}
else {
System.out.print("*");
asterisk1(n-1);
}
}
public void asterisk3(int count,int m) {
if( count == 0) {
System.out.println();
} else {
asterisk1(m);
asterisk3(n-1,m+1);
}
}
}
The output of this code if number 4 is entered will be like this.
*
**
***
****

To get a form that would look like this,
****
***
**
*
*
**
***
****
3. Here is the other code.

//main method
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
Asterisk1 access = new Asterisk1();
access.asterisk2(n); access.asterisk3(n,1);
}
}
// java class
public class Asterisk1 {
private int count = 0;
public void asterisk1(int n) {
if(n==0) { System.out.println();
} else {
System.out.print("*");
asterisk1(n-1);
}
}
public void asterisk2( int n) {
if(n==0) {
return;
} else {
asterisk1(n);
asterisk2(n-1);
}
}
public void asterisk3( int n,int m)
{ if( n == 0) {
System.out.println();
} else {
asterisk1(m);
asterisk3(n-1,m+1);
}
}
}
4. Lastly, to acquire a shape like this,
*
**
***
****
****
***
**
*
here is the code:
//main method
package prog_proj2;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
Asterisk1 access = new Asterisk1();
access.asterisk3(n); access.asterisk2(n);
}
}
//java class
public class Asterisk1 {
private int count = 0;
public static void asterisk1(int n) {
if(n==0) { System.out.println();
} else {
System.out.print("*");
asterisk1(n-1);
}
}
public void asterisk2( int n) {
if(n==0) { return;
} else {
asterisk1(n);
asterisk2(n-1);
}
}
public void asterisk3( int n) {
count++;
if( n == 0) {
return;
} else {
asterisk1(count);
asterisk3(n-1);
}
}
}
READ MORE - Print Different Asterisk Shapes in java

How to pass parameters on URL query string


READ MORE - How to pass parameters on URL query string

what is servlet context,page context and application context


READ MORE - what is servlet context,page context and application context

Error in JSP page for displaying elements of an array list


READ MORE - Error in JSP page for displaying elements of an array list

Check if user has clicked on submit button based on client/server side


READ MORE - Check if user has clicked on submit button based on client/server side

File uploading using JSP and Servlet


READ MORE - File uploading using JSP and Servlet

Filtering Responses


READ MORE - Filtering Responses

Sending value from one jsp page to another jsp page


READ MORE - Sending value from one jsp page to another jsp page

default size of a JSP?


READ MORE - default size of a JSP?

Process Simple Text Files As JSP


READ MORE - Process Simple Text Files As JSP

How to invoke a URL from a JSP page


READ MORE - How to invoke a URL from a JSP page

Login authentication using tomcat7


READ MORE - Login authentication using tomcat7

Java program to Read text File Line by Line


import java.io.*;
class FileRead
{
 public static void main(String args[])
  {
  try{
  // Open the file that is the first
  // command line parameter
  FileInputStream fstream = new FileInputStream("textfile.txt");
  // Get the object of DataInputStream
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  //Read File Line By Line
  while ((strLine = br.readLine()) != null)   {
  // Print the content on the console
  System.out.println (strLine);
  }
  //Close the input stream
  in.close();
    }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }
}
READ MORE - Java program to Read text File Line by Line

Convert Integer List to int array


READ MORE - Convert Integer List to int array

HTTP Status 404 error in tomcat


READ MORE - HTTP Status 404 error in tomcat

Difference between start() and run() method?


READ MORE - Difference between start() and run() method?

How to invoke a URL from a JSP page


READ MORE - How to invoke a URL from a JSP page

How can i count the returned rows from a database ?


READ MORE - How can i count the returned rows from a database ?

total number of rows in ResultSet


READ MORE - total number of rows in ResultSet

How to find the number of rows in the resultset ?


READ MORE - How to find the number of rows in the resultset ?

Compare HashSet,TreeSet and ArrayList by Example


import java.util.*;
import java.math.*;
public class NoDupsTest
{
  /* ---- HashSet approach (list order not maintained) ---- */
  public static void test_HashSet(ArrayList a_master)
  {
    ArrayList a = new ArrayList(a_master);
    long cur = System.currentTimeMillis();
    HashSet h = new HashSet(a);
    a.clear();
    a.addAll(h);
    long diff = System.currentTimeMillis()-cur;
    System.out.println("HashSet approach (no order) = "+diff);
  }
 
  /* ---- TreeSet approach (list order not maintained, but sorted) ---- */
  public static void test_TreeSet(ArrayList a_master)
  {
    ArrayList a = new ArrayList(a_master);
    long cur = System.currentTimeMillis();
    TreeSet t = new TreeSet(a);
    a.clear();
    Iterator iter = t.iterator();
    while (iter.hasNext())
      a.add(iter.next());
    long diff = System.currentTimeMillis()-cur;
    System.out.println(
      "TreeSet approach (sorted order) = "+diff+" ms");
  }
 
  /* ---- ArrayList and HashSet approach (order maintained) ---- */
  public static void test_HashSet_listOrder(ArrayList a_master)
  {
    ArrayList a = new ArrayList(a_master);
    long cur = System.currentTimeMillis();
    Set set = new HashSet();
    List newList = new ArrayList();
    for (Iterator iter = a.iterator(); iter.hasNext(); ) {
      Object element = iter.next();
      if (set.add(element))
        newList.add(element);
    }
    a.clear();
    a.addAll(newList);
    long diff = System.currentTimeMillis()-cur;
    System.out.println(
      "ArrayList/HashSet approach (list order) = "+diff+" ms");
  }
 
  /* ---- ArrayList and TreeSet approach ---- */
  public static void test_TreeSet_listOrder(ArrayList a_master)
  {
    ArrayList a = new ArrayList(a_master);
    long cur = System.currentTimeMillis();
    Set set = new TreeSet();
    List newList = new ArrayList();
    for (Iterator iter = a.iterator(); iter.hasNext(); ) {
      Object element = iter.next();
      if (set.add(element))
        newList.add(element);
    }
    a.clear();
    a.addAll(newList);
    long diff = System.currentTimeMillis()-cur;
    System.out.println(
      "ArrayList/TreeSet approach (list order) = "+diff+" ms");
  }
 
  public static void main(String[] args)
  {
    int num = Integer.parseInt(args[0]);
    int numUnique = Integer.parseInt(args[1]);
    /* Create master list */
    Random rnd = new Random();
    ArrayList masterList = new ArrayList();
    for (int i=0; i<num; i++) {
      masterList.add(new Integer((Math.abs(rnd.nextInt())%numUnique)));
    }
    /* Run tests */
    test_HashSet(masterList);
    test_TreeSet(masterList);
    test_HashSet_listOrder(masterList);
    test_TreeSet_listOrder(masterList);
  }
}
READ MORE - Compare HashSet,TreeSet and ArrayList by Example

ArrayList without duplicates


READ MORE - ArrayList without duplicates

Simple console print statement demonstration


public class ConsolePrintApplet1 extends java.applet.Applet
{
  public void init ()
  {

    // Put code between this line
    //------------------------------------------
    double x = 5.0;
    double y = 3.0;
    System.out.println ("x * y = " + (x*y));
    System.out.println ("x / y = " + (x/y));

    // and this line.
    //------------------------------------------
  }

  // Paint message in Applet window.
  public void paint (java.awt.Graphics g) {
     g.drawString ("ConsolePrintApplet1",10,20);
  }
}
public class ConsolePrintApp1 extends java.applet.Applet
{
  public static void main (String [] args) {
    // Put code between this line
    //------------------------------------------

    double x = 5.0;
    double y = 3.0;
    System.out.println ("x * y = " + (x*y));
    System.out.println ("x / y = " + (x/y));

    //------------------------------------------
    // and this line.
  }

}
READ MORE - Simple console print statement demonstration

How to install and Configure the Tomcat Server


READ MORE - How to install and Configure the Tomcat Server

How to open a .war file inside Netbean IDE?


READ MORE - How to open a .war file inside Netbean IDE?

How to change functionlatiy in web page


READ MORE - How to change functionlatiy in web page

How to use web service in J2ME application(MIDP)


READ MORE - How to use web service in J2ME application(MIDP)

how to add web cam in web page


READ MORE - how to add web cam in web page

How to Open Text or Word File on JButton Click in Java


READ MORE - How to Open Text or Word File on JButton Click in Java

Hashtable in java

// Demonstrate a Hashtable 
import java.util.*; 
class HTDemo { 
public static void main(String args[]) { 
Hashtable balance = new Hashtable(); 
Enumeration names; 
String str; 
double bal; 
balance.put("John Doe", new Double(3434.34)); 
balance.put("Tom Smith", new Double(123.22)); 
balance.put("Jane Baker", new Double(1378.00)); 
balance.put("Todd Hall", new Double(99.22)); 
balance.put("Ralph Smith", new Double(-19.08)); 
// Show all balances in hash table. 
names = balance.keys(); 
while(names.hasMoreElements()) { 
str = (String) names.nextElement(); 
System.out.println(str + ": " + 
balance.get(str)); 

System.out.println(); 
// Deposit 1,000 into John Doe's account 
bal = ((Double)balance.get("John Doe")).doubleValue(); 
balance.put("John Doe", new Double(bal+1000)); 
System.out.println("John Doe's new balance: " + 
balance.get("John Doe")); 

}
READ MORE - Hashtable in java

 
 
 
 


Copyright © 2012 http://codeprecisely.blogspot.com. All rights reserved |Term of Use and Policies|