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

Monday, 14 December 2015

How to Convert Enumeration to Arraylist - Java Example

We can convert enumeration to arraylist in java with  the help list() method of Collections.

package javaproficeincy;

import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;

public class EnumerationToList {
public static void main(String[] args) {
Vector<String> vt = new Vector<String>();
        vt.add("java");
        vt.add("php");
        vt.add("array");
        vt.add("string");
        vt.add("c");
        Enumeration<String> enm = vt.elements();
        List<String> ll = Collections.list(enm);
        System.out.println("List elements: "+ll);
}

}


Output:

List elements: [java, php, array, string, c]

Related Posts :


Wednesday, 2 December 2015

How Find out duplicate number between 1 to N numbers - Java Program

We have numbers from 1 to n  and one number is duplicate. Now we will find out duplicate number in given list. For this we will use formula sum of 1....n numbers.Firstly we will calculate the sum of list and sum of 1.... n number. Now difference between sum of list and sum of 1... n is equal to duplicate number .

sum of 1... n number = n*(n+1)/2


package com.javaproficiency;

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

public class FindDuplicateNumber {

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i < 10; i++) {
list.add(i);
}
list.add(5);
FindDuplicateNumber duplicateNumber = new FindDuplicateNumber();
System.out.println(" duplicate number ="+ duplicateNumber.getDuplicateNumber(list));
}

public  int getDuplicateNumber( ArrayList<Integer> list){

int size = list.size()-1;
int totalSum = (size*(size+1))/2;
int duplicateNumber = getSumOfList(list)- totalSum ;
return duplicateNumber;
}

public int getSumOfList( ArrayList<Integer> list){
int sum =0;
for (Integer num : list) {
sum += num;
}
return sum;
}


}


Output :

 duplicate number =5




Tuesday, 1 December 2015

How to convert binary to decimal number - Java Program

In this example we will convert binary to decimal using  java. We will use this logic

11 ==>>  1*2^1+1*2^0   == > 3

110 ==> 1*2^2+1*2^1+0*2^0  ==> 6

package com.javaproficiency;

public class BinaryToDecimal {

public static void main(String[] args) {

System.out.println(" decimal number ="+ getDecimalFromBinary(11));

}


public static int getDecimalFromBinary(int num ){
int decimal = 0 ;
int p = 0;
 while ( num > 0) {
 decimal += num %10 * Math.pow(2, p );
 num = num /10;
 p++;
}

return decimal;
}

}


Output:

decimal number = 3

Monday, 30 November 2015

Method Overriding Example - Java Program

package com.javaproficiency;


class Y {

void display(){
System.out.println(" Y is called");
}

}


public class X extends Y{

void display(){
System.out.println(" X is called");
}


public static void main(String[] args) {

    Y y = new Y();
    X x = new X();
    Y obj = new X();
   
    y.display();
    x.display();
    obj.display();
   
   

}

}



Output:

 Y is called

 X is called

 X is called

Thursday, 26 November 2015

How to count the number of occurrences of a character in a string in java

Count the number of occurrences of a character in a string is good programming questions . It is ask in colleges and schools mostly. This question also asked in many times in interviews. 

Method 1:

We can count number of occurrences of a character in a string with the help of indexOf() method.

package com.javaproficiency;

public class CountCharOccurance {
public static void main(String[] args) {
String str = "javaproficiencyexamplebyannu";
 
    String findStr = "a";
    int lastIndex = 0;
    int counter = 0;
 
    while (lastIndex != -1) {
 
     lastIndex = str.indexOf(findStr, lastIndex);
 
     if (lastIndex != -1) {
      counter++;
      lastIndex += findStr.length();
 
     }
    }
    System.out.println(counter);
}


}


Output: 

4


Method 2:

In this example we will use charAt() method of string for count number of occurrences of a character in a string .

package com.javaproficiency;

public class CountCharOccurancejava {
public static void main(String[] args) {
String s = "javaproficiencyexamplebyannu";
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
   if( s.charAt(i) == 'a' ) {
       counter++;
   } 
}
System.out.println( counter );
}

}


Output:

4


How to print numbers from 1 to 10 without using loop?

We can print numbers 1 to 10 or 1 to 100 using recursion. Recursion is a good alternatives of loop. There we can use recursion to print numbers 1 to 10. We also use goto statement but in java we can not used goto statement. visit java keyword list http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html. So we will use here recursion.


package com.javaproficiency;

public class PrintNumber {

public static void main(String[] args) {

printNumberWithRecursion(1);

}

public static void printNumberWithRecursion(int n){

if (n <= 10) {
System.out.println(" number is ="+ n);
printNumberWithRecursion(n+1);
}

}

}


Output :

 number is =1
 number is =2
 number is =3
 number is =4
 number is =5
 number is =6
 number is =7
 number is =8
 number is =9
 number is =10

How to Sort the String using string Method In java

Java have a lot of method for string operations. We can sort a string by convert in to array of characters , now we will sort array after that we will make a new string from sorted array.Now our new string is in sorted order of characters.

package com.javaproficiency;

import java.util.Arrays;

public class StringSort {

public static void main(String[] args) {
String str = "xyabds";
char [] arr = str.toCharArray();
Arrays.sort(arr);
String sortedStr = new String(arr);
System.out.println(" sorted string = "+sortedStr);
}

}

Output:

 sorted string = abdsxy

Wednesday, 25 November 2015

Object Cloning in java example?

package com.javaproficiency;

public class Emp implements Cloneable {
//Object Cloning in java example?

int id;
String name;

public Emp(int id, String name) {
super();
this.id = id;
this.name = name;
}

public Emp clone() throws CloneNotSupportedException{

return (Emp ) super.clone();

}

public static void main(String[] args) {

Emp  emp = new Emp(10, "java");
Emp emp1 = null;
try {
emp1 = emp.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println(" clone object is ");
System.out.println("id ="+ emp1.id+ " name ="+ emp1.name);

}

}


Output:

 clone object is
 id =10 name =java




How to reverse a number in java

package com.javaproficiency;

public class ReverseNumber {

public static void main(String[] args) {
int num =251;
int rNum =0;
while(num > 0){
rNum = rNum*10+ num%10;
num = num/10;
}
System.out.println(" reverse number is ="+rNum);
}
}


Output:

 reverse number is =152

How to Check number is prime or not


A number which is divided by one and itself is called prime number. For Example

7 is a prime number and
8 is not a prime number

package com.javaproficiency;

public class PrintPrime {

public static void main(String[] args) {
int i =101;
boolean flag = false;
for(int j=2 ; j <= i/2; j++){
if(i%j==0)
{
flag = true ;
break;
}
}
if(flag){
System.out.println(" number "+ i +" is not prime");
}else{
System.out.println(" number "+ i +" is  prime");
}

}

}


Output :

 number 101 is  prime

Monday, 25 May 2015

How to Remove List From Vector

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class RemoveList {
   
      public static void main(String[] args) {
           
             Vector<String> vector = new Vector<String>();
             //add element in vector
             vector.add("cricket");
             vector.add("hockey");
             vector.add("football");
             vector.add("tennish");
           
             // print vector
             System.out.println("Vector = "+vector);
           
             List<String> list = new ArrayList<String>();
             list.add("hockey");
             list.add("tennish");
             list.add("apple");
             list.add("java");
           
             System.out.println("list is = "+list);
           
             /*
              * Removes from this Vector all of its
              *  elements that are contained in the
              *  specified Collection.
              */
             vector.removeAll(list);
           
             System.out.println("Vector after remove list = "+vector);
                   
                }

}


Output:
Vector = [cricket, hockey, football, tennish]

list is = [hockey, tennish, apple, java]

Vector after remove list = [cricket, football]