1. Write a program to input a binary number and convert it to its decimal equivalent.  Display both the numbers

public class A {

    public static int retrieveDecimal(int binarynumber) {

        int decimalnumber = 0;

        int power = 0;

        while (true) {

            if (binarynumber == 0) {

                break;

            } else {

                int temp = binarynumber % 10;

                decimalnumber += temp * Math.pow(2, power);

                binarynumber = binarynumber / 10;

                power++;

            }

        }

        return decimalnumber;

    }

    public static void main(String args[]) {

        System.out.println("Decimal value is: " + retrieveDecimal(1110));

        System.out.println("Decimal value is: " + retrieveDecimal(0010));

        System.out.println("Decimal value is: " + retrieveDecimal(1010));

        System.out.println("Decimal value is: " + retrieveDecimal(0110));

        System.out.println("Decimal value is: " + retrieveDecimal(1101));

    }

}


  1. Write a program to input a decimal number and convert it to its decimal equivalent.

class GFG

{

    // function to convert decimal to binary

    static void decToBinary(int n)

    {

        // array to store binary number

        int[] binaryNum = new int[1000];

   

        // counter for binary array

        int i = 0;

        while (n > 0)

        {

            // storing remainder in binary array

            binaryNum[i] = n % 2;

            n = n / 2;

            i++;

        }

   

        // printing binary array in reverse order

        for (int j = i - 1; j >= 0; j--)

            System.out.print(binaryNum[j]);

    }

     

    // driver program

    public static void main (String[] args)

    {

        int n = 17;

          System.out.println("Decimal - " + n);

        System.out.print("Binary - ");

          decToBinary(n);

    }

}


  1. Design a class ArmNum to check if a given number is an Armstrong number or not. [A number is said to be Armstrong if sum of its digits raised to the power of length of the number is equal to the number]

Example: 371 = 33 + 73 + 13

import java.util.*;

public class Armstrong {

    public static void main()  {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter a number");

        int num = sc.nextInt();

                String num2 = num + "";

                int nod = num2.length();

                

        int number, digit, sum = 0;

        number = num;

        while (number != 0) {

            digit = number % 10;

            sum = sum + Math.pow(digit, nod);

            number /= 10;

        }

        if (sum == num)

            System.out.println(num + " is an Armstrong number");

        else

            System.out.println(num + " is not an Armstrong number");

    }

}


  1. Write a program to initialize a single dimensional array ar[ ] of 12 integers. Store all even integers of array ar[ ] from left to right and all odd integers from right to left in another array br[ ]. Print both the arrays.

Example:

Array ar[ ] = 3, 6, 9, 5, 12, 14, 8, 18, 7, 21, 10, 4

Output : Array br[ ] = 6, 12, 14, 8, 18, 10, 4, 21, 7, 5, 9, 3

public class MyClass {

    public static void main(String args[]) {

     int a[] = {3, 6, 9, 5, 12, 14, 8, 18, 7, 21, 10, 4 };

     int len = a.length;

     int b[] = new int[len];

     int k=0, p=len-1;

     System.out.println("Original Array: ");

     displayArray(a);

     

     for(int i = 0; i<len; i++)

     {

         int key = a[i];

         if(key % 2 == 0)

         {

             b[k] = key;

             k++;

         }

         else

         {

             b[p] = key;

             p--;

         }

         

     }

     

     System.out.println("\n\nNew Array: ");

     displayArray(b);

    }

    static void displayArray(int a[])

    {

        for(int i=0; i < a.length; i++)

            System.out.print(a[i] + "\t");

    }

}


  1. Write a program to input a two dimensional array of 4 rows and 5 columns. Print the array in the form of a matrix of the same order. Also print the greatest and smallest integers. from the array and also print their average.

import java.util.Scanner;

public class MyClass {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);

        int a[][] = new int[4][5];

        System.out.println("Enter elements of the 2d array: ");

        int sum = 0, max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;

                

        for (int i = 0; i < 4; i++) {

            for (int j = 0; j < 5; j++) {

                a[i][j] = sc.nextInt();

                int key = a[i][j];

                sum += key;

                if (key > max)

                    max = key;

                if (key < min)

                    min = key;

            }

        }

        double avg = sum / 20;

        System.out.println("You have enterd: ");

        displayArray(a);

        System.out.println("Max Number: " + max);

        System.out.println("Min Number: " + min);

        System.out.println("Average: " + avg);

    }

    static void displayArray(int a[][]) {

        for (int i = 0; i < 4; i++) {

            for (int j = 0; j < 5; j++) {

                System.out.print(a[i][j] + "\t");

            }

            System.out.println();

        }

    }

}


  1. Write a program to input a sentence. Count and print the occurrence/frequency of a word “good” or “GOOD” from the sentence. Each word in the sentence contains either all small letters or all capital letters.

public class MyClass {

    public static void main(String args[]) {

        String s = "Today is a good day good", word = "";

        s += " ";

        s = s.toUpperCase();

        int count = 0;

        for (int i = 0; i < s.length(); i++) {

            char ch = s.charAt(i);

            if (ch != ' ')

                word += ch;

            else {

                if (word.equals("GOOD"))

                    count++;

                word = "";

            }

        }

        System.out.println(count);

    }

}


  1. Input a string. Convert in upper case and shift each letter of the English alphabet one step towards right. Characters other than the alphabet remain the same. Print original and new string in two different lines with suitable documentation.

Example :

Input :   ZEBRAS ARE FOUND IN THE FOREST

Output: AFCSBT BSF GPVOE JO UIF GPSFTU

public class MyClass {

    public static void main(String args[]) {

        String s = "Today is a go^od $day good", word = "";

        s += " ";

        s = s.toUpperCase();

        System.out.println(s);

        for (int i = 0; i < s.length(); i++) {

            char ch = s.charAt(i);

            if (Character.isLetter(ch)) {

                if (ch == 'Z')

                    ch = 'A';

                else

                    ch++;

            }

            System.out.print(ch);

        }

    }

}


  1. Write a function void getNumbers(int d[ ]) which takes an array d[ ] as argument with 20 integers. Arrange the array in descending order using Bubble sort method. Print the array before and after sorting.

import java.util.Scanner;

public class MyClass {

    public static void main(String args[]) {

        int a[] = new int[20];

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter 20 elements of the array: ");

        for (int i = 0; i < 20; ++i)

            a[i] = sc.nextInt();

        System.out.println("Before Sorting ");

        printArray(a);

        getNumbers(a);

        System.out.println("After Sorting ");

        printArray(a);

    }

    static void getNumbers(int arr[]) {

        int n = arr.length;

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

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

                if (arr[j] > arr[j + 1]) {

                    // swap temp and arr[i]

                    int temp = arr[j];

                    arr[j] = arr[j + 1];

                    arr[j + 1] = temp;

                }

    }

    /* Prints the array */

    static void printArray(int arr[]) {

        int n = arr.length;

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

            System.out.print(arr[i] + " ");

        System.out.println();

    }

}


  1. Write a program to input a long integer in num. Print the frequency of each digit present in num.

import java.util.Scanner;

public class MyClass {

    public static void main(String args[]) {

        System.out.println("Enter a number");

        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        int b[] = printFreq(n);

        for (int i = 0; i < b.length; i++)

            if (b[i] != 0)

                System.out.println(i + " " + b[i]);

    }

    static int[] printFreq(int n) {

        int a[] = new int[10];

        while (n > 0) {

            int d = n % 10;

            switch (d) {

                case 1:

                    a[1]++;

                    break;

                case 2:

                    a[2]++;

                    break;

                case 3:

                    a[3]++;

                    break;

                case 4:

                    a[4]++;

                    break;

                case 5:

                    a[5]++;

                    break;

                case 6:

                    a[6]++;

                    break;

                case 7:

                    a[7]++;

                    break;

                case 8:

                    a[8]++;

                    break;

                case 9:

                    a[9]++;

                    break;

                case 0:

                    a[0]++;

                    break;

            }

            n = n / 10;

        }

        return a;

    }

}


  1. The sum of two distances is calculated as :

Distance 1 = 10 feets                         24 inches

Distance 2 = 5 feets                         16 inches

Sum of distances = 18 feets                 4 inches

A class Distance has following members :

Instance variable/data members : f1, f2 (integers to store two feet values)

n1, in2 (integers to store two inches).

Member function/methods :

(i) public Distance(int f, int n1, int ff, int n2)- constructor to initialize f to f1,i n1 to in1, ff to f2, n2 to in2.

(ii) public void showdistance( ) - to display both the distances with suitable message.

(iii) public void Sum0fDistance( ) - to find sum of distances

class Distance {

    int f1,f2,in1,in2;

    int totalFeet, totalInches;

    Distance(int f, int n1, int ff, int n2)

    {

        f1 = f;

        in1 = n1;

        f2 = ff;

        in2 = n2;

    }

    public void showDistance() {

        System.out.println("Distance 1: " + f1 + " feet " + in1 + " inches");

        System.out.println("Distance 2: " + f2 + " feet " + in2 + " inches");

        System.out.println("Total Feet: " + totalFeet + "\tTotal Inches: " + totalInches);

    }

    public void SumOfDistance() {

        totalFeet = f1 + f2;

        totalInches = in1 + in2;

    }

   

    public static void main() {

        Distance D1 = new Distance(12,5,14,6);

        D1.SumOfDistance();

        D1.showDistance();

    }

}


  1. Write a menu driven program to perform following operations using switch-case.

(i) Input the limit of series N. Print Fibonacci numbers upto N terms using do-while loop. At the end print sum of all Fibonacci numbers upto N. The Fibonacci numbers are generated by assigning two numbers as 0 and 1 then every third number is sum of two previous numbers. Example: Input N = 7 Output: 0, 1, 1, 2, 3, 5, 8 Sum of all the terms = 20

(ii) Print the following series upto 6 terms. Example: 1, 11, 111, 1111, 11111, 111111

import java.util.Scanner;

class A

{

        static void main()

        {

                Scanner sc = new Scanner(System.in);

                System.out.println("--Menu--");

                System.out.println("1. Fibonacci");

                System.out.println("2. Pattern2");

                int choice = sc.nextInt();

                

                switch(choice)

                {

                        case 1: System.out.printn("Enter value of n");

                                        int n = sc.nextInt();

                                        int a = 0, b = 1, sum=a+b, count=2;

                                        System.out.print(a + " " + b);

                                        

                                        do

                                        {

                                                System.out.print(" " + c);

                                                a=b;

                                                b=c;

                                                c=a+b;

                                        }while(count<n)

                                        break;

                        case 2: int p = 0;

                                        

                                        for(int i=0; i<6; i++)

                                        {

                                                p = p * 10 + 1;

                                                System.out.print(p);

                                        }

                                        break;

                        default: System.out.println("Wrong choice");

                }

        }

}


  1. Write a menu driven program to accept an integer number. Check and print whether the number is a Prime-Palindrome or not OR an Armstrong number or not. Make proper use of switch-case.

(i) Prime-Palindrome number: If a number is prime and reads same in reverse and forward, the number is a Prime- Palindrome.

(ii) Armstrong number

import java.util.Scanner;

class A

{

        static void main()

        {

                Scanner sc = new Scanner(System.in);

                System.out.println("--Menu--");

                System.out.println("1. Prime Palindrome");

                System.out.println("2. Armstrong No");

                int choice = sc.nextInt();

                

                switch(choice)

                {

                        case 1: System.out.println("Enter a number");

                                        int n = sc.nextInt();

                                        int count=0;

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

                                        {

                                                if(n % i == 0)

                                                        count++;

                                        }

                                        int t = n, rev=0;

                                        while(t>0)

                                        {

                                                int d = t%10;

                                                rev=rev*10+d;

                                                t=t/10;

                                        }

                                        if(count==2 && rev==n)

                                                System.out.println(n + " is a Prime Palindrome No");

                                        else

                                                System.out.println(n + " is not a Prime Palindrome No");

                                        break;

                        case 2: System.out.println("Enter a number");

                                        int m = sc.nextInt();

                                        int p = m, nod=0, sum=0;

                                        while(p>0)

                                        {

                                                nod++;

                                                p=p/10;

                                        }

                                        

                                        p = m;

                                        while(p>0)

                                        {

                                                int d = p%10;

                                                sum += Math.pow(d, nod);

                                                p/=10;

                                        }

                                        if(sum == m)

                                                System.out.println(m + " is an armstrong no");

                                        else        

                                                System.out.println(m + " is not an armstrong no");

                                        break;

                        default: System.out.println("Invalid input");

                }

        }

}


  1. Write a program to input three sides of a triangle (sl, s2, s3). Using switch-case print whether the triangle is Equilateral, Isosceles, Right angled triangle or Scalene. The program should be used with menu and switch...case.

import java.util.*;

class Triangle

{

    public static void main( )

    {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter 3 sides of triangle ");

        double s1 = sc.nextDouble( );

        double s2 = sc.nextDouble( );

        double s3 = sc.nextDouble( );

        char ch ='0';

        double sq1 = s1 * s1;

        double sq2 = s2 * s2;

        double sq3 = s3 * s3;

        double sum1 = sq1 + sq2;

        double sum2 = sq2 + sq3;

        double sum3 = sq1 + sq3;

        if(s1 == s2 && s2 == s3 )

            ch = 'E';

        if(s1 == s2 || s2 == s3 || s1 == s3)

            ch = 'I';

        if(sum1 == sq3 || sum2 == sq1 || sum3 == sq2)

            ch = 'R';

        if(s1 != s2 && s2!=s3)

            ch = 'S';

       

        switch(ch)

        {

            case 'E': System.out.println("Equilateral triangle"); break;

            case 'T': System.out.println("lsoscless triangle"); break;

            case 'R': System.out.println("Right triangle"); break;

            case 'S': System.out.println("Scalene triangle"); break;

        }

    }

}


  1. Write a program to input an integer n1 and another integer n2. Merge n2 after n1 and store merged number M. Print nl, n2 and merged number M. Example : Input : nl = 24, n2 = 567 Output : M = 24567

public class A {

 

    // Function to concatenate

    // two integers into one

    static int concat(int a, int b)

    {

 

        // Convert both the integers to string

        String s1 = a + "";

        String s2 = b + "";

 

        // Concatenate both strings

        String s = s1 + s2;

 

        // Convert the concatenated string

        // to integer

        int c = Integer.parseInt(s);

 

        // return the formed integer

        return c;

    }

 

    public static void main()

    {

        int a = 23;

        int b = 43;

 

        System.out.println(concat(a, b));

    }

}


  1. Twin Prime numbers are such prime numbers whose difference is always 2

For example : (3,5) (5,7) (11,13)(17,19) etc.

Write a program to print all twin prime numbers between 3 to 300.

import java.util.Scanner;

public class TwinPrime

{

    public static void main(String[] args)

    {

        int a, b;

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a=");

        a = sc.nextInt();

        System.out.print("Enter b=");

        b = sc.nextInt();

        if (prime(a) && prime(b) && (Math.abs(a - b) == 2))

        {

            System.out.println("Twin Prime");

        }

        else

        {

            System.out.println("Not Twin Prime");

        }

    }

    static boolean prime(int n)

    {        

        int i = 2;

        boolean flag = true;

        while (n > i)

        {

            if (n % 2 == 0)

            {

                flag = false;

                break;

            }

            i++;

        }

        return flag;

    }

}


  1. Given a string s, find the length of the longest substring without repeating characters.

Example 1:

Input: s = "abcabcbb"

Output: 3

Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"

Output: 1

Explanation: The answer is "b", with the length of 1.

public class A {

    public int lengthOfLongestSubstring(String s) {

        int n = s.length(), ans = 0;

        Map<Character, Integer> map = new HashMap<>(); // current index of character

        // try to extend the range [i, j]

        for (int j = 0, i = 0; j < n; j++) {

            if (map.containsKey(s.charAt(j))) {

                i = Math.max(map.get(s.charAt(j)), i);

            }

            ans = Math.max(ans, j - i + 1);

            map.put(s.charAt(j), j + 1);

        }

        return ans;

    }

}


  1. Write a program to input two binary numbers and display their addition.

import java.util.Scanner;

public class Example {

        private static Scanner sc;

        

        public static void main(String[] args) {

                sc = new Scanner(System.in);

                

                System.out.println("Enter First and Second Numbers = ");        

                long b1 = sc.nextLong();

                long b2 = sc.nextLong();

                

                int i = 0, carry = 0;

                

                int[] sum = new int[10];

                

                while(b1 != 0 || b2 != 0)

                {

                        sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2);

                        carry    = (int)((b1 % 10 + b2 % 10 + carry) / 2);

                        b1 /= 10;

                        b2 /= 10;

                }

                if(carry != 0)

                {

                        sum[i++] = carry;

                }

                --i;

                System.out.print("\nThe Total of the above Two = ");

                while(i >= 0)

                {

                        System.out.print(sum[i--]);

                }

                System.out.println();

        }

}


  1. Write a program to input two numbers and print their HCF and LCM

import java.util.Scanner;

public class A{

   public static void main(String args[]){

      int temp1, temp2, num1, num2, temp, hcf, lcm;

      Scanner scanner = new Scanner(System.in);

      System.out.print("Enter First Number: ");

      num1 = scanner.nextInt();

      System.out.print("Enter Second Number: ");

      num2 = scanner.nextInt();

      scanner.close();

      temp1 = num1;

      temp2 = num2;

      while(temp2 != 0){

         temp = temp2;

         temp2 = temp1%temp2;

         temp1 = temp;

      }

      hcf = temp1;

      lcm = (num1*num2)/hcf;

      System.out.println("HCF of input numbers: "+hcf);

      System.out.println("LCM of input numbers: "+lcm);

   }

}


  1. Write a Java program to get the character at the given index within the String.

Sample Output:

Original String = Java Exercises!                                                                            

The character at position 0 is J                                                                              

The character at position 10 is i

import java.util.Scanner;

public class A

{

    public static void main()

    {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter a string ");

        String str = sc.nextLine();

        System.out.println("\nOriginal String = " + str);

       

        System.out.println("\nChoose an index between 0 and " + (str.length()-1));

       

        int index=sc.nextInt();

        System.out.println("\nThe character at position " + index + " is " + str.charAt(index));

    }

}


  1. Write a Java program to test if a given string contains the specified sequence of char values.

Sample Input: and

Original String: Java Exercises and Python Exercises                                                          

Specified sequence of char values: and                                                                        

true

public class A {

    public static void main(String[] args)

    {

        String str1 = "This is a test of reality";

        String str2 = "est";

        System.out.println("Original String: " + str1);

        System.out.println("Specified sequence of char values: " + str2);

        System.out.println(str1.contains(str2));

    }

}


Project:

//Program Author: Rishikesh Sahani"

import java.io.*;  

import java.util.Scanner;

public class Movie

{

    int choice, noOfAvailableSeats;

    Scanner sc;

    public static void main()

    {

        Movie obj = new Movie();

        do

        {

            obj.displayMenu();

            obj.getChoice();

            switch(obj.choice)

            {

                case 1: obj.bookTicket();

                    break;

                case 2: obj.cancelTicket();                    

                    break;

                case 3: obj.showAvailable(true);

                    break;

                case 4: obj.resetSeats();

                    break;

                case 5: System.out.println("\n*****Program Terminated*****");

                        System.exit(0);

                default: System.out.println("Invalid Choice!! Try Again!!");

            }

        }while(obj.choice != 5);

       

    }

    void getChoice()

    {

        System.out.print("\n\nPlease enter your choice: ");

        sc = new Scanner (System.in);

        choice = sc.nextInt();

        sc.close();

    }

    void displayMenu()

    {

        System.out.println("\n\n\n\n---Movie Ticket Booker---");

        System.out.println("--------------------------");

        System.out.println("|   1.Book a ticket      |");

        System.out.println("|   2.Cancel a ticket    |");

        System.out.println("|   3.Check Availability |");

        System.out.println("|   4.Reset Seats        |"); //cancel all tickets

        System.out.println("|   5.Exit               |");

        System.out.println("--------------------------");

    }

    void showAvailable(boolean printSeats)

    {

        try

        {

            File myObj = new File("d:\\movie.txt");

            Scanner myReader = new Scanner(myObj);

            while (myReader.hasNextInt())

            {

                String data = myReader.nextLine();

                noOfAvailableSeats = Integer.valueOf(data);

                System.out.println("\nTotal Seats Available: " + noOfAvailableSeats);

            }

            myReader.close();

            if(printSeats)

                printSeats();

        }

        catch (FileNotFoundException e)

        {

            System.out.println("An error occurred.");

            e.printStackTrace();

        }

    }

    void printSeats()

    {

        int count=0;

        System.out.println();

        for(int i=1;i<=noOfAvailableSeats; i++)

        {

            System.out.print("\u2b1b\t");

            count++;

            if(count == 10)

            {

                System.out.println("\n");

                count=0;

            }

        }

    }

    void cancelTicket()

    {

        showAvailable(true); //read/update number of seats available in noOfAvailableSeats variable

        sc = new Scanner(System.in);

        System.out.print("\n\nEnter how many tickets to cancel: ");

        int not = sc.nextInt(); //no of tickets need to be cancelled

        sc.close();

       

        if(not + noOfAvailableSeats > 100)

        {

            System.out.println("Tickets not cancelled. Maximum Tickets that can be cancelled is: " + (100 - noOfAvailableSeats));

        }

        else

        {

            noOfAvailableSeats += not;

            try

            {

                FileWriter myWriter = new FileWriter("d:\\movie.txt");

                myWriter.write(noOfAvailableSeats+"");

                myWriter.close();

                System.out.println(not + " tickets successfully cancelled!!\n\n");

                printSeats();

            }

            catch (IOException e)

            {

                System.out.println("An error occurred.");

                e.printStackTrace();

            }

        }

    }

    void bookTicket()

    {

        showAvailable(true); //read/update number of seats available in noOfAvailableSeats variable

        if(noOfAvailableSeats == 0)

        {

            System.out.println("\nAll tickets booked out. Sorry!!\n");

            return;

        }

       

        sc = new Scanner(System.in);

        System.out.print("\n\nEnter how many tickets: ");

        int not = sc.nextInt(); //no of tickets need to be booked

        sc.close();

       

        if(not <= noOfAvailableSeats)  //no of tickets needed should be less than available seats

        {

            noOfAvailableSeats = noOfAvailableSeats - not;

            try

            {

                FileWriter myWriter = new FileWriter("d:\\movie.txt");

                myWriter.write(noOfAvailableSeats+"");

                myWriter.close();

                System.out.println(not + " tickets successfully booked!! Enjoy the movie!!\n\n");

                printSeats();

            }

            catch (IOException e)

            {

                System.out.println("An error occurred.");

                e.printStackTrace();

            }

        }

        else

        {

            System.out.println("\nNo. of tickets should be less than " + noOfAvailableSeats);

            printSeats();

        }

    }

    void resetSeats()

    {

        try

        {

            FileWriter myWriter = new FileWriter("d:\\movie.txt");

            myWriter.write("100");

            myWriter.close();

            System.out.println("Reset complete!");

        }

        catch (IOException e)

        {

            System.out.println("An error occurred.");

            e.printStackTrace();

        }

    }

}