Sunday, October 5, 2014

Java programs

no.of occurance of a letter:

public class countexample {
public static void main(String args[]){  
String input="meeraja";
int charCount = 0; //resetting character count
    for(char ch: input.toCharArray()){
        if(ch == 'a'){
            charCount++;
        }
    }     
    System.out.println("count of character 'a' on String: " + charCount);
}


}


Fibonacci:


public class fibonacc {

public static void main(String[]args){
int num=8;
int current = 1;
int last = 0;
int lastlast;
for(int i=0;i<num;i++){
lastlast=last;
last=current;
current= last + lastlast;

System.out.println(current);
}}}


Bubble sort:


public class bubblesort1 {
static int num[]={2,5,45,23};

public static void main(String[] args) {
System.out.println("before sort");
for (int i =0;i<num.length;++i){
System.out.println(num[i]);
}
int temp;
for(int i=num.length-1;i>0;i--)
{
for(int j=0;j<i;j++){
if(num[j]>num[j +1]){
temp=num[j];
num[j]= num[j+1];
num[j+1]=temp;
}}}
for(int k=0;k<num.length;k++)  
System.out.println(num[k]);
}


Sort integer array:


public class sort_int_example {

public static void main(String[]args){

//Sorting integers

  

  int a[] = {10,5,6,3};

  a = sort(a);

  for(int i:a)

  System.out.println(i);

}

  public static int[] sort(int[] a)

  {

  int n = a.length;

  int temp;

  

  for(int i=0;i<n-1;++i)

  {

  for(int j=0;j<n-i-1;j++)

  {

  if(a[j]>a[j+1])

  {

  temp = a[j];

  a[j] = a[j+1];

  a[j+1] = temp;

  }

  }

  }

  return a;

  }

}



sort a string:



public class sort_exam {



public static void main(String[] args){
   String wordSt="watch";
   char[] word=wordSt.toCharArray();
int n=wordSt.length();
   for(int i=0;i<(n-1);i++){
    //for(int j=0;j<n-i-1;j++){
      for(int j=i+1;j>0;j--){
           if(word[j]<word[j-1]){
               char temp=word[j-1];
               word[j-1]=word[j];
               word[j]=temp;
           }
       }
   }
   wordSt=String.valueOf(word);
   System.out.println(wordSt);
}
}

**********************************************************
public class string_sort {
public static void main(String args[]){
sort("meeraja");
}
public static String sort(String str)
  {
  StringBuffer result = null;
  
  if(str!=null && str.length()>0)
  {
  
  char[] chars = new char[str.length()];
  result = new StringBuffer(chars.length);
  
  for(int i=0;i<chars.length;++i)
  chars[i] = str.charAt(i);
  
  //character array is ready to sort
  int n = chars.length;
  char temp;
  for(int i=0;i<n-1;++i)
  {
  for(int j=0;j<n-i-1;j++)
  {
  if(chars[j]>chars[j+1])
  {
  temp = chars[j];
  chars[j] = chars[j+1];
  chars[j+1] = temp;
  }
  }
  }
  
  for(char c:chars)
  {
  System.out.print(c);
  result.append(c);
  }
  return result.toString();  
  }
  return str;
  
  }
}



String array sorting:

public class Str_Examples {

public static void main(String[]args){


//Sorting strings

  String names[] = {"Sanjay","Sriram","Meeraja","Ramana"};

  names = sort(names);

  for(String name1:names)

  System.out.println(name1); }

public static String[] sort(String[] a)

  {

  int n = a.length;

  System.out.println(n);

  String temp;

  

  for(int i=0;i<n-1;++i)

  {

  for(int j=0;j<n-i-1;j++)

  {

  if(a[j].compareTo(a[j+1])>0)

  {

  temp = a[j];

  a[j] = a[j+1];

  a[j+1] = temp;

  }

  }

FInd largest number:


    1. Find Largest and Smallest Number
    2.  /*
    3.   Find Largest and Smallest Number in an Array Example
    4.   This Java Example shows how to find largest and smallest number in an
    5.   array.
    6. */
    7. public class FindLargestSmallestNumber {
    8.         public static void main(String[] args) {
    9.                
    10.                 //array of 10 numbers
    11.                 int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};
    12.                
    13.                 //assign first element of an array to largest and smallest
    14.                 int smallest = numbers[0];
    15.                 int largetst = numbers[0];
    16.                
    17.                 for(int i=1; i< numbers.length; i++)
    18.                 {
    19.                         if(numbers[i] > largetst)
    20.                                 largetst = numbers[i];
    21.                         else if (numbers[i] < smallest)
    22.                                 smallest = numbers[i];
    23.                        
    24.                 }
    25.                
    26.                 System.out.println("Largest Number is : " + largetst);
    27.                 System.out.println("Smallest Number is : " + smallest);
    28.         }
    29. }
    30. /*
    31. Output of this program would be
    32. Largest Number is : 98
    33. Smallest Number is : 23
    34. */

FindEvenOrOddNumber
  1. /*
  2.   Even Odd Number Example
  3.   This Java Even Odd Number Example shows how to check if the given
  4.   number is even or odd.
  5. */
  6. public class FindEvenOrOddNumber {
  7.         public static void main(String[] args) {
  8.                
  9.                 //create an array of 10 numbers
  10.                 int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10};
  11.                
  12.                 for(int i=0; i < numbers.length; i++){
  13.                        
  14.                         /*
  15.                          * use modulus operator to check if the number is even or odd. 
  16.                          * If we divide any number by 2 and reminder is 0 then the number is
  17.                          * even, otherwise it is odd.
  18.                          */
  19.                          
  20.                          if(numbers[i]%== 0)
  21.                                 System.out.println(numbers[i] + " is even number.");
  22.                          else
  23.                                 System.out.println(numbers[i] + " is odd number.");
  24.                                
  25.                 }
  26.                
  27.         }
  28. }
  29. /*
  30. Output of the program would be
  31. 1 is odd number.
  32. 2 is even number.
  33. 3 is odd number.
  34. 4 is even number.
  35. 5 is odd number.
  36. 6 is even number.
  37. 7 is odd number.
  38. 8 is even number.
  39. 9 is odd number.
  40. 10 is even number.
  41. */


remove duplicates from an array:


import java.util.HashSet;

public class test {
static int[] array = {4, 3, 3, 4, 5, 2, 4};
static HashSet l = new HashSet();
public static void main(String ar[])
{       
    for(int i=0;i<array.length;i++)
    {         
      l.add(array[i]);

    }
    System.out.println(l);
}}


Reverse a numbere:
import java.util.Scanner;
 
class ReverseNumber
{
   public static void main(String args[])
   {
      int n, reverse = 0;
 
      System.out.println("Enter the number to reverse");
      Scanner in = new Scanner(System.in);
      n = in.nextInt();
 
      while( n != 0 )
      {
          reverse = reverse * 10;
          reverse = reverse + n%10;
          n = n/10;
      }
 
      System.out.println("Reverse of entered number is "+reverse);
   }
}


Java – Reverse String without using Reverse function

package JavaPrograms;
import java.util.*;
public class ReverseString {

  public static void main(String args[])
  {
     String original, reverse ="";
     Scanner in = new Scanner(System.in);

     System.out.println("Enter a string to reverse");
     original = in.nextLine();

     int length = original.length();

     for ( int i = length - 1 ; i >= 0 ; i-- )
        reverse = reverse + original.charAt(i);

     System.out.println("Reverse of entered string is "+reverse);
  }
}




Java – Remove Duplicate Number from Array


package JavaPrograms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveduplicateArray {


//  Remove duplicate entries from an array of long integers

    public static void main(String[] args)
    {
        //
        // A long integer array with some duplicated values
        //
        long [] longArray = { 11,0, 11, 22, 44, 55, 66, 77, 88, 0, 99, 77, 66, 42, 55, 66, 99, 11};

        System.out.println("Original array size = " + longArray.length);
        System.out.println("Original array            : " +
                Arrays.toString(longArray));

        //
        // Want to let Java convert the array to a Set, since
        // the Set object won't have duplicate entries.
        //
        // But first...
        //
        // Since the Set constructor needs a List (not an array),
        // "convert" the array to a List.
        //
        List<Long> longList = new ArrayList<Long>();
        for (int i = 0; i < longArray.length; i++)
        {
            longList.add(longArray[i]);
        }

        // Now, instantiate a Set with its constructor that has a List argument
        Set <Long> longSet = new HashSet<Long>(longList);

        //
        // Create an array of Long objects and use Set.toArray()
        // to "convert" the Set to the array.
        Long[] resultNoDups = new Long[longSet.size()];
        longSet.toArray(resultNoDups);

        // Finally, if we want an array of long ints rather
        // than an array of Long objects, create the array
        // and copy the values
        long [] finalArray = new long[resultNoDups.length];
        for (int i = 0; i < resultNoDups.length; i++) {
            finalArray[i] = resultNoDups[i];
        }

        // Taa-daa
        System.out.println("After removing duplicates : " +
                Arrays.toString(finalArray));

        System.out.println("Result array size = " + finalArray.length);
        System.out.println();
    }
}


Program to Find Prime Number

package JavaPrograms;
import java.util.*;

public class PrimeNumber {
//Note: Scanner class work with JDK1.5 or above

public static void main(String args[])
{
int n, i, res;
boolean flag=true;

System.out.println("Please Enter a No.");
Scanner scan= new Scanner(System.in);
n=scan.nextInt();
for(i=2;i<=n/2;i++)
{
res=n%i;
if(res==0)
{
flag=false;
break;
}
}
if(flag)
System.out.println(n + " is Prime Number");
else
System.out.println(n + " is not Prime Number");
}
}



Program Palindrome Series

package JavaPrograms;
import java.util.*;
public class palindrome {

  public static void main(String args[])
  {
     String original, reverse="";
     Scanner in = new Scanner(System.in);

     System.out.println("Enter a string to check if it is a palindrome");
     original = in.nextLine();

     int length = original.length();

     for ( int i = length - 1 ; i >= 0 ; i-- )
        reverse = reverse + original.charAt(i);

     if (original.equals(reverse))
        System.out.println("Entered string is a palindrome.");
     else
        System.out.println("Entered string is not a palindrome.");

  }
}



Integer array sorting:

package JavaExamplea;

public class sort_int_example {

public static void main(String[]args){

//Sorting integers

  int a[] = {10,5,6,3};
  a = sort(a);
  for(int i:a)
  System.out.println(i);

}

  public static int[] sort(int[] a)
  {
  int n = a.length;
  int temp;

  for(int i=0;i<n-1;++i)
  {
  for(int j=0;j<n-i-1;j++)
  {
  if(a[j]>a[j+1])
  {
  temp = a[j];
  a[j] = a[j+1];
  a[j+1] = temp;
  }
  }
  }
  return a;
  }

}


Program to find Fibonacci series of a given number

package JavaPrograms;

public class fabonacciSeries {

/*Write a program to find Fibonacci series of a given no.
 Example :
 Input - 8
 Output - 1 1 2 3 5 8 13 21
*/

public static void main(String args[])
{
int num = 6; //taking no. as command line argument.
System.out.println("*****Fibonacci Series*****");
int f1=0, f2=0, f3=1, f4=0, temp=0;
for(int i=1;i<=num;i++){
System.out.print(" "+f3+" ");
temp =f1+f2-1;
f1 = f2;
f2 = f3;
f3 = f1 + f2;

f4 = f3 + temp;
}
System.out.print(" \n sum of Fabonacci series numbers "+f4+" ");
}
}


Compare Two Array Program

package JavaPrograms;

public class CompareArray {

public static void compareArrays(int[] array1, int[] array2) {
boolean b = true;
if (array1 != null && array2 != null){
if (array1.length != array2.length)
b = false;
else
for (int i = 0; i < array2.length; i++) {
if (array2[i] != array1[i]) {
b = false;
}
}
}else{
b = false;
}
System.out.println(b);
}
}


BubbleSort Program

package JavaPrograms;

import java.util.Scanner;

class BubbleSort {
public static void main(String []args) {
int n, c, d, swap;
Scanner in = new Scanner(System.in);

System.out.println("Input number of integers to sort");
n = in.nextInt();

int array[] = new int[n];

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++)
array[c] = in.nextInt();

for (c = 0; c < ( n - 1 ); c++) {
for (d = 0; d < n - c - 1; d++) {
if (array[d] > array[d+1]) /* For descending order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}

System.out.println("Sorted list of numbers");

for (c = 0; c < n; c++)
System.out.println(array[c]);
}
}

Program Array to Vector

package JavaPrograms;
import java.util.*;
public class ArraytoVector {

public static void main(String[] args) {
// declare and initialize array of object of given class.
Object[] arrObject = {"Manish", new Date(), "Rajesh"};
//create list for this object array.
List list = Arrays.asList(arrObject);
// create vector for given list.
Vector vector = new Vector(list);
// access the elements of the vector.
Enumeration enume = vector.elements();
while (enume.hasMoreElements()) {
System.out.println(enume.nextElement().toString());
}
}
}



Reverse String Array 


  1. /*
  2.         Java Reverse String Array Example
  3.         This Java Reverse String Array example shows how to find sort an array of
  4.         String in Java using Arrays and Collections classes.
  5.  */
  6. import java.util.Collections;
  7. import java.util.List;
  8. import java.util.Arrays;
  9. public class ReverseStringArrayExample {
  10.        
  11.         public static void main(String args[]){
  12.                
  13.                 //String array
  14.                 String[] strDays = new String[]{"Sunday""Monday""Tuesday","Wednesday"};
  15.                
  16.                 /*
  17.                  * There are basically two methods, one is to use temporary array and
  18.                  * manually loop through the elements of an Array and swap them or to use
  19.                  * Arrays and Collections classes.
  20.                  *
  21.                  * This example uses the second approach i.e. without temp variable.
  22.                  *
  23.                  */
  24.                
  25.                 //first create a list from String array
  26.                 List<String> list = Arrays.asList(strDays);
  27.                
  28.                 //next, reverse the list using Collections.reverse method
  29.                 Collections.reverse(list);
  30.                
  31.                 //next, convert the list back to String array
  32.                 strDays = (String[]) list.toArray();
  33.                
  34.                 System.out.println("String array reversed");
  35.                
  36.                 //print the reversed String array
  37.                 for(int i=0; i < strDays.length; i++){
  38.                         System.out.println(strDays[i]);
  39.                 }
  40.                
  41.         }
  42. }
  43. /*
  44. Output of above given Java Reverse String Array example would be
  45. String array reversed
  46. Wednesday
  47. Tuesday
  48. Monday
  49. Sunday
  50. */

No comments:

Post a Comment