Showing posts with label Interview Programs in Java. Show all posts
Showing posts with label Interview Programs in Java. Show all posts

Monday, 27 June 2016

Program to Check whether a String is Positive or not.

Explanation :
ANT is a positive String (Since T comes after N and N comes after A)
APPLE is not positive since L comes before P in the alphabetical order.

Code:

import java.util.Scanner;
public class PositiveString
{
    char a1,b;
    boolean checkPositive(String a)
    {
        System.out.println("Given input is :"+a);
        int f,s;
        for(int i=0;i<a.length()-1;i++)
        {
            a1=a.charAt(i);
            b=a.charAt(i+1);
            f=Character.getNumericValue(a1);
            s=Character.getNumericValue(b);
            if(f-s>0)
                return false;
            else
                continue ;
        }
        return true;
        }
   
    public static void main(String[] args)
    {
        PositiveString n=new PositiveString();
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the string:");
       
        String s=sc.next();
        boolean a=n.checkPositive(s);
        if(a)    System.out.println("positive");
        else    System.out.println("Negative");
        sc.close();
    }     
}

Program to Convert a String to an Encrypted Code.

Explanation :
For String =cde the Encrypted Code Shall be ASCII Values of c+9, d+9, e+9.
If n=abc then Output will be "jkl"
If n=az then Output will be "ji".

Code:

import java.util.Scanner;
public class Encryption
{
    String encryptString(String st)
    {
        char ch[]=st.toCharArray();
        for(int i=0;i<st.length();i++)
        {
            if(ch[i]>='a' && ch[i]<='q')
                  ch[i]=(char) (ch[i]+9);
            else
                  ch[i]=(char) (ch[i]-17); //(26-9)
        }
        String str=new String(ch);
        return str;
    }
   
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        String str1,str2;
        System.out.println("Enter String");
        str1=sc.next();
        Encryption ecr=new Encryption();
        str2=ecr.encryptString(str1);
        System.out.println("Encrypted string is  :"+str2);
        sc.close();
    }
}

Program to perform Sum of Digits On Double Datatype.

Explanation :
If n=123.56 then Output will be 6:11 .
If n=401 then Output will be 5:0 .

Code:

import java.util.Scanner;
public class DoubleSumOfDigits
{
    String getSum(double d)
    {
        String s=Double.toString(d);
        int res1=0,res2=0;
        int i=s.indexOf(".");
       
        for(int j=0;j<i;j++)
        {
            int n=s.charAt(j);
            res1+=Character.getNumericValue(n);
        }
        for(int j=i+1;j<s.length();j++)
        {
            res2+=Character.getNumericValue(s.charAt(j));
        }
        String fnl=Integer.toString(res1)+":"+Integer.toString(res2);
        return fnl;
    }
   
    public static void main(String[] args)
    {
       
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter any double number");
       
        DoubleSumOfDigits das=new DoubleSumOfDigits();
        String b=das.getSum(sc.nextDouble());
        System.out.println(b);

        sc.close();
    }
}

Program to Print Numbers in String Format .

Explanation :
If n=123 then Output will be "One Two Three" .

Code:

import java.util.Scanner;
public class NumberToString
{
    String getNumber(int num)
    {
        String str="";
        int d;
        while(num!=0)
        {
            d=num%10;
            switch(d)
            {
               case 0:str="Zero  "+str;            break;
               case 1:str="One  "+str;             break;
               case 2:str="Two  "+str;            break;
               case 3:str="Three  "+str;          break;
               case 4:str="Four  "+str;            break;
               case 5:str="Five  "+str;            break;
               case 6:str="Six  "+str;              break;
               case 7:str="Seven  "+str;         break;
               case 8:str="Eight  "+str;          break;
               case 9:str="Nine  "+str;           break;
               default:break;
            }
            num=num/10;
        }
        return str;
    }

    public static void main(String args[])
    {
        NumberToString cnt= new NumberToString();
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter number  :");
        int num=sc.nextInt();
        String str=cnt.getNumber(num);
        System.out.println(num+" in String format is: "+str);
        sc.close();
    }
}

Sunday, 19 June 2016

Program to print a Number Pattern Type-1.

Explanation :
If n=6 then output will be
66666666666
65555555556
65444444456
65433333456
65432223456
65432123456
65432223456
65433333456
65444444456
65555555556
66666666666.

Code:

import java.util.Scanner;
public class Pattern11
{
    public static void main(String args[])
    {
        int i,j;
        System.out.print("Enter any number:");
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        for (i=n; i >=1 ; i--)
        {
           for (j=n ; j >= i ; j--)
                System.out.print(j);
           for (j=1 ; j<(i*2)-1 ;j++)
                System.out.print(i);
           for (j=i+1;j<=n;j++)
                System.out.print(j);
           System.out.print("\n");
        }
      
        for (i=2;i<=n;i++)
        {
            for (j=n; j>=i; j--)
               System.out.print(j);
            for (j =1 ; j<(i*2)-1 ; j++)
               System.out.print(i);
            for (j=i+1 ;j<=n ;j++)
               System.out.print(j);
            System.out.print("\n");
        }
        sc.close();
}
}

Saturday, 18 June 2016

Program to prove that String Object is immutable or an example of String Pooling.

Code:

public class StringPooling
{
    public static void main( String args[])
    {
        String s1="a";
        String s2="a";
        System.out.println(s1==s2);//true
        System.out.println(s1.equals(s2));//true
       
        String s3=new String("a");
        String s4=new String("a");
        System.out.println(s3==s4);//false
        System.out.println(s3.equals(s4));//true
       
        String s5="a";
        String s6=new String("a");
        System.out.println(s5==s6);//false
        System.out.println(s5.equals(s6));//true
    }
}

Program to print the Words of a Given String ending with a Particular Letter.

Explanation :
If String= "All cars are supercars until they have tires".
1)If Letter = "s" then output will be "cars,supercars,tires".
2)If Letter = "l" then output will be "All,until".
3)If letter = "v" then output will be "There are no words ending with Letter v".

Code:

import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class EndsWithLetter
{   
     public static void main(String args[])
     {
        int count=0;
        ArrayList<String> ar= new ArrayList<String>();
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any String");
        String x=sc.nextLine();
        System.out.println("Enter a letter");
        String y=sc.nextLine();
        StringTokenizer st=new StringTokenizer(x,",/-@ ");
        while(st.hasMoreTokens())
        {
            String st1 = (String) st.nextToken();
            if(st1.endsWith(y))
            {
                ar.add(st1);//Adding Words in ArrayList
                count+=1;
            }
        }
        if(count!=0)
        {
                System.out.println("Words ending with letter "+y+" are:");
                for(String z:ar)
                {
                    System.out.println(z);
                }
        }
        else System.out.println("There are no words ending with Letter "+y);
        sc.close();
    }
}

Program to find the frequency of a SubString in a given String.

Explanation :
If String ="For each rose,a rose is a rose" and SubString ="rose" then,
output will be "rose has occured 3 times".

Code:

import java.util.Scanner;
import java.util.StringTokenizer;
public class SubStringCount
{
      public static void main(String args[])
     {
         int count=0;
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter any String");
         String x=sc.nextLine();
         System.out.println("Enter Sub String");
         String y=sc.nextLine();
         StringTokenizer st=new StringTokenizer(x,", ");
        while(st.hasMoreTokens())
       {
             String st1 = (String) st.nextToken();
               if(st1.equals(y))
              {
                   count ++;
               }
        }
             System.out.println(y+" has occured "+ count+ " times in "+x);
             sc.close();
}
}

Program to perform Merge Sort.

Code:

public class MergeSort
{    
    private int[] array;
    private int[] tempMergArr;
    private int length;
    public static void main(String args[])
    {        
        int[] inputArr = {45,23,11,89,77,98,4,28,65,43};
        MergeSort mms = new MergeSort();
        mms.sort(inputArr);
        for(int i:inputArr)
        {
            System.out.print(i);
            System.out.print(" ");
        }
    }
    
    public void sort(int inputArr[])
    {
        this.array = inputArr;
        this.length = inputArr.length;
        this.tempMergArr = new int[length];
        doMergeSort(0, length - 1);
    }

    private void doMergeSort(int lowerIndex, int higherIndex)
    {        
        if (lowerIndex < higherIndex)
        {
            int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
            // Below step sorts the left side of the array
            doMergeSort(lowerIndex, middle);
            // Below step sorts the right side of the array
            doMergeSort(middle + 1, higherIndex);
            // Now merge both sides
            mergeParts(lowerIndex, middle, higherIndex);
        }
    }

    private void mergeParts(int lowerIndex, int middle, int higherIndex)
    {
        for (int i = lowerIndex; i <= higherIndex; i++)
        {
            tempMergArr[i] = array[i];
        }
        int i = lowerIndex;
        int j = middle + 1;
        int k = lowerIndex;
        while (i <= middle && j <= higherIndex)
        {
            if (tempMergArr[i] <= tempMergArr[j])
            {
                array[k] = tempMergArr[i];
                i++;
            }
            else
            {
                array[k] = tempMergArr[j];
                j++;
            }
            k++;
        }
        while (i <= middle)
        {
            array[k] = tempMergArr[i];
            k++;
            i++;
        }
     }
}

Friday, 17 June 2016

Program to print 1 to 10 using Recursion.

Explanation :
Recursion means calling a method within itself until it returns a value.

Code:

public class Print
{
       public static void recursive(int n)
      {
        if(n <= 10)
       {
              System.out.println(n);
              recursive(n+1);
       }
       }

       public static void main(String args[])
      {
       recursive(1);
       }
 }

Program to reverse a string without using String API.

Explanation :
If str ="Hello world" then output will be "dlrow olleH".

Code:

public class Reverse
{
       public static void main(String[] args)
      {
           String str="Hello world";
           String rev="";
          for(int i=str.length()-1;i>=0;--i)
          {
            revs +=str.charAt(i);
           }

           System.out.println(rev);
}
}

Program to print Floyd Triangle.

Explanation :
If n=4 then output will be
1
2 3
4 5 6
7 8 9 10

Code:

import java.util.Scanner;
public class FloydTriangle
{
public static void main(String[] args)
{
     Scanner in = new Scanner(System.in);
     System.out.println("Enter the number of rows: ");
     int r = in.nextInt();
     int n=0;
     for(int i=0; i<r; i++)
     {
        for(int j=0; j<=i; j++)
        {
           System.out.print(++n+" ");
        }
        System.out.println();
        }
     in.close();
}
}

Program to know whether a number is Magic Number or not.

Explanation :
If n=1729 then find the sum of digits of the given number i.e,
(1 + 7 + 2 + 9 =19). Reverse of 19 is 91.
Then (19 X 91 = 1729).
If the obtained product value and the given input are same, then the given number is a magic number.

Code:

import java.util.Scanner;
public class MagicNumber
{
    public static void main (String args[])
    {
        int num, sum, rev;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the value for num:");
        num=sc.nextInt();
        MagicNumber m=new MagicNumber();
        sum = m.sumOfDigits(num);
        rev = m.reverse(sum);
        if (sum < 10)
        {
                if ((sum * sum) == num)
                {
                    System.out.println(num+" is a magic number");
                }
                else
                {
                    System.out.println(num+" is not a magic number");
                }
              
        }
        else if ((sum * rev) == num)
        {
            System.out.println(num+" is a magic number");
        }
        else
        {
            System.out.println(num+" is not a magic number");
        }
        sc.close();
    }
   
    public int sumOfDigits(int n)
    {
        int s = 0;
        while (n > 0)
        {
                s = s + (n % 10);
                n = n / 10;
        }
        return s;
    }

    public int reverse(int num)
    {
        int rev = 0;
        while (num > 0)
        {
                rev = (rev * 10) + (num % 10);
                num = num / 10;
        }
        return rev;
    }
}

Program to find the Second Maximum digit in a number without using Arrays.

Explanation :
1) If n=12 then output will be 1.
2) If n=71233568 then output will be 7.

Code:

import java.util.Scanner;
public class SecondMax
{
public static void main(String args[])
{
    Scanner sc=new Scanner(System.in);
    int max = 0,r=0;
    int secondmax = 0;
    System.out.println("Enter any number :");
    int n = sc.nextInt();
    int num=n;
     
    while(num % 10 != 0)
    {
        r = num % 10;
        if(r > max)
        {
            secondmax=max;
            max = r;
        }
        else if(r<max && r>secondmax)
        {
            secondmax=r;
        }
       
        num /= 10;
    }
    System.out.println("Maximum is :"+max);
    System.out.print("Second Maximum digit in "+n+" is :"+secondmax);
    sc.close();
}
}

Program to find the Lucky number of a Person based on Date Of Birth.

Explanation :
If Input is 15-Mar-1995 then the output will calculated as :
(1+5)+(0+3)+(1+9+9+5)=33 which will proceed to give output as 3+3=6 which is the Lucky Number.

Code:

import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;

public class LuckyNumber
{
      public static void main(String[] args)
      {
         int n,rem,sum = 0;
         ArrayList<String> s=new ArrayList<String>();
         String s2;
         int date,year,month;
        
         //Taking Date as Input
         Scanner sc=new Scanner(System.in);
         System.out.println("Enter the Date in the 15-Mar-1995 Format:");
         String day=sc.nextLine();
         StringTokenizer st=new StringTokenizer(day,",/- ");
         while(st.hasMoreTokens())
         {
             s2 =st.nextToken();
             s.add(s2);//Adding Date In the ArrayList as String Objects
         }
         date=Integer.parseInt(s.get(0));//Getting the Date
         s2=s.get(1);//Getting the Month from the Date
         s2.toLowerCase();
         year=Integer.parseInt(s.get(2));//Getting Year
        
         if(s2=="jan") month =1;
         else if(s2=="feb") month =2;
         else if(s2=="mar") month =3;
         else if(s2=="apr") month =4;
         else if(s2=="may") month =5;
         else if(s2=="jun") month =6;
         else if(s2=="jul" || s2=="july") month =7;
         else if(s2=="aug") month =8;
         else if(s2=="sep" || s2=="sept") month =9;
         else if(s2=="oct") month =10;
         else if(s2=="nov") month =11;
         else  month =12;
        
         n=date+month+year;
        
         while(n > 0)
         {
                     while(n != 0)
                     {
                          rem = n%10;
                          sum = sum+rem;
                          n=n/10;
                     }
                     if(sum > 9)
                     {
                            n = sum;
                            sum = 0;
                     }
          }
          System.out.println("Your Lucky Number is: "+sum);  
          sc.close();
    }  
}

Program to find the Sum of digits of a Given Number until a Single digit is obtained.

Explanation :
1) If n=12 then output will be 1+2=3.
2) If n=78 then output will be 7+8=15 which will further proceed to give the result as 1+5=6.

Code:

import java.util.Scanner;
public class SumOfDigits
{
    public static void main(String[] args)
    {    
         int sum=0,rem=0;
         Scanner sc=new Scanner(System.in);
         System.out.println("Enter any Number:");
         int n=sc.nextInt();
          while(n > 0)
          {
                     while(n != 0)
                     {
                          rem = n%10;
                          sum = sum+rem;
                          n=n/10;
                     }
                     if(sum > 9)
                     {
                            n = sum;
                            sum = 0;
                     }
           }
          System.out.println("Sum: "+sum);
          sc.close();
    }  
}

Program to find the Previous date of an Entered Date.

Explanation :
1)If input = 12/12/1995 then output will be 11/12/1995.
2)If input = 1/1/1995 then output will be 31/12/1994.
3)If input = 31/11/1995 then output will be Invalid as November has only 30 days.
4)If input = 29/02/1995 then output will be Invalid as 1995 is not a Leap year.
5)If input = 1/03/1996 then output will be 29/02/1996 as 1996 is a Leap year.

Code:

import java.util.*;
public class Previousday
{
   public static void display(int d,int m,int y)
   {
       System.out.print("Previous day of Entered date is:"+d+ "-"+m+"-"+y);
   }
 
   public static void main(String args[])
   {
      System.out.println("Enter the date in DD-MM-YYYY Format:");
      Scanner sc=new Scanner(System.in);
      String s=sc.next();
      sc.close();
      StringTokenizer st=new StringTokenizer(s,"-/ ");
      int d=Integer.parseInt(st.nextToken());
      int m=Integer.parseInt(st.nextToken());
      int y=Integer.parseInt(st.nextToken());
      if(d==1)
      {
          if(m==1)
          {
              d=31;m=12;y=y-1;display(d,m,y);
          }
          else if(m==3)
          {
              if((y % 400 == 0) || ((y % 4 == 0) && (y % 100 != 0)))
              {
                  d=29;m-=1;display(d,m,y);
              }
              else
              {
                  d=28;m-=1;display(d,m,y);
              }
          }
          else if(m==2 || m==4 ||m==6 ||m==8 ||m==9 || m==11)
          {
              d=31;m=m-1;display(d,m,y);
          }
          else if(m==5||m==7||m==10||m==12)
          {
              d=30;m=m-1;display(d,m,y);
          }
          else System.out.print("Invalid date Format");
      }
      else if(d>1 && d<=31)
      {
          if(m==2 && d<=29)
          {
              if(d==29)
              {
                 if((y % 400 == 0) || ((y % 4 == 0) && (y % 100 != 0)))
                 {
                   d=d-1;display(d,m,y);
                 }
                 else System.out.print("Invalid date Format");
              }
              else
              {
                  d=d-1;display(d,m,y);
              }
          }
          else if((m==1 ||m==3||m==5||m==7||m==8||m==10||m==12) && d<=31)
          {
              d=d-1;display(d,m,y);
          }
          else if((m==4||m==6||m==9||m==11) && d<=30)
          {
              d=d-1;display(d,m,y);
          }
          else System.out.print("Invalid date Format");
      }
      else System.out.print("Invalid date Format");
   }
}

Thursday, 16 June 2016

Program to concatenate two strings.

Conditions :
1)If s1 or s2 is null then print "Error".
2)If s1=abc ,s2=de then print "deabcde".
3)If s1=xy,s2=abc then print "xyabcxy".
4)If s1=abc,s2=xyz then print "axbycz".

Code:

public class WeaveingString
{
  public static void main(String[] args)
  {
     System.out.println(weaveingStrings("abc", "xyz")); 
   }
  
  public static String weaveingStrings(String s1, String s2) 
 {
    String s3=" ";
    if(s1=="" || s2 =="")
    {
       s3=(String)(s3+"Error");
       return s3;
     }
    else if(s1.length()>s2.length())
    {
       s3=(String)s2+s1+s2;
       return s3; 
     }
     else if(s1.length()<s2.length())
    {
       s3= (String)s1+s2+s1;
       return s3;
      }
      else
     {
        char i1[]=s1.toCharArray();
        char i2[]=s2.toCharArray();
        for(int i=0;i<s1.length();i++)
       {
            s3+=(char)i1[i];
            s3+=(char)i2[i];
        }
         return s3;
       }
    }
}

Wednesday, 15 June 2016

Program to find the least among 4 numbers.

If 20,33,5,77 are the given numbers then 5 must be returned.

Code:

public class LeastNumberFrom4
{
    public static void main(String[] args)
   {
        int n1 = 20;
        int n2 = 33;
        int n3 = 5;
        int n4 = 77;
        System.out.println(getLeastNumber(n1, n2, n3, n4));
    }

    public static int getLeastNumber(int num1 , int num2, int num3, int num4)
   {
         int least;
         int[] n = {num1,num2,num3,num4};
         least = Integer.MAX_VALUE;
         for(int i =0;i<n.length;i++)
         {
            if(least > n[i])
             {
                        least = n[i];
              }
          }
             return least;
     }
 }

Program to reverse an Integer using StringBuffer class.

If n1=16, n2=26 then output must be 321.
Explanation: 16,26 should be reversed as 61,62 and added.
Then addition result should be reversed and printed.    

Code:

public class Stringbuffer
{
   public static void main(String[] args)
  {
        StringBuffer sb=new StringBuffer("16");
        StringBuffer sb1=new StringBuffer("26");
        StringBuffer sb2;
       
        sb.reverse();
        sb1.reverse();
       
        String s=sb.toString();
        int n1=Integer.parseInt(s);
       
        String s1=sb1.toString();
        int n2=Integer.parseInt(s1);
       
        int n3=n1+n2;
               
        sb2=new StringBuffer();
        sb2.append(n3);
        sb2.reverse();
        String s3=sb2.toString();
        int n4=Integer.parseInt(s3);
        System.out.println(n4);
    }
}