Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

program of fibonacci series with recursion without loop

Thursday, 8 May 2014

This is java program to calculate fibonacci series with recursion. Always think alternatively as we can do this program easily using a loop. Every element in the fibonacci seires is addition of previous two elements. a[n]=a[n-1]+a[n-2] follow this rule to calculate whole series.




Program of  fibonacci series using Recursion in Java


import java.util.*;

public class FiboByRecursion {
public static void main(String args[]){
  
    Scanner s=new Scanner(System.in);
    System.out.println("Enter Number of Elements");
    int a=s.nextInt();
    for(int i=0;i<a;i++){
    System.out.println(doRecursion(i));
    }
}



public static int doRecursion(int a)
{
    if(a==0)
        return 0;
    else if(a == 1)
        return 1;
    else
        return doRecursion(a-1)+doRecursion(a-2);

}
}
Continue Reading | comments

Different ways to read and write files in java

Java provides different ways to read and write files. Java has library for file management thats' java.io.* .All file handling methods is defined inside it. We have to use io methods for insertion & deletion of data of files. For this we use java.io.* package which contains Input - Output classes.


First Let's discuss important file handling methods in java. which is important for file handling.


->Create a new file;

1) File f= new File()

2) File f =new File("pathname"); /* pathname should be like this    "C:\\dir1\\dir2\\file.txt" */

3) File f = new File("directoryname",filename);

4) File getName()   /* for retrieval of filename */

 5) mkdir() for creating directory.

filename.mkdir();

6) mkdirs() for creating all parents directory of filename.

filename.mkdirs()

7) list()  for listing all the directories inside any directory. In java directory & files r synonym to each other.




Methods for Input - Output to a File



-->By Stream Classes

 
 
The image shows inhertiance structure of classes Input & Output Stream. We use FileInputStream most oftenly.


Methods for reading file (InputStream Classes)

int read() throws IOException  /* Returns next Byte from InputStream */

int read(byte a[]) throws IOException /*Returns some byte from InputStream & Saves data into byte array a */


 As it is for OutputStream Classes

void write(int a) throws IOException  /* Write a into file */

void write(byte a[]) throws IOException  /* Write some no. of bytes to OutputStream */



Program to input content into a File

import java.io.*;
public class InputClassByStream {

    public static void main(String args[]) throws IOException
    {
        String s="new file i m  -1 innocent";
        File f=new File("C:\\Users\\op\\Desktop\\file.txt");    \* Create File Object *\
        FileOutputStream fi=new FileOutputStream(f);      
        byte b[]=s.getBytes();   \* Convert String into Bytes array *\
        fi.write(b);
        byte b1=33;
        fi.write(b1);
    }

}


Program show output from a File


public class OutputClassByStream{
    public static void main(String args[]) throws IOException
    {
        File f=new File("C:\\Users\\op\\Desktop\\file.txt");
        FileInputStream fo=new FileInputStream(f);
        int i;
        while((i=fo.read())!=-1){        \* Returns -1 at the end of Stream *\      
        System.out.print((char)i);     \* cast into char value *\
        }
     }
}




/* InputSreamReader i = new InputStreamReader(filename,"UTF8"); */

This line we use when we require stream into particular character set. Here UTF8 character set.






Character Stream








Click on image to enlarge it and you will see actual path in the reader classes. They derived from Object class going downward and end up with filereader & filewriter.



FileReader is used to read stream of characters from a file.
CharArrayReader is used to read stream from array. Here array act as inputstream.
BufferedReader is used to taking character stream from anywhere(Console,arrays). It is used to hold large piece of data into a buffer. Which minimize IO time.
FilterReader is used to filter output based on the filteration apply on input stream.
InputStreamReader is used to convert byte streams into specific charset.




Read Character From Command Prompt, Store in a File and print output on command prompt.



import java.io.*;
public class IOClassByStream{
    public static void main(String args[]) throws IOException
    {
       
        File f = new File("C:\\Users\\op\\Desktop\\file.txt");
        FileWriter fo=new FileWriter(f); // for Writiing File
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        FileReader fi=new FileReader(f); // for Reading File

        int ch;
        while((ch=br.read())!='e')
        fo.write(ch);                    // Writing Characters to file

        while((ch=fi.read())!=-1){
        System.out.print(fi.read());    // Reading String contents from file
        }
    }

}


If you r facing problem in any part of program then please inform us. We will get back to you shorter. This program is easiest way to get input from console and feed content into the file.




Continue Reading | comments

How to read html content from any website in java program & JUnitTest

Friday, 2 May 2014

Here the full code for the given program. First of all understand the problem thats more important. Now its time to write code for this. I think anyone can easily understand this program.

This program will show you html code of any website & simulateously store contents into file located in your E:\Sex.txt. You can change its location or its name.






package test;

import java.util.*;
import java.net.*;
import java.io.*;

  public class JavaSourceViewer{
 
  
  public static void main(String args[])throws IOException{
  System.out.print("Enter Your URL(use http before url) : ");
  Scanner in=new Scanner(System.in);

 String str =in.nextLine();

 try{
  StringBuffer sb=new StringBuffer();
  actionPerform(str,sb);
  }catch(MalformedURLException e){
  System.out.println(str+" is not valid");
  }
 }

  public static void actionPerform(String u,StringBuffer br)throws MalformedURLException{
  
  try{
   File out1=new File("E://Sex.txt");
   FileWriter f=new FileWriter(out1,false);
   URL u1=new URL(u);
  HttpURLConnection hp=(HttpURLConnection)u1.openConnection();
  int code =hp.getResponseCode();
  String str1=hp.getResponseMessage();
  System.out.println("HTTP/1.x "+code+" "+str1);
  Scanner out=new Scanner(hp.getInputStream());
 

  String str2;
 
  while(out.hasNext())
  {
   
          str2=out.nextLine();
          br.append(str2);
          f.write(str2);
          System.out.println(str2);
  }
  }catch(Exception e){}
  }}

Now its time for creating JUnit Test Cases for the given program. Always remember few steps before going to test. JUnitTest is an api defined in  import static org.* package. It means you have to import this library to use JUnitTest.


How to create JUnitTestCase in Eclipse ?

Please do the same thing otherwise it would difficult for novice users. There r some following steps for creating JUnitTest.


Step 1 :






Step 2 :

Name your Class and then browse class under test (class which we wants to test)







Step 3 :

 browse class under test



And click on Ok then click on next.



Step 4 :

Select class methods which you want to test. You can select any number of methods.





Now work is half completed, its time to write testClass.





This is simple JUnitTest program easy to understand i will make you understand later.


package test;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileReader;

import org.junit.Test;
import java.io.*;


public class JavaSource {

 @Test
 public void testActionPerform() throws Exception
 {
  StringBuffer str=new StringBuffer();
  JavaSourceViewer.actionPerform("http://www.skillrefine.com",str);
   assertEquals("op",-1,str.indexOf("hhihiuhihui"));
  //fail("Not yet implemented");
  }
 }


assertEquals("Your Message",Object 1,Object 2); // it will show error if two objects r unequal.
assertTrue(boolean); // it will show error if expression inside this function return false.
assertFalse(boolean); // it will show error if expression inside this function return true.




 
Continue Reading | comments

Collections Framework in Java (brief)

Monday, 28 April 2014

collections in java is data structure to hold different objects and iterate them through different inbulit functions. I defined collections with small letter becoz there is another Collections class in java.util package which contains static utility function which operates on collection of objects.

collections -> data structure to hold objects (or framework).

Collections -> class inside java.util package contains static methods which iterates over collections object.

Collection - > Collection interface is on the top of hierarchy which is extended by list, queue and set. Map is not a part of Collection but collections. As i said collections is way to store objects. Map use to store object using key-value pair.

It is not a part of Collection becoz their methods or operation is different than list, queue. It does n't implement any of the methods of Collection interface. Thats why it is not a part of Collection interface.


How many interfaces and concrete classes in collections framework ?

Concrete classes r the classes which implements interfaces in java. In fig when you see red circle which means a interface otherwise concrete class.






What is difference b/w ArrayList and Vector ?

Vector and Arraylist methods r same bt Vector methods r more likely synchronized.


Difference b/w ArrayList and LinkedList ?

ArrayList use index for any of the operations like removal, insertion and updation while LinkedList can be iterate whether from beginning or top not from middle.


Difference b/w Set and List ?

Set doesn't allow duplicates items while list allows duplicates. Random output in case of set.


Difference b/w Map and Set ?

Map contains key-value pair, all objects(values) store through key. Autoboxing is automatically performed by java complier So primitive types convert into respective wrapper objects.



Some common methods in coolection framework (not for Map)

->public boolean addAll(collection c)

->public boolean add(object a)

->public boolean remove(Object a)

->public boolean removeAll(collection c)

->public int size()

->public boolean contains(object a)

->public boolean containsAll(collection c)

->public Iterator iterator()

-> Arrays.asLists(arrayname)

->public int hashcode()

->public boolean equals(coolection c)


Comparable interface is used to compare values of user defined data types. It uses compareTo(object a) for this purpose.

Comparator interface defined in java.lang package, it consists 2 member functions equals(), public int compare(Object b1, Object b2).


Maps Methods-

put(key,value);
get(key);

like -  put(1,"i m unemployed);
to get the value we use get(key) function
System.out.println(get(1));

Properties classes is where both key and value both r strings.

sort() is used to sort elements of list or subclasses.



TreeSet provides us sorted elements of set and same for TreeMap.









Continue Reading | comments
 
My Other Websites : Ad Networks | Games Copyright © 2014. Study Depth - All Rights Reserved