Sunday, 29 November 2015

Fibonacci Series in Java

 
public class FibDemo {


  public static void main(String[] args) {
           int current, prev1 = 1, prev2 = 0;
          for(int i = 0; i < 5; i++) { 
                 current = prev1 + prev2;    
                System.out.print(current + " ");
                prev2 = prev1;
                prev1 = current; 
         }
    System.out.println();  
  }
}

Output :
 1 2 3 5 8
 

Recursive Factorial in Java



public class RecursiveFactorial {
      public static void main(String[] args) {
          System.out.println(""+factorial(5));
      }

      public static long factorial(long x) {
          if (x == 1) return 1;
              else return x * factorial(x-1);
      }
}


Output :

120

Factorial in Java



public class FactorialDemo {

   public static void main(String[] args) {
      System.out.println(""+factorial(5));
   }


    public static int factorial(int x) {
       int fact = 1;
       for(int i = 2; i <= x; i++)  {
         fact *= i;       
       }

       return fact;
    }
}


Output :
120

Friday, 27 November 2015

Reading Input from Command Line using Stream Class

class JStreamDemo
{
 public static void main(String[] args)
 {
  String text = null;
  InputStreamReader inputStream = new InputStreamReader(System.in);
  BufferedReader bufferedReader = new BufferedReader(inputStream);
  text = bufferedReader.readLine();
  System.out.println(text);
 }
}
 
Given Input :
 
Java is programming language.
 
 
Output :
 
Java is programming language. 

Reading Input from Command Line

 
 
Below will explain how to get the input string from commandline:
 
public class JScanDemo
{
  public static void main (String[] args)
  {
     Scanner scanner = new Scanner(System.in); 
    System.out.print("Enter name: ");
    String name = scanner.next();
    System.out.println(name);
  }
}
 
Given Input :
---------------

Enter name:
 
Rajesh
 
Output :
---------- 
Rajesh