//Using recursion
public class Febo
{
public static void main(String[] args)
{
for ( int i = 0; i < 10; i++ ) {
System.out.print ( fib(i) + " " );
}
//System.out.println ( fib(10) );
}
//to find nth Fibonacci number
static long fib(int n) {
return n <= 1 ? n : fib(n-1) + fib(n-2);
}
}
//Simple program written by me
import java.io.*;
public class Febo {
public static void main(String []args) throws IOException
{
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter a number");
String input=reader.readLine();
int i=Integer.parseInt(input);
int []ret=Fibo(i);
for(int j=0;j<ret.length;j++)
{
System.out.print(" "+ret[j]);
}
}
public static int[] Fibo(int n)
{
int a[]=new int[n];
if (n==1)
a[0]=0;
else
{a[0]=0;
a[1]=1;
}
if(n>2)
{
for(int i=2;i<n;i++)
{
a[i]=a[i-1]+a[i-2];
}
}
return a;
}
}
Wednesday, April 18, 2012
Efficient program to reverse a string
public class Reverse {
public static void main(String [] args)
{
String s=reverse("Anand Prakash Yadav");
System.out.println(s);
}
public static String reverse ( String s ) {
int length = s.length(), last = length - 1;
char[] chars = s.toCharArray();
for ( int i = 0; i < length/2; i++ ) {
char c = chars[i];
chars[i] = chars[last - i];
chars[last - i] = c;
}
return new String(chars);
}
}
Friday, March 23, 2012
Hit Counter Servlet Example
This example illustrates about counting how many times the servlet is
accessed. When first time
servlet (CounterServlet) runs then session is created and value of the counter will be zero and after
again accessing of servlet the counter value will be increased by one. In this
program isNew() method is used whether session is new or old and getValue()
method is used to get the value of counter.
Here is the source code of CounterServlet.java:
Mapping of Servlet ("CounterServlet.java") in web.xml file
Running the servlet by this url: http://localhost:8080/CodingDiaryExample/CounterServlet
Here is the source code of CounterServlet.java:
import java.io.*;
|
| <servlet> <servlet-name>CounterServlet</servlet-name> <servlet-class>CounterServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CounterServlet</servlet-name> <url-pattern>/CounterServlet</url-pattern> </servlet-mapping> |
Thursday, March 22, 2012
How can I create a daemon thread?
The Thread API allows
Threads to be created which are at the mercy of their user threads. This
is accomplished simply by passing true to the setDaemon() method and invoking the method off an instance of the thread wishing to set it's status.
public void setDeamon(boolean b)
The following is a simple program which creates a thread within the
context of the main thread of execution. Since the main thread is a user
thread the created thread will also be a user thread unless it's status
is set otherwise. A couple of notes about the following code. If the
created threads status is not set or false is passed to the setDameon()
method then the created thread will fully execute. This is because the
main thread cannot return until all non-daemon threads are finished.
Setting the status to true in our case doesn't give our daemon
thread much time to do it's bussiness since the main method will quickly
execute then return thus stopping our daemon thread dead in it's
tracks. We would be lucky to get a print out of one year!. So what can
we do? Either we can put the main thread to sleep for an amount of time
(enough to give our dameon thread time to do it's business) or simply
make it a non-daemon thread by setting it's status to false.
public class UserThread{
public static void main(String[] args){
Thread t = new Thread(new DaemonThread(525.00f, 0.09f));
t.setDaemon(true);
t.start();
try{
Thread.sleep(250); // must give the deamon thread a chance to run!
}catch(InterruptedException ei){ // 250 mills might not be enough!
System.err.println(ei);
}
}
}
class DaemonThread implements Runnable{
private float principal;
private float futureval;
private float rate;
private float i;
public DaemonThread(float principal, float rate){
this.principal= principal;
this.rate = rate;
}
public void run(){
for(int year = 0; year <= 75; year++){
i = (1 + rate);
futureval = principal * (float)Math.pow(i,year);
System.out.print(principal + " compounded after " + year + " years @ " + rate + "% = " + futureval);
System.out.println();
}
}
}
Java is strictly pass-by-value
/*Java is Pass-by-Value
Pass-by-value
The actual parameter (or argument expression) is fully evaluated and the resulting value is copied into a location being used to hold the formal parameter's value during method/function execution. That location is typically a chunk of memory on the runtime stack for the application.
Pass-by-reference
The formal parameter merely acts as an alias for the actual parameter. Anytime the method/function uses the formal parameter (for reading or writing), it is actually using the actual parameter.
Java is strictly pass-by-value
Litmus test is swap method.
Value outside the method not changed.
*/
public class Swap {
public static void main(String [] args)
{
int a=20;
int b=30;
swap(20,30);
System.out.println(" "+a+" "+b);
}
public static void swap(int a,int b)
{
// int temp=a;
// a=b;
// b=temp;
a=a+b;
b=a-b;
a=a-b;
System.out.println(" "+a+" "+b);
}
}
Another good example show how values change if you directly change value pointed by that reference else if you create by new operator or setters, it will not change.
public class PassByRefEx {
public static void main(String [] args)
{
int [] a={2,3,6,9,10};
int abc=23;
Dog aDog = new Dog("Max");
System.out.println("int Before modification "+abc);
System.out.println("Dog object Before modification "+aDog.name);
System.out.print("Array Before modification ");
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
System.out.println();
modifyArray(a,abc,aDog);
System.out.println("int After modification "+abc);
System.out.println("Dog object after modification "+aDog.name);
System.out.print("Array After modification ");
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
public static void modifyArray(int []b, int x, Dog d)
{
// d.setName("Fifi"); // would change the name of the dog
d = new Dog("Fifi"); // would not change the original variable
// b[0] = 3; // would change the contents of the original array
b = new int[1]; // followed by...
b[0] = 3; // would not affect the original array
x=34; // It would not affect the original value
}
}
class Dog {
String name=null;
public Dog(String aname)
{
name=aname;
}
public void setName(String bname)
{
name=bname;
}
}
Monday, March 12, 2012
OccurancesInArray
import java.io.*;
public class OccurancesInArray{
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many elements you want to enter in the array: ");
int num=0;
try{
num = Integer.parseInt(in.readLine());
}
catch(NumberFormatException ne){
System.out.println(ne.getMessage() + " is not a number!");
System.exit(0);
}
String[] elements = new String[num];
int a;
int k;
for(int i = 0; i < num; i++){
elements[i] = in.readLine();
}
for(int i = 0; i < elements.length; i++){
a = 0;
k = 1;
for(int j = 0; j < elements.length; j++){
if(j >= i){
if(elements[i].equals(elements[j]) && j != i){
k++;
}
}
else if(elements[i].equals(elements[j])){
a = 1;
}
}
if(a != 1){
System.out.println("Occurance of \'" + elements[i] + "\' : " + k);
}
}
}
}
FindMissingNumber
/*Find out sum of n numbers and substract the sum of numbers from this sum.
*
*
*/
public class FindNumber {
public static void main(String [] args)
{
int totalsum=10*(10+1)/2;
int givensum=0;
int [] a={1,4,3,2,5,7,9,8,10};
for(int i=0;i<a.length;i++)
{
givensum +=a[i];
}
int missingnum=totalsum-givensum;
System.out.println(" Missing number is :"+missingnum);
}
}
*
*
*/
public class FindNumber {
public static void main(String [] args)
{
int totalsum=10*(10+1)/2;
int givensum=0;
int [] a={1,4,3,2,5,7,9,8,10};
for(int i=0;i<a.length;i++)
{
givensum +=a[i];
}
int missingnum=totalsum-givensum;
System.out.println(" Missing number is :"+missingnum);
}
}
Subscribe to:
Posts (Atom)