20 Must Practice basic Java Programs for beginners

20 Must Practice basic Java Programs for beginners

  1. Write a program to swap two numbers in Java.
    Ans. Two ways to do this -with third variable and without third variable.

    public static void swapNumberswithtemp(int a, int b) { //using 3rd variable
    int temp = a;
    a = b;
    b = temp;
    }
    public static void swapNumberswithouttemp(int a, int b) {//without using 3rd variable
    b = b + a;
    a = b - a;
    b = b - a;
    }
    public static void main(String[] args) {
    int a = 10;
    int b = 20;
    swapNumbers(a, b);
    System.out.printf("%d %d", a, b); 
  2. Write a program to print all the elements of Fibonacci series.
    Ans. A Fibonacci series is given by Fib(n)=Fib(n-1)+Fib(n-2)

    public static int fibonacci(int number){
        if(number == 1 || number == 2){ //base case
            return 1;
        }
        return fibonacci(number-1) + fibonacci(number -2); 
    }  
    public static void main(String args[]) {
        int number = new Scanner(System.in).nextInt();
        for(int i=1; i<=number; i++){
            System.out.print(fibonacci2(i) +" ");
        }    
    }
  3. Check if a given number is palindrome or not.
    Ans. A palindrome is a number which is when reversed give the same number. We find the reverse and check whether it is equal to the given number or not.

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        int length = str.length();         
        boolean isPalindrome = true;          
        for(int i = 0; i < length; i++)
        {
            if(str.charAt(i) != str.charAt(length-1-i)) {
                System.out.println("Snot a palindrome.");
                isPalindrome = false;
                break;
            }
        }          
        if(isPalindrome) {
            System.out.println("palindrome.");
        }
    }
  4. Write a program to find whether a number is an Armstrong number or not.
    Ans. Armstrong number – Sum of the cubes of its digit is equal to the number itself. E.g - 153

    public static void main(String[] args) 
    {
        int num = Integer.parseInt(args[0]);
        int temp = num;
        int count = 0;
        int sum = 0;
        while(num > 0)   
        {
            num = num / 10;
            count++;
        }
        num = temp;
        while (num > 0)
        {
            int rem = num % 10;
            int val = 1;
            for(int i = 1; i <= count; i++)
            {   
                val = val * rem;
            }
            num = num / 10;
            sum = sum + val;
        }   
        if(temp == sum)
            {
                System.out.println("Armstrong number");
            }
            else
            {
                System.out.println("Not an armstrong number");
            }   
    }
  5. Find the GCD of two numbers in logn time.
    Ans.

    public static int gcd(int a, int b) {
    while (((a > 0) && (b > 0))) {
      if ((a > b)) {
        a = (a % b);
      } else {
        b = (b % a);
      }
    }
    if ((a == 0)) {
      return b;
    } else {
      return a;
    }
    }  
    public static void main(String[] args) {
    int a = new Scanner(System.in);
    int b = new Scanner(System.in);
    System.out.println(GCD.gcd(a, b));
    }
  6. Write a program to find the sum of n natural numbers
    Ans.

    summation of i from 1 to n=n*(n+1)/2
    public static void main(String arg[]){
                  int n,sum=0;
                  Scanner sc=new Scanner(System.in);
                    sum = (n*(n+1))/2;
                   System.out.println(sum);                  
                }
  7. Write a program to find the lcm of two numbers.
    Ans.

    private static int getGCD(int num1, int num2) {
    while (num2 > 0) {
        int temp = num2;
        num2 = num1 % num2;
        num1 = temp;
    }
    return num1;
    }
    private static int getLCM(int num1, int num2) {
    return num1 * (num2 / getGCD(num1, num2));
    }
  8. Calculate the sum of digits of a given number.
    Ans.

    public static void main(String args[]){
     long number=-9999,input=-9999;
        try{    
           number=Long.parseLong(System.console().readLine());
           input=number;    
        }catch(NumberFormatException nfe){
           System.exit(1);    
          }
        long remainder=0,total=0;
        while(number > 0){
            remainder=number % 10;
            total+=remainder;
            number=number/10;
         }
        System.out.println(total);
    }
  9. Write a program to reverse a string.
    Ans. We use the string buffer class to easily reverse the string

    public static void main(String args[]) {
        String word = "HelloWorld";
        String reverse = new StringBuffer(word).reverse().toString();
        word = "thisisstring";
        reverse = new StringBuilder(word).reverse().toString();
        System.out.printf(reverse);
    }     
    public static String reverse(String source){
        if(source == null || source.isEmpty()){
            return source;
        }       
        String reverse = "";
        for(int i = source.length() -1; i>=0; i--){
            reverse = reverse + source.charAt(i);
        }      
        return reverse;
    }
  10. Can you find the second highest number in given array?
    Ans.

    public static void main(String[] args)
    {
        int arr[] = { 1,4,2,3,5};
        int largest = 0;
        int secondLargest = 0;
        for (int i = 0; i < arr.length; i++)
        {
            System.out.print(arr[i] + "\t");
        }
        for (int i = 0; i  largest)
            {
                secondLargest = largest;
                largest = arr[i];
            }
            else if (arr[i] > secondLargest)
            {
                secondLargest = arr[i];
            }
        }
        System.out.println(secondLargest);
    }
  11. Find the first repeating element In the array.
    Ans.

    void firstrep(int a[], int n) 
    {
        Set set = new HashSet();
        int firstrepeating = -1;
        for (int i = 0; i < n; i++){            
            if (set.contains(a[i])) {
                majority = i;
            } else {
                set.add(a[i]);
            }
        }        
        System.out.println(a[firstrepeating]);
    }
    public static void main(String[] args) 
    {
        int arr[] = {1, 2, 5, 4, 5, 5, 1, 2};
        int n = arr.length;
        firstrep(arr,n);
    }
  12. Write a program to find two elements in the array whose sum is near to zero.
    Ans.

    public static void main (String[] args) 
    {
      int arr[] = {3, 2, -1, 9, -8, 6};
      int size = arr.length;
      int l, r, min_sum, sum, min_l_num, min_r_num;      
      min_l_num = 0;
      min_r_num = 1;
      min_sum = arr[0] + arr[1];      
      for(l = 0; l < size - 1; l++)   {
        for(r = l+1; r  Math.abs(sum))
          {
            min_sum = sum;
            min_l_num = l;
            min_r_num = r;
          }
        }
      }
      System.out.println(arr[min_l_num],arr[min_r_num]);
    }
  13. What is Singleton and write a program to describe it.
    Ans. Singleton class in Java has only one instance in the whole program. We can easily implement a singleton class with thread safe property. We can see the implementation below –

    public class Javasingleton
    {
    private static  volatile Javasingleton  singleinstance;
    private Javasingleton(){}
    public static   Javasingleton  getInstance()
    {
        if (singleinstance ==null )
        {
            synchronized(Javasingleton.class)
            {
                if (singleinstance ==null )
                {
                    singleinstance=new Javasingleton();
                }
            }
        }
        return singleinstance ;
    }
    }
  14. Write a code to print all the first n prime numbers where n will be given as input.
    Ans.

    public static void main(String[] args) {
        int N = 200;
        int k;
        Scanner sc = new Scanner(System.in);
        k = sc.nextInt();
        int i = 0;
        for (int num = 2; num <= N; num++) {
            if (isPrimeNumber(num) && i!=k) {
                System.out.println(num);
                i++;
            }
        }
    }
    public static boolean isPrimeNumber(int num) {
        for (int i = 2; i 0)
          {
            RevNumber=(RevNumber*10)+(n%10);
            n=n/10;
          }
          return  (int) RevNumber;   
        }
  15. Can you write the Bubble Sort Algorithm?
    Ans. The idea is to bubble out the greater numbers to the right.

    public void sort(int[] numbers) {
    validateInput(numbers);
    int length = numbers.length;
    boolean swap = true;
    while (swap) {
      swap = false;
      for (int i = 0; i < length - 1; i++) {
        for (int j = 0; j  numbers[j + 1]) {
            swap(numbers, j, j + 1);
            swap = true;
          }
        }
      }
    }
    }
    }
  16. Implement the merge Sort algorithm.
    Ans. This is a Divide and conquer algorithm.

    public static void main(String[] args) {
        int[] list = {4,5,2,1,3};
        mergeSort(list, 0, list.length - 1);
    }
    public static void mergeSort(int[] a, int first, int last)
      {
        if(last - first == 0) 
        {
        }
        else if (last - first == 1) 
        {
            if(a[first] > a[last])
            {
                int temp = a[first];
                a[first] = a[last];
                a[last] = temp;
            }
        }
        else    
        {
            int mid = (first + last) / 2;
            mergeSort(a, first, mid);
            mergeSort(a, mid + 1, last);
            merge(a, first, mid, last);
        }
      }
    private static void merge(int[] a, int first, int mid, int last)
      {
        int[] temp = new int[last - first + 1];
        int i = first; int j = mid + 1;
        for(int k = first; k  mid || j > last)
            {
                if(i > mid && j <= last)
                {
                    System.out.println("a[j]: " + a[j]);
                    temp[k - first] = a[j];
                    j++;
                }
                else if(i  last)
                {
                    System.out.println("a[i]: " + a[i]);
                    temp[k - first] = a[i];
                    i++;
                }
                else
                {
                    break;
                }
            }
            else
            {
                if(a[i] < a[j])
                {
                    temp[k - first] = a[i];
                    i++;
                }
                else
                {
                    temp[k - first] = a[j];
                    j++;
                }
            }
        }
        for(int count = 0; count < temp.length; count++)
        {
            a[first + count] = temp[count];
        }
      }
  17. Write a program to get the sum of even numbers and odd number in an array.
    Ans.

    public static void main(String[] args) 
    {
        int n, sumeven= 0, sumodd = 0;
        Scanner s = new Scanner(System.in);
        n = s.nextInt();
        int[] a = new int[n];
        for(int i = 0; i < n; i++)
        {
            a[i] = s.nextInt();
        }
        for(int i = 0; i  0)
    {
    bin[i++] = n%2;
       n = n/2;
    }
    for(int j = i-1;j >= 0;j--)
    {
       System.out.print(bin[j]);
    }
    }
  18. Write a program to add two binary numbers.
    Ans.

    public static void main(String[] args)
    {     
    long b1, b2;
    int i = 0, carry = 0;
    int[] sum = new int[10];
    Scanner scanner = new Scanner(System.in);
    b1 = scanner.nextLong();
    b2 = scanner.nextLong();
    while (b1 != 0 || b2 != 0) 
    {
        sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2);
        carry = (int)((b1 % 10 + b2 % 10 + carry) / 2);
        b1 = b1 / 10;
        b2 = b2 / 10;
    }
    if (carry != 0) {
        sum[i++] = carry;
    }
    --i;
    while (i >= 0) {
        System.out.print(sum[i--]);
    }
    System.out.print("\n");  
    }
Previous post Commonly asked interview questions on c
Next post Top 50 Basic interview questions from C

Leave a Reply

Your email address will not be published. Required fields are marked *