Challenging Java programs and succeeding in coding interviews-10

In part 10 of java programs and succeeding in coding interviews. we tackle a range of programming challenges, including binary tree programs, finding the Nth Fibonacci number, displaying a 2-D matrix, working with inheritance, overriding methods, and overloading methods.

By mastering these Java programming concepts, you’ll be better equipped to handle the technical challenges presented during coding interviews and improve your chances of success. So, dive in and enhance your Java programming skills!

Write a program to check if a binary tree is a binary search tree or not in Java

public class JavaTechypid {

    static class Node {
        int data;
        Node left, right;

        public Node(int item) {
            data = item;
            left = right = null;
        }
    }

    static class BinaryTree {
        Node root;

        boolean isBST() {
            return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
        }

        boolean isBSTUtil(Node node, int min, int max) {
            if (node == null)
                return true;

            if (node.data < min || node.data > max)
                return false;

            return (isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max));
        }
    }

    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(4);
        tree.root.left = new Node(2);
        tree.root.right = new Node(5);
        tree.root.left.left = new Node(1);
        tree.root.left.right = new Node(3);

        if (tree.isBST())
            System.out.println("Binary tree is a BST");
        else
            System.out.println("Binary tree is not a BST");
    }
}

Output:

Binary tree is a BST

Explanation Of Above Java Code:

Here, we first define a class Node to represent a node in a binary tree. The Node class contains the data of the node and pointers to its left and right children.

Next, we define a class BinaryTree to represent the binary tree. The BinaryTree class contains a pointer to the root of the tree, and a method isBST that returns true if the binary tree is a binary search tree, and false otherwise.

The isBST method calls a recursive helper method isBSTUtil that checks if the tree rooted at a given node is a binary search tree or not.

The isBSTUtil method takes in the node, the minimum and maximum values that the data in the node can take, and returns true if the tree rooted at the given node is a binary search tree and false otherwise.

In the main method, we create a binary tree, and check if it is a binary search tree using the isBST method.

If the tree is a binary search tree, we print a message saying so, otherwise we print a message saying that the tree is not a binary search tree.

Write a Java program to generate the Nth Fibonacci number using iteration

public class JavaTechypid {
    public static int fib(int n) {
        if (n <= 1) {
            return n;
        }
        int fib = 1;
        int prevFib = 1;
        for (int i = 2; i < n; i++) {
            int temp = fib;
            fib += prevFib;
            prevFib = temp;
        }
        return fib;
    }

    public static void main(String[] args) {
        int n = 10;
        System.out.println("The " + n + "th Fibonacci number is: " + fib(n));
    }
}

Output:

The 10th Fibonacci number is: 55

Explanation Of Above Java Code:

In this code, we use a loop to iterate through all Fibonacci numbers up to the Nth number.

We start with fib = 1 and prevFib = 1 (since the first two Fibonacci numbers are 1), and then calculate the next Fibonacci number by adding prevFib to fib and storing the result in fib.

We update prevFib to the old value of fib before moving on to the next iteration. Finally, we return the value of fib for the Nth Fibonacci number.

Write a Java program to input and display a 2-D matrix

import java.util.Scanner;

public class JavaTechypid {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        
        // Input number of rows and columns
        System.out.print("Enter number of rows: ");
        int rows = sc.nextInt();
        System.out.print("Enter number of columns: ");
        int cols = sc.nextInt();
        
        int[][] matrix = new int[rows][cols];
        
        // Input matrix elements
        System.out.println("Enter matrix elements:");
        for(int i=0; i<rows; i++) {
            for(int j=0; j<cols; j++) {
                matrix[i][j] = sc.nextInt();
            }
        }
        
        // Display matrix
        System.out.println("Matrix:");
        for(int i=0; i<rows; i++) {
            for(int j=0; j<cols; j++) {
                System.out.print(matrix[i][j] + "\t");
            }
            System.out.println();
        }
    }

}

Output:

Enter number of rows: 2
Enter number of columns: 3
Enter matrix elements:
0
1
2
3
4
5
Matrix:
0       1       2
3       4       5

Explanation Of Above Java Code:

In this program, we first ask the user to input the number of rows and columns of the matrix.

We then create a 2-D array of the specified size and use nested loops to input the matrix elements from the user.

Here, two integer variables rows and columns are declared and initialized by taking input from the user for the number of rows and columns of the matrix.

Next, a 2D integer array matrix is declared with the size of rows and columns.

A nested for loop is used to take input from the user for each element of the matrix using the nextInt() method of the Scanner class.

Finally, another nested for loop is used to display the matrix on the console and The outer loop iterates over each row of the matrix and the inner loop iterates over each column of the matrix.

Write a java program that demonstrates inheritance

// Parent class
class Vehicle {
   void display() {
      System.out.println("This is a vehicle");
   }
}

// Child class inheriting from Vehicle
class Car extends Vehicle {
   void display() {
      System.out.println("This is a car");
   }
}

// Main class
class JavaTechypid {
   public static void main(String args[]) {
      Vehicle vehicle = new Vehicle(); // creating object of parent class
      Car car = new Car(); // creating object of child class
      vehicle.display(); // calling method of parent class
      car.display(); // calling method of child class
   }
}

Output:

This is a vehicle
This is a car

Explanation Of Above Java Code:

In the above example, we have a parent class Vehicle and a child class Car that inherits from the Vehicle class.

The Vehicle class has a method display() that prints “This is a vehicle” to the console.

The Car class also has a method display() that overrides the Vehicle class method and prints “This is a car” instead.

In the Main class, we create an object of the Vehicle class and an object of the Car class.

We then call the display() method on each object, which demonstrates that the Car class is inheriting the display() method from the Vehicle class and overriding it with its own implementation.

Write a program to demonstrate method overriding in Java

class Animal {
   public void makeSound() {
      System.out.println("The animal makes a sound");
   }
}

class Cat extends Animal {
   @Override
   public void makeSound() {
      System.out.println("Meow");
   }
}

public class JavaTechypid {
   public static void main(String[] args) {
      Animal animal = new Animal();
      animal.makeSound(); // output: The animal makes a sound

      Cat cat = new Cat();
      cat.makeSound(); // output: Meow

      Animal anotherAnimal = new Cat();
      anotherAnimal.makeSound(); // output: Meow
   }
}

Output:

The animal makes a sound
Meow
Meow

Explanation Of Above Java Code:

In this example, we have a superclass Animal with a method makeSound().

We then create a subclass Cat that inherits from Animal and overrides the makeSound() method to make a “meow” sound instead.

In the main method, we first create an Animal object and call the makeSound() method, which outputs “The animal makes a sound”.

Then we create a Cat object and call the makeSound() method, which outputs “Meow”.

Finally, we create an Animal object and assign it a Cat instance, and call the makeSound() method, which outputs “Meow”.

This demonstrates that the overridden method in the Cat class is called instead of the one in the Animal class when called on a Cat object or a variable of type Animal that points to a Cat object.

Write a program to demonstrate method overloading in Java

public class JavaTechypid {
    
    // method with one parameter
    public static void print(int num) {
        System.out.println("Printing an integer: " + num);
    }
    
    // method with two parameters of different types
    public static void print(int num, String str) {
        System.out.println("Printing an integer and a string: " + num + ", " + str);
    }
    
    // method with two parameters of the same type
    public static void print(String str1, String str2) {
        System.out.println("Printing two strings: " + str1 + ", " + str2);
    }
    
    public static void main(String[] args) {
        // calling the overloaded methods
        print(10);
        print(20, "Hello");
        print("Java", "Programming");
    }
}

Output:

Printing an integer: 10
Printing an integer and a string: 20, Hello
Printing two strings: Java, Programming

Explanation Of Above Java Code:

In this program, we have defined three methods with the same name print(), but with different parameters.

The first print() method takes an integer as input, the second print() method takes an integer and a string as inputs, and the third print() method takes two strings as inputs.

We then call these methods from the main() method with different parameters to demonstrate how Java automatically selects the appropriate method to call based on the parameters provided.

Leave a Reply