Posts

Showing posts from June, 2016

reverse a number

 public int reverseNumber(int number){                 int reverse = 0;         while(number != 0){             reverse = (reverse*10)+(number%10);             number = number/10;         }         return reverse;     }

Maximum repeated words from file

mport java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.Map.Entry; public class MaxDuplicateWordCount {         public Map getWordCount(String fileName){         FileInputStream fis = null;         DataInputStream dis = null;         BufferedReader br = null;         Map wordMap = new HashMap ();         try {             fis = new FileInputStream(fileName);             dis = new DataInputStream(fis);             br ...

Duplicate characters in a String

import java.util.HashMap; import java.util.Map; import java.util.Set; public class DuplicateCharsInString {     public void findDuplicateChars(String str){                 Map dupMap = new HashMap ();          char[] chrs = str.toCharArray();         for(Character ch:chrs){             if(dupMap.containsKey(ch)){                 dupMap.put(ch, dupMap.get(ch)+1);             } else {                 dupMap.put(ch, 1);             }         }         Set keys = dupMap.keySet();         for(Character ch:keys){             if(dupMap.get(ch) > 1){                 System.out.println(ch+"--->"+dupM...

Swapping two numbers

 public static void main(String a[]){         int x = 10;         int y = 20;         System.out.println("Before swap:");         System.out.println("x value: "+x);         System.out.println("y value: "+y);         x = x+y;         y=x-y;         x=x-y;         System.out.println("After swap:");         System.out.println("x value: "+x);         System.out.println("y value: "+y);     }

Get Distinct word

public List getDistinctWordList(String fileName){         FileInputStream fis = null;         DataInputStream dis = null;         BufferedReader br = null;         List wordList = new ArrayList ();         try {             fis = new FileInputStream(fileName);             dis = new DataInputStream(fis);             br = new BufferedReader(new InputStreamReader(dis));             String line = null;             while((line = br.readLine()) != null){                 StringTokenizer st = new StringTokenizer(line, " ,.;:\"");                 while(st.hasMoreTokens()){                     String tmp = st.nextToken()....

Delete Particular Element of Array

  String[] str_array = {"item1","item2","item3"}; List list = new ArrayList (Arrays.asList(str_array)); list.remove("item2"); str_array = list.toArray(new String[0]); System.out.println(Arrays.toString(str_array)); public static String[] removeItemFromArray(String[] input, String item) {     if (input == null) {         return null;     } else if (input.length <= 0) {         return input;     } else {         String[] output = new String[input.length - 1];         int count = 0;         for (String i : input) {             if (!i.equals(item)) {                 output[count++] = i;             }         }         return output;     } }     String[] strArr = new String[]{"google","microsoft","...

Remove duplicates sorted array

int all[]=new int[]{1,2,1,2,1,3,4,5,2,7}; Arrays.sort(all); System.out.println(Arrays.toString(all)); HashSet set=new HashSet (); for(Integer a:all) { set.add(a); } System.out.println(set);     int[] input = {2,3,6,6,8,9,10,10,10,12,12}; ArrayList list = new ArrayList (); for(int i = 0 ; i < input.length; i++) { if(!list.contains(input[i])) { System.out.println(input[i]); list.add(input[i]); } } System.out.println(list); private void removeTheDuplicates(List myList) {     for(ListIterator iterator = myList.listIterator(); iterator.hasNext();) {         Customer customer = iterator.next();         if(Collections.frequency(myList, customer) > 1) {             iterator.remove();         }     }     System.out.println(myList.toString()); } Set s = new HashSet (listCustomer); If you need to preserve elements order then use LinkedHashSet instead of HashSet ...

Fibonacci Series

class FibonacciExample1{ public static void main(String args[]) {    int n1=0,n2=1,n3,i,count=10;    System.out.print(n1+" "+n2);//printing 0 and 1        for(i=2;i  {     n3=n1+n2;     System.out.print(" "+n3);     n1=n2;     n2=n3;    }     }} 

File Read

try (BufferedReader br = new BufferedReader(new FileReader(file))) {     String line;     while ((line = br.readLine()) != null) {        // process the line.     } } import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public static void readText throws FileNotFoundException {     Scanner scan = new Scanner(new File("samplefilename.txt"));     while(scan.hasNextLine()){         String line = scan.nextLine();         //Here you can manipulate the string the way you want     } } try( BufferedReader reader = new BufferedReader( ... ) ) {   reader.lines().foreach( line -> processLine( line ) ); }    String pathFile="/path/to/file.txt";    String cmd="type";    if(System.getProperty("os.name")=="Linux"){        cmd="cat";    }    Process p= Runtime.getRuntime().exe...

Java Learning

http://www.java2novice.com/

Treeset Sorting

mport java.util.Comparator; import java.util.TreeSet; public class MyCompUserDefine {     public static void main(String a[]){         //By using name comparator (String comparison)         TreeSet nameComp = new TreeSet (new MyNameComp());         nameComp.add(new Empl("Ram",3000));         nameComp.add(new Empl("John",6000));         nameComp.add(new Empl("Crish",2000));         nameComp.add(new Empl("Tom",2400));         for(Empl e:nameComp){             System.out.println(e);         }         System.out.println("===========================");         //By using salary comparator (int comparison)         TreeSet salComp = new TreeSet (new MySalaryComp());         salComp.add(new Empl("Ram",3000));   ...

Comparable and Comparator

import java.util.Comparator; public class Employee implements Comparable<Employee> {     private int id;     private String name;     private int age;     private long salary;     public int getId() {         return id;     }     public String getName() {         return name;     }     public int getAge() {         return age;     }     public long getSalary() {         return salary;     }     public Employee(int id, String name, int age, int salary) {         this.id = id;         this.name = name;         this.age = age;         this.salary = salary;     }     @Override     public int compareTo(Employee emp) {         //let's sort the employee ...

Array Sorting

import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class JavaObjectSorting {     /**      * This class shows how to sort primitive arrays,       * Wrapper classes Object Arrays      * @param args      */     public static void main(String[] args) {         //sort primitives array like int array         int[] intArr = {5,9,1,10};         Arrays.sort(intArr);         System.out.println(Arrays.toString(intArr));                  //sorting String array         String[] strArr = {"A", "C", "B", "Z", "E"};         Arrays.sort(strArr);         System.out.println(Arrays.toString(strArr));                  //sorting list of o...

User Defined Object Sorting

public class ExampleComparator { public static void main(String[] args) {     List<Person> list = new ArrayList<Person>();     list.add(new Person("shyam",24));     list.add(new Person("jk",29));     list.add(new Person("paul",30));     list.add(new Person("ashique",4));     list.add(new Person("sreeraj",14));     for (Person person : list) {         System.out.println(person.getName()+ "   "+ person.getAge());     }     Collections.sort(list,new PersonComparator());     System.out.println("After sorting");     for (Person person : list) {         System.out.println(person.getName()+ "   "+ person.getAge());     } } } public class Person { private int age; private String name; Person (String name, int age){     setName(name);     setAge(age); } public int getAge() {     return a...

Xml SAX and DOM Parser

import java.io.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.w3c.dom.*; public class create { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter number to add elements in your XML file: "); String str = bf.readLine(); int no = Integer.parseInt(str); System.out.print("Enter root: "); String root = bf.readLine(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();         DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();         Document document = documentBuilder.newDocument(); Element rootElement = document.createElement(root);         document.appendChild(rootElement); for (int i = 1; i <= no; i++){ System.out.print("Enter the elem...

SOAP and Axis WebService Client

import java.net.URL; import java.util.Vector; import org.apache.soap.Constants; import org.apache.soap.rpc.Call; import org.apache.soap.rpc.Parameter; import org.apache.soap.rpc.Response; public class test {   public static void main( String[] args ) throws Exception {    // soap service endpoint     URL url = new URL( "http://localhost:8080/soap/servlet/rpcrouter" );     // create a call    Call call = new Call();     // Service uses standard SOAP encoding     call.setEncodingStyleURI( Constants.NS_URI_SOAP_ENC );     // Set service locator parameters     call.setTargetObjectURI( "urn:ex" );     call.setMethodName( "rstring" );     // Create input parameter vector     Vector params = new Vector();     params.addElement( new Parameter( "s", String.class, "hai da...", null ) );     call.setParams( params );     // Invoke the service, note that a...
https://drive.google.com/open?id=0B_WUy8ODLamYd0p4YTNqQWFsRUU

Java Oracle Database Connectivity

import java.sql.*; public class JdbcAccessCreate {  Connection con;  Statement st;  public JdbcAccessCreate()  {   try{    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");    con=DriverManager.getConnection("jdbc:odbc:abc");    System.out.println("Database Connected");    st=con.createStatement();    String query="create table student(roll number,name text,contactno number)";     st.executeUpdate(query);     System.out.println("Table created successfully");     }catch(Exception e)       {       System.out.println("Error in connection"+e);       }   }   public static void main(String arg[])   {     new JdbcAccessCreate();     } }        import java.sql.*; public class JdbcOracleCreate {  Connection con;  Statement st;  public JdbcOracleCreate()  {   try{   ...